-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathviewer.rkt
2439 lines (2235 loc) · 102 KB
/
viewer.rkt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#lang racket
; TODO need to add a warning for files that are not accounted for in
; any manifest even though it is not technically an error in the same
; way that we do for folders
; TODO missing biophsyics as a general appraoch
; TODO remote-organization is currently read-only and is not easy to change/switch
; TODO make manifest report and paths report work from view prod export
; TODO protocols.io renew credientials workflow
; TODO reminder for download to avoid caching probably
; TODO need to refresh when fetch finishes
(require racket/gui
racket/generic
racket/pretty
racket/runtime-path
framework
compiler/compilation-path
compiler/embed
gui-widget-mixins
json
json-view
net/url
(except-in gregor date? date)
(prefix-in oa- orthauth/base)
orthauth/paths
orthauth/python-interop
orthauth/utils
)
(define-runtime-path asdf "viewer.rkt")
(define this-file (path->string asdf))
(define this-file-compiled (with-handlers ([exn? (λ (e) this-file)]) (get-compilation-bytecode-file this-file)))
(define this-file-exe (embedding-executable-add-suffix (path-replace-extension this-file "") #f))
(define this-file-exe-tmp (path-add-extension this-file-exe "tmp"))
(define this-package-path (let-values ([(parent name dir?) (split-path this-file)]) parent))
(when (and this-file-exe-tmp (file-exists? this-file-exe-tmp))
; windows can't remove a running exe ... but can rename it ... and then delete the old
; file on next start
(delete-file this-file-exe-tmp))
(define running? #t) ; don't use parameter, this needs to be accessible across threads
(define update-running? #f)
; true global variables that should not be thread local
(define *current-dataset* #f)
(define *current-datasets* #f)
(define *current-datasets-view* #f)
;; parameters (yay dynamic variables)
(define path-config (make-parameter #f))
(define path-log-dir (make-parameter #f))
(define path-cache-dir (make-parameter #f))
(define path-cache-push (make-parameter #f))
(define path-cache-datasets (make-parameter #f))
(define path-cleaned-dir (make-parameter #f))
(define path-export-dir (make-parameter #f))
(define path-export-datasets (make-parameter #f))
(define path-source-dir (make-parameter #f))
(define url-prod-datasets (make-parameter "https://cassava.ucsd.edu/sparc/datasets"))
(define *current-blob* #f)
(define current-blob
(case-lambda
[() *current-blob*]
[(value) (set! *current-blob* value)]))
(define current-dataset
(case-lambda
[() *current-dataset*]
[(value) (set! *current-dataset* value)]))
(define current-datasets
(case-lambda
[() *current-datasets*]
[(value) (set! *current-datasets* value)]))
(define current-datasets-view
(case-lambda
[() *current-datasets-view*]
[(value) (set! *current-datasets-view* value)]))
(define *current-jview* #f)
(define current-jview
(case-lambda
[() *current-jview*]
[(value) (set! *current-jview* value)]))
(define *current-mode-panel* #f)
(define current-mode-panel ; TODO read from config/history
(case-lambda
[() *current-mode-panel*]
[(value) (set! *current-mode-panel* value)]))
(define overmatch (make-parameter #f))
(define power-user? (make-parameter #f))
(define *allow-update* #f)
(define allow-update?
; "don't set this, it should only be used to keep things in sync with the config"
(case-lambda
[() *allow-update*]
[(value) (set! *allow-update* value)]))
;; TODO add check to make sure that the python modules are accessible as well
(define terminal-emulator
(begin
#;
(sort (environment-variables-names (current-environment-variables)) bytes<?)
(for/or ([emu '("urxvt"
"xfce4-terminal"
"konsole"
"gnome-terminal"
#; ; here's a nickle kid, go buy yourself a real terminal emulator
"xterm")]
[args (list "-cd" ; urxvt
"--default-working-directory" ; xfce4-terminal
"--workdir" ; konsole
"--working-directory" ; gnome-terminal
#; ; xterm
(lambda (ps) (format "-e 'cd \"~a\"; ~a'" ps (getenv "SHELL"))))])
(let ([ep (find-executable-path emu)])
(and ep (list ep args))))))
(define (unix-vt path-string)
(append terminal-emulator (list path-string)))
(define (win-vt path-string)
(list (find-executable-path "cmd") "/c" "start"
"powershell" "-NoLogo" "-WindowStyle" "normal" "-WorkingDirectory" path-string))
(define (macos-vt path-string)
;; oh the horror ... racket -> osascript -> bash/zsh/whoevenknows
;; and yes, users put single quotes in their dataset names ALL THE TIME AAAAAAAAAAAAAAAAAAAAAAAAA
(let* ([ps (string-replace (string-replace path-string "'" "\\'") "\"" "\\\"")]
[horror (format "tell application \"Terminal\" to do script \"cd '~a'\"" ps)])
(list (find-executable-path "osascript") "-e" horror)))
(define (vt-at-path path [os #f])
(case (or os (system-type))
((unix) (unix-vt path))
((macosx) (macos-vt path))
((windows) (win-vt path))))
;; string constants
(define msg-dataset-not-fetched "Dataset has not been fetched yet!")
(define msg-dataset-not-exported "Dataset has not been exported yet!")
(define msg-no-logs "Dataset has no logs.")
(define missing-var "???")
;; other variables
(define include-keys
; have to filter down due to bad performance in the viewer
; this is true even after other performance improvements
'(id meta rmeta status prov submission))
;; python argvs
(define (python-mod-args module-name . args)
(cons (python-interpreter) (cons "-m" (cons module-name args))))
(define argv-simple-for-racket (python-mod-args "sparcur.simple.utils" "for-racket")) ; FIXME needs --project-id probably
(define (argv-simple-for-racket-meta path-string)
; this is peak LOL PYTHON for slowness on startup which makes this completely non-viable
(parameterize ([python-interpreter
(if (string=? (python-interpreter) "pypy3") ; bad startup time ??? no just LOL PYTHON everywhere
"python"
(python-interpreter))])
(python-mod-args "sparcur.simple.utils" "for-racket" "meta" path-string)))
(define (argv-simple-diff ds)
(python-mod-args "sparcur.simple.utils" "for-racket" "diff"
(path->string (dataset-working-dir-path ds))))
(define (argv-simple-make-push-manifest ds updated-transitive push-id)
(python-mod-args "sparcur.simple.utils" "for-racket" "make-push-manifest"
(dataset-id ds) updated-transitive push-id (path->string (dataset-working-dir-path ds))))
(define (argv-simple-push ds updated-transitive push-id)
(python-mod-args "sparcur.simple.utils" "for-racket" "push" (dataset-id ds) updated-transitive push-id
(path->string (dataset-working-dir-path ds))))
(define argv-simple-git-repos-update (python-mod-args "sparcur.simple.utils" "git-repos" "update"))
(define argv-spc-export (python-mod-args "sparcur.cli" "export"))
(define (argv-simple-retrieve ds) (python-mod-args "sparcur.simple.retrieve" "--sparse-limit" "-1" "--dataset-id" (dataset-id ds)))
(define argv-spc-find-meta
(python-mod-args
"sparcur.cli"
"find"
"--name" "*.xml"
"--name" "submission*"
"--name" "code_description*"
"--name" "dataset_description*"
"--name" "subjects*"
"--name" "samples*"
"--name" "sites*"
"--name" "performances*"
"--name" "manifest*"
"--name" "resources*"
"--name" "README*"
"--limit" "-1"
"--fetch"))
(define (argv-clean-metadata-files ds)
(let ([argv (python-mod-args ; XXX note that this is separate from normalize metadata files
"sparcur.simple.clean_metadata_files"
"--dataset-id" (dataset-id ds))])
(if (power-user?) ; FIXME decouple
(append argv '("--log-level" "DEBUG"))
argv)))
(define (argv-open-dataset-shell ds)
(let ([path (dataset-src-path ds)])
(if (directory-exists? path)
(vt-at-path (dataset-working-dir-path ds))
(begin (println msg-dataset-not-fetched) #f))))
(define (xopen-dataset-latest-log ds)
(let ([latest-log-path (dataset-latest-log-path ds)])
(if latest-log-path
(xopen-path latest-log-path)
(begin (println msg-no-logs) #f))))
(define (argv-download-everything ds)
(python-mod-args
"sparcur.simple.fetch_files"
"--extension" "*"
(dataset-working-dir-path ds)))
(define (argv-open-export-ipython ds)
(let*-values ([(path) (dataset-export-latest-path ds)]
[(parent name dir?) (split-path path)]
[(path-meta-path) (build-path parent "path-metadata.json")]
[(python-code) ; LOL PYTHON can't use with in the special import line syntax SIGH
(format "import json;print('~a');f = open('~a', 'rt');\
blob = json.load(f);f.close();f = open('~a', 'rt');\
path_meta = json.load(f);f.close()"
parent path path-meta-path)])
(if (directory-exists? parent)
(append (unix-vt parent)
(cons "-e" ; FIXME running without bash loses readline somehow
(cons "rlwrap"
(python-mod-args
"IPython"
"-i" "-c"
python-code))))
(begin (println msg-dataset-not-exported) #f))))
(define path-getfattr (find-executable-path "getfattr"))
(define (argv-getfattr path-string) (list path-getfattr "-d" path-string))
;; utility functions
(define --sigh (gensym))
(define (py-system* exe #:set-pwd? [set-pwd? --sigh] . args)
(call-with-environment
(λ ()
(if (eq? set-pwd? --sigh)
(apply system* exe args)
(apply system* exe args #:set-pwd? set-pwd?)))
'(("PYTHONBREAKPOINT" . "0")
; silence error logs during pennsieve top level import issue
("PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION" . "python"))))
(define (datetime-file-system-safe inexact-seconds)
"Y-M-DTHMS,6Z" ; FIXME this is producing garbages results with weird and bad padding
(let ([d (seconds->date inexact-seconds #f)])
(string-join
(map (λ (e) (format "~a" e))
(list
(date-year d)
"-"
(date-month d)
"-"
(date-day d)
"T"
(date-hour d)
(date-minute d)
(date-second d)
","
(inexact->exact (truncate (/ (date*-nanosecond d) 1e3)))
"Z"
))
"")))
#; ; broken due to padding issues above
(define (datetime-for-path-now)
(datetime-file-system-safe
(/ (current-inexact-milliseconds) 1e3)))
(define time-format-friendly "YYYY-MM-dd'T'HHmmss,SSSSSSX")
(define (datetime-for-path-now)
(~t (posix->moment (/ (current-inexact-milliseconds) 1e3) "Etc/UTC") time-format-friendly))
#; ; sigh
(define (in-cwd-thread argv cwd)
; FIXME not quite right because we need to be able to run multiple things in a row
; it would have to be a list of argv cwd pairs or we just use this for the oneoffs
(thread
(thunk
(let ([status #f])
(parameterize ([current-directory cwd])
(values
(with-output-to-string
(thunk (set! status (apply system* argv #:set-pwd? #t))))
status))))))
(define (path->json path)
(let ([path (expand-user-path (if (path? path) path (string->path path)))])
(with-input-from-file path
(λ () (read-json)))))
(define (url->json url)
(call/input-url
(string->url url)
get-pure-port
read-json))
(define (resolve-relative-path path)
"Resolve a symlink to a relative path from the parent folder of the symlink."
; simple-form-path calls path->complete-path internally, which we don't want
; also have to tell simplify-path not to use the file system
(if (link-exists? path)
(path->complete-path (resolve-path path) (simplify-path (build-path path 'up) #f))
(error 'non-existent-path "cannot resolve a non-existent link ~a" path)))
(define (object->methods obj)
(interface->method-names (object-interface obj)))
(define (populate-datasets)
(let* ([pcd (path-cache-datasets)]
[result (if (file-exists? pcd)
(with-input-from-file pcd
(λ () (read)))
(begin
(let ([pc-dir (path-cache-dir)])
(unless (directory-exists? pc-dir)
; `make-directory*' will make parents but
; only if pc-dir is not a relative path
(make-directory* pc-dir)))
(let ([result (get-dataset-list)])
(with-output-to-file pcd
#:exists 'replace ; yes if you run multiple of these you could have a data race
(λ () (pretty-write result)))
; just to confuse everyone
result))
)]
[datasets (result->dataset-list result)])
(current-datasets datasets)
(set-datasets-view! lview (current-datasets)) ; FIXME TODO have to store elsewhere for search so we
result))
(define (ensure-directory! path-dir)
(unless (directory-exists? path-dir)
(make-directory* path-dir)))
(define (init-paths!)
"initialize or reset the file system paths to cache, export, and source directories"
; FIXME 'cache-dir is NOT what we want for this as it is ~/.racket/
; FIXME more cryptic errors if sparcur.simple isn't tangled
; FIXME it should be possible for the user to configure path-source-dir
(parameterize ([oa-current-auth-config-path (python-mod-auth-config-path "sparcur")])
(define ac (oa-read-auth-config))
(path-config (build-path (expand-user-path (user-config-path "sparcur")) "viewer.rktd"))
; FIXME sppsspps stupidity
(path-source-dir (or (oa-get-path ac 'data-path #:exists? #f)
(build-path (find-system-path 'home-dir) "files" "sparc-datasets")))
(path-log-dir (build-path
(or (oa-get-path ac 'log-path #:exists? #f)
(expand-user-path (user-log-path "sparcur")))
"datasets"))
(path-cache-dir (build-path
(or (oa-get-path ac 'cache-path #:exists? #f)
(expand-user-path (user-cache-path "sparcur")))
"racket"))
(path-cache-push
(build-path ; must match python or sparcur.simple.utils won't be able to find {push-id}/paths.sxpr
(or (oa-get-path ac 'cache-path #:exists? #f)
(expand-user-path (user-cache-path "sparcur")))
"push"))
(path-cache-datasets (build-path (path-cache-dir) "datasets-list.rktd"))
(path-cleaned-dir (or (oa-get-path ac 'cleaned-path #:exists? #f)
(expand-user-path (user-data-path "sparcur" "cleaned"))))
(path-export-dir (or (oa-get-path ac 'export-path #:exists? #f)
(expand-user-path (user-data-path "sparcur" "export"))))
(path-export-datasets (build-path (path-export-dir) "datasets"))))
(define (save-config!)
(with-output-to-file (path-config)
#:exists 'replace
(λ () (pretty-write
(list
(cons 'viewer-mode viewer-mode-state)
(cons 'power-user? (power-user?))
)))))
(define (*->string maybe-string)
(cond
[(symbol? maybe-string) (symbol->string maybe-string)]
[(number? maybe-string) (number->string maybe-string)]
[(keyword? maybe-string) (keyword->string maybe-string)]
[(path? maybe-string) (path->string maybe-string)]
[(boolean? maybe-string) (format "~a" maybe-string)]
[(string? maybe-string) maybe-string]
[else (error '*->string "unknown object type ~s" maybe-string)]))
(define (load-config!)
; TODO various configuration options
(parameterize ([oa-current-auth-config-path (python-mod-auth-config-path "sparcur")])
(define config (oa-read-auth-config))
(let ([org (oa-get config 'remote-organization)]
[orgs (oa-get config 'remote-organizations)] ; TODO
[never-update (oa-get config 'never-update)])
(allow-update? (not never-update))
(send menu-item-update-viewer enable (allow-update?))
(let* ([pc (path-config)]
[cfg (if (and pc (file-exists? pc))
(with-input-from-file pc
(λ ()
(read)))
'())])
(define (obfus str [ends 4])
(let ([ls (string-length str)])
(string-append
(substring str 0 ends)
(make-string (- ls (* 2 ends)) #\*)
(substring str (- ls ends) ls))))
(send text-prefs-remote-organization set-value (*->string org))
(send text-prefs-api-key set-value (obfus (*->string (oa-get-sath 'pennsieve org 'key))))
(send text-prefs-api-sec set-value (obfus (*->string (oa-get-sath 'pennsieve org 'secret))))
#;
(send text-prefs-path-? set-value "egads")
(send text-prefs-path-config set-value (path->string (path-config)))
(send text-prefs-path-user-config set-value (oa-user-config-path))
(send text-prefs-path-secrets set-value (oa-secrets-path))
(send text-prefs-path-data set-value (path->string (path-source-dir)))
(let* ([config-exists (assoc 'viewer-mode cfg)]
[power-user-a (assoc 'power-user? cfg)]
[power-user (and power-user-a (cdr power-user-a))])
(if config-exists
(begin
; set-selection does not trigger the callback
(send radio-box-viewer-mode set-selection (cdr config-exists))
(cb-viewer-mode radio-box-viewer-mode #f)
(power-user? (not power-user))
; cb does the toggle interinally so we set the opposite of what we want first
(cb-power-user check-box-power-user #f))
(set-current-mode-panel! panel-validate-mode)))))))
(define refresh-dataset-metadata-semaphore (make-semaphore 1))
(define (refresh-dataset-metadata text-search-box)
; XXX requries python sparcur to be installed
(call-with-semaphore
refresh-dataset-metadata-semaphore
(thunk
(dynamic-wind
(thunk (send button-refresh-datasets enable #f))
(thunk
(let* ([result (get-dataset-list)]
[datasets (result->dataset-list result)]
[unfiltered? (= 0 (string-length (string-trim (send text-search-box get-value))))])
(current-datasets datasets)
(if unfiltered?
(set-datasets-view! (send text-search-box list-box) (current-datasets))
(cb-search-dataset text-search-box #f))
(println "dataset metadata has been refreshed") ; TODO gui viz on this (beyond updating the number)
(with-output-to-file (path-cache-datasets)
#:exists 'replace ; yes if you run multiple of these you could have a data race
(λ () (pretty-write result)))))
(thunk (send button-refresh-datasets enable #t))))))
(define (get-path-err)
(hash-ref
(hash-ref
(current-blob)
'status
(hash))
'path_error_report
#f))
(define (paths-report)
(for-each (λ (m) (displayln (regexp-replace #rx"SPARC( Consortium)?/[^/]+/" m "\\0\n")) (newline))
; FIXME use my hr function from elsewhere
(let ([ihr (get-path-err)])
(if ihr
(hash-ref (hash-ref ihr '|#/specimen_dirs| #hash((messages . ()))) 'messages)
'()))))
(define (manifest-report)
; FIXME this will fail if one of the keys isn't quite right
; TODO displayln this into a text% I think?
(for-each (λ (m) (displayln (regexp-replace #rx"SPARC( Consortium)?/[^/]+/" m "\\0\n")) (newline))
; FIXME use my hr function from elsewhere
(let ([ihr (get-path-err)])
(if ihr
(hash-ref (hash-ref ihr '|#/path_metadata/-1| #hash((messages . ()))) 'messages)
'()))))
;; update viewer
(define (update-viewer)
"stash and pull all git repos, rebuild the viewer"
;; FIXME the menu option should be disabled if on a system where this is broken/banned
; find the git repos
;; XXX for upgrading python/racket from setup.org we need PYROOTS and RKTROOTS
;; and then REPOS, see specifically clone-repos and python-setup
;; XXX also bug where [email protected]:org/repo.git was used but no key is available
(if (or update-running? (not (allow-update?)))
(println
(if update-running?
"Update is already running!"
"User config is set to never allow update (e.g. because this is a development system)."))
(begin
(set! update-running? #t)
(thread
(thunk
(dynamic-wind
(λ () #t)
(thunk
(println "Update starting ...")
(let ([exec-file (path->string (find-system-path 'exec-file))]
[raco-exe (path->string (find-executable-path "raco"))] ; XXX SIGH
[status
(parameterize ()
(apply py-system* argv-simple-git-repos-update))])
; TODO pull changes for racket dependent repos as well
; TODO raco pkg install local git derived packages as well
(println (format "running raco pkg update ~a" this-package-path))
(let ([mtime-before (file-or-directory-modify-seconds
this-file-compiled
#f
(λ () -1))])
(parameterize ()
(system* raco-exe "pkg" "update" "--batch" this-package-path)
#;
(system* raco-exe "make" "-v" this-file))
#; ; raco exe issues ... i love it when abstractions break :/
(parameterize ([current-command-line-arguments
(vector "--vv" this-file)])
(dynamic-require 'compiler/commands/make #f))
#;
(system* exec-file "-l-" "raco/main.rkt" "make" "--vv" "--" this-file)
(let ([mtime-after (file-or-directory-modify-seconds
this-file-compiled
#f
(λ () -2))])
(when (not (= mtime-before mtime-after))
(println (format "running raco exe -v -o ~a ~a "
this-file-exe this-file))
(parameterize ()
(when (file-exists? this-file-exe)
(rename-file-or-directory this-file-exe this-file-exe-tmp))
(system* raco-exe "exe" "-v" "-o" this-file-exe this-file)
(unless (file-exists? this-file-exe) ; restore the old version on failure
(when (file-exists? this-file-exe-tmp)
(rename-file-or-directory this-file-exe-tmp this-file-exe))))
#; ; this is super cool but an eternal pain for raco exe
(parameterize ([current-command-line-arguments
(vector
"++lib" "compiler/commands/make"
"++lib" "compiler/commands/exe"
"++lib" "racket/lang/reader"
"--vv" this-file)])
(dynamic-require 'compiler/commands/exe #f))
#;
(system* exec-file "-l-" "raco/main.rkt" "exe" "--vv" "--" this-file)))))
(println "Update complete!")
#; ; TODO issue this only if the viewer itself was updated and there was a success
(println "Restart at your convenience.")
)
(λ () (set! update-running? #f))))))))
;; json view
(define-syntax when-not (make-rename-transformer #'unless))
(define (apply-items-rec function item)
;(pretty-print item)
(when (function item)
(let* ([sub-items (send item get-items)])
(for [(sub-item sub-items)] (apply-items-rec function sub-item)))))
(define (do-open item)
; FIXME still slow
(let*-values ([(ud) (send item user-data)]
[(type name) (values (node-data-type ud) (node-data-name ud))])
#;
(pretty-print (list (node-data-type ud) (node-data-name ud) (node-data-value ud)))
(and (or (eq? type 'hash)
(and
(eq? type 'list)
(not (memq name ; filter cases that are v slow to open
'(; FIXME hardcoded
synonyms
curation_errors
unclassified_errors
submission_errors
unclassified_stages
)))))
(send item open))))
(define (set-jview-json! jview json)
"set the default state for jview"
(define jhl (get-field json-hierlist jview))
(define old-root (get-field root jhl))
(when old-root
; this is safe because we force selection at startup
; strangely this code this makes the interface less jerky when scrolling quickly
(send jhl delete-item old-root))
(send jview set-json! json)
(define root (get-field root jhl))
(send jhl sort json-list-item< #t)
#;
(send root open)
; can't thread this because some part of it is not thread safe
(apply-items-rec do-open root)
(send jhl scroll-to 0 0 0 0 #t)
#;
(define (by-name name items)
(let ([v (for/list ([i items]
#:when (let ([ud (send i user-data)])
(and (eq? (node-data-type ud) 'hash)
(eq? (node-data-name ud) name))))
i)])
(and (not (null? v)) (car v))))
#;
(let ([ritems (send root get-items)])
(when (> (length ritems) 1) ; id alone is length 1
(map (λ (x)
(let ([ud (send x user-data)])
(when (and (eq? (node-data-type ud) 'hash)
(memq (node-data-name ud) '(meta submission status))) ; FIXME hardcoded
(when-not (null? (send x get-items)) ; compound item
(send x open))
(when (eq? (node-data-name ud) 'status)
(let ([per (by-name 'path_error_report (send x get-items))])
(when per
(send per open)))))))
ritems))))
(define jviews (make-hash))
(define (dataset-jview! dataset #:update [update #f] #:background [background #f])
; FIXME #:background is bad design forced by having (current-blob) decoupled
(let* ([uuid (id-uuid dataset)]
[hr-jview (hash-ref jviews uuid #f)]
[jview
(if (and hr-jview (not update))
(begin
(current-blob #f)
hr-jview)
(letrec ([hier-class json-hierlist%
#; ; too slow when doing recursive opens
(class json-hierlist% (super-new)
(rename-super [super-on-item-opened on-item-opened])
(define/override (on-item-opened item)
(define root (get-field json-hierlist jview-inner))
#;
(define-values (x y w h)
(values
(send root get-x)
(send root get-y)
(send root get-width)
(send root get-height)))
(super-on-item-opened item)
(send root sort json-list-item< #t)
#; ; this isn't working as a way to stabilize the position of the buffer
; when we get to the end of its content, which is the classic and
; monumentally stupid behavior of most gui toolkits, not clear what can
; be done about this
; XXX the behavior is worse on-item-close so maybe a solution there
(send root scroll-to x y w h #t)))]
[jview-inner
(or (and update hr-jview)
(new json-view%
[hier-class% hier-class]
;;[font (make-object font% 10 'modern)]
[parent frame-helper]))])
(let* ([lp (dataset-export-latest-path dataset)]
[json (if lp (path->json lp)
(hash
'id (dataset-id dataset)
'meta (hash
'id-project (id-project dataset)
'folder_name (dataset-title dataset)
'owner (dataset-pi-name-lf dataset)
'updated (dataset-updated dataset))))]
[jhash (for/hash ([(k v) (in-hash json)]
; FIXME I think we don't need include keys anymore
; XXX false, there are still performance issues
#:when (member k include-keys))
(values k v))])
(unless (or background (not (is-current? dataset)))
(current-blob json)) ; FIXME this will go stale
(set-jview-json! jview-inner jhash)
(hash-set! jviews uuid jview-inner)
jview-inner)))])
jview))
(define (unset-current-jview)
(let ([old-jview (current-jview)])
(when old-jview
(send old-jview reparent frame-helper)
(current-jview #f))))
(define jviews-loading (set))
(define jview-semaphore (make-semaphore 1))
(define (set-jview! dataset)
(let ([uuid (id-uuid dataset)])
; unset-current-jview is safe to call unconditionally because even
; if we can't draw the jview for the new dataset we definitely should
; stop drawing the jview for the most recently deselected dataset
(unset-current-jview)
; when scrolling fast back and forth don't try to load the same jview multiple times
(unless (set-member? jviews-loading uuid)
(set! jviews-loading (set-add jviews-loading uuid))
; setting current dataset must be called in the main thread so that
; curent-dataset is always guranteed to be synchronized with the gui view ...
; setting current dataset is called with a semaphore becuase I have seen one freak case
; where a hang resulted in the double jview behavior, I have tested with this and not
; seen it happen again, however that doesn't mean much, in principle this should block
; the main thread from proceeding until the fast part of the thread below is done which
; in principle should ensure fully sequential behavior, but that's just the theory
(call-with-semaphore
jview-semaphore
(thunk (current-dataset dataset))) ; XXX this is the only place current-dataset should ever be set
(thread
(thunk ; we thread because dataset-jview! can be quite slow for large json blobs
(let ([jview (dataset-jview! dataset)])
; we're done loading so if you want to load again knock yourself out
(set! jviews-loading (set-remove jviews-loading uuid))
; we must use a semaphore here because if you have two consecutive events
; that are very close together in time the exact orderin of the threads
; they spawn can result in a case where (is-current? a) will be called and
; return true before (current-dataset b) is called and (reparent a) is called
; after (b-unparent) is called, said another way, the call to unset-current-jview
; in in main thread for b can fall between the call (is-current? a) and (reparent a)
; in the a subthread, the semaphore ensures that even if this happens that the call
; to unset-current-jview in b will unparent a because b's reparent cannot start until
; after a's finishes in the case where b's unset has been called between ica and ra (confusing I know)
(call-with-semaphore
jview-semaphore
(thunk
(when (string=? uuid (id-uuid (current-dataset)))
; even with the semaphore there is a chance that another thread snuck in and set itself while
; this one was working so we unset the current jview again here otherwise we periodically get two jviews
(unset-current-jview)
(send jview reparent panel-right)
(current-jview jview))))))))))
;; dataset struct and generic functions
(define-generics ds
(populate-list ds list-box)
(lb-cols ds)
(lb-data ds)
(updated-short ds)
(id-short ds)
(id-uuid ds)
(id-project ds)
(uri-human ds)
(uri-sds-viewer ds)
(dataset-src-path ds)
(dataset-working-dir-path ds)
(dataset-log-path ds)
(dataset-latest-log-path ds)
(dataset-export-latest-path ds)
(dataset-cleaned-latest-path ds)
(fetch-export-dataset ds)
(fetch-dataset ds)
(clean-metadata-files ds)
(load-remote-json ds)
(export-dataset ds)
(is-current? ds))
(struct dataset (id title updated pi-name-lf id-project)
#:methods gen:ds
[(define (populate-list ds list-box)
; FIXME annoyingly it looks like these things need to be set in
; batch in order to get columns to work
(send list-box append
(list
(dataset-pi-name-lf ds)
(dataset-title ds)
(id-short ds)
(updated-short ds))
ds))
(define (lb-cols ds)
(list
(dataset-pi-name-lf ds)
(dataset-title ds)
(id-short ds)
(updated-short ds)))
(define (lb-data ds)
; TODO we may want to return more stuff here
ds)
(define (dataset-export-latest-path ds)
(let* ([uuid (id-uuid ds)]
[lp (build-path (path-export-datasets)
uuid "LATEST" "curation-export.json")]
#;
[asdf (println lp)]
[qq (and (file-exists? lp) (resolve-path lp))])
; FIXME not quite right?
qq))
(define (dataset-cleaned-latest-path ds)
(let* ([uuid (id-uuid ds)]
[lp (build-path (path-cleaned-dir)
uuid "LATEST")]
[qq (and (directory-exists? lp) ; sigh, paths are hard
(build-path (path-cleaned-dir) uuid (resolve-path lp)))])
qq))
(define (dataset-src-path ds)
(let ([uuid (id-uuid ds)])
(build-path (path-source-dir) uuid)))
(define (dataset-working-dir-path ds)
(let ([path (dataset-src-path ds)])
(if (directory-exists? path)
(resolve-relative-path (build-path path "dataset"))
(error msg-dataset-not-fetched))))
(define (dataset-log-path ds)
(let ([uuid (id-uuid ds)])
(build-path (path-log-dir) uuid)))
(define (dataset-latest-log-path ds)
(define lp (build-path (dataset-log-path ds) "LATEST/stdout.log"))
(and (file-exists? lp) (resolve-path lp)))
(define (fetch-dataset ds)
(println (format "dataset fetch starting for ~a" (dataset-id ds))) ; TODO gui and/or log
(let ([cwd-1 (path-source-dir)]
[cwd-2 (build-path (dataset-src-path ds)
; FIXME dataset here is hardcoded
"dataset")]
[argv-1 (argv-simple-retrieve ds)]
[argv-2 argv-spc-find-meta])
(thread
(thunk
(let ([status-1 #f]
[status-2 #f])
(ensure-directory! cwd-1)
(parameterize ([current-directory cwd-1])
(with-output-to-string (thunk (set! status-1
(apply py-system* argv-1 #:set-pwd? #t)))))
(parameterize ([current-directory (resolve-relative-path cwd-2)])
(with-output-to-string (thunk (set! status-2
(apply py-system* argv-2 #:set-pwd? #t)))))
(when status-1 (set-button-status-for-dataset ds))
(if (and status-1 status-2)
(println (format "dataset fetch completed for ~a" (dataset-id ds)))
(println (format "dataset fetch FAILED for ~a" (dataset-id ds)))))))))
(define (export-dataset ds)
(println (format "dataset export starting for ~a" (dataset-id ds))) ; TODO gui and/or log
(let ([cwd-2 (build-path (dataset-src-path ds)
; FIXME dataset here is hardcoded
"dataset")]
[argv-3 (append argv-spc-export '("--fill-cache-metadata"))]) ; fill cache metadata in case a file was modified and xattrs were lost
(thread
(thunk
(let ([status-3 #f]
[cwd-2-resolved (resolve-relative-path cwd-2)])
(parameterize ([current-directory cwd-2-resolved])
(with-output-to-string (thunk (set! status-3
(apply py-system* argv-3 #:set-pwd? #t)))
))
(if status-3
(begin
(dataset-jview! ds #:update #t #:background #t)
(println (format "dataset export completed for ~a" (dataset-id ds))))
(println (format "dataset export FAILED for ~a" (dataset-id ds)))))))))
(define (fetch-export-dataset ds)
(println (format "dataset fetch and export starting for ~a" (dataset-id ds))) ; TODO gui and/or log
(let ([cwd-1 (path-source-dir)]
; we can't resolve-path on cwd-2 here because it
; may not exist or it may point to a previous release
[cwd-2 (build-path (dataset-src-path ds)
; FIXME dataset here is hardcoded
"dataset")]
[dataset-log-path-now (build-path (dataset-log-path ds) (datetime-for-path-now) "stdout.log")]
[argv-1 (argv-simple-retrieve ds)]
[argv-2 argv-spc-find-meta]
[argv-3 argv-spc-export])
(let*-values ([(date-path _ __) (split-path dataset-log-path-now)]
[(uuid-path local-date-path __) (split-path date-path)]
[(latest-path) (build-path uuid-path "LATEST")])
(ensure-directory! uuid-path)
(ensure-directory! date-path)
(when (link-exists? latest-path)
(delete-file latest-path))
(make-file-or-directory-link local-date-path latest-path))
(thread
(thunk
(let ([status-1 #f]
[status-2 #f]
[status-3 #f])
(ensure-directory! cwd-1)
(parameterize ([current-directory cwd-1])
#;
(println (string-join argv-1 " "))
(with-output-to-file
dataset-log-path-now
(thunk
(parameterize (#;[current-error-port (current-output-port)]) ; TODO
(set! status-1
(apply py-system* argv-1 #:set-pwd? #t))))
#:exists 'append))
(if status-1
(let ([cwd-2-resolved (resolve-relative-path cwd-2)])
(parameterize ([current-directory cwd-2-resolved])
(with-output-to-file
dataset-log-path-now
(thunk (set! status-2
(apply py-system* argv-2 #:set-pwd? #t)))
#:exists 'append)
; TODO figure out if we need to condition further steps to run on status-2 #t
(println (format "dataset fetch for export completed for ~a" (dataset-id ds)))
(set-button-status-for-dataset ds)
(with-output-to-file
dataset-log-path-now
(thunk (set! status-3
(apply py-system* argv-3 #:set-pwd? #t)))
#:exists 'append))
; TODO gui indication
(if (and status-2 status-3)
(begin
; now that we have 1:1 jview:json we can automatically update the jview for
; this dataset in the background thread and it shouldn't block the ui
(when (equal? ds (current-dataset))
(send button-export-dataset enable #t)
(send button-open-dataset-shell enable #t)
(send button-clean-metadata-files enable #t))
(dataset-jview! ds #:update #t #:background #t)
(println (format "dataset fetch and export completed for ~a" (dataset-id ds))))
(format "dataset ~a FAILED for ~a"
(cond ((nor status-2 status-3) "fetch and export")
(status-2 "export")
(status-3 "fetch"))
(dataset-id ds))))
(println (format "dataset retrieve FAILED for ~a" (dataset-id ds))))
#;
(values status-1 status-2 status-3)
#; ; this doesn't work because list items cannot be customized independently SIGH
; I can see why people use the web for stuff like this, if you want to be able to
; customize some particular entry why fight with the canned private opaque things
; that don't actually meet your use cases?
(set-lview-item-color lview ds) ; FIXME lview free variable
)))))
(define (clean-metadata-files ds)
(println (format "cleaning metadata files for ~a" (dataset-id ds))) ; TODO gui and/or log
(let ([cwd (build-path (dataset-src-path ds)
; FIXME dataset here is hardcoded
"dataset")]
[argv-1 (argv-clean-metadata-files ds)])
(thread
(thunk
(let ([status-1 #f]
[cwd-resolved (resolve-relative-path cwd)])
(parameterize ([current-directory (path-source-dir)])
(with-output-to-string (thunk (set! status-1
(apply py-system* argv-1 #:set-pwd? #t)))
))
(if status-1
(begin
; TODO open folder probably ?
(println (format "cleaning metadata files completed for ~a" (dataset-id ds))))
(println (format "cleaning metadata files FAILED for ~a" (dataset-id ds)))))))))
(define (dataset-latest-prod-url ds)
(string-append (url-prod-datasets) "/" (id-uuid ds) "/LATEST/curation-export.json"))
(define (load-remote-json ds)
(let* ([uuid (id-uuid ds)]
[hr-jview (hash-ref jviews uuid #f)]
[jview-inner
(or hr-jview
(new json-view%
[hier-class% json-hierlist%]
[parent frame-helper]))]
[url (dataset-latest-prod-url ds)]
[json (url->json url)]
[jhash (for/hash ([(k v) (in-hash json)]
; FIXME I think we don't need include keys anymore
; XXX false, there are still performance issues
#:when (member k include-keys))
(values k v))])
(current-blob json) ; FIXME this will go stale
(set-jview-json! jview-inner jhash)
(hash-set! jviews uuid jview-inner)
jview-inner))
(define (set-lview-item-color lview ds)
; find the current row based on data ??? and then change color ?
(println "TODO set color") ; pretty sure this cannot be done with this gui widgit
)
(define (updated-short ds)
(if (string=? (dataset-updated ds) missing-var)
(dataset-updated ds)
(let* ([momnt-z (iso8601->moment (dataset-updated ds))]
[momnt-l (adjust-timezone momnt-z (current-timezone))])
(~t momnt-l "YY-MM-dd HH:mm"))))
(define (id-short ds)
(let-values ([(N type uuid)
(apply values (string-split (dataset-id ds) ":"))])
(string-append
(substring uuid 0 4)
" ... "