-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
om-dash.el
1649 lines (1456 loc) · 60.8 KB
/
om-dash.el
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
;;; om-dash.el --- Building blocks for org-based dashboards -*- lexical-binding: t -*-
;; Copyright (C) 2024 Victor Gaydov
;; Author: Victor Gaydov <[email protected]>
;; URL: https://github.com/gavv/om-dash
;;; License:
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; om-dash implements a set of dynamic blocks for org-mode that you can use
;; to compose a custom dashboard for your projects.
;; Currently om-dash implementats three configurable dynamic blocks:
;; - om-dash-github - generates a table with github issues or pull requests
;; - om-dash-orgfile - generates tables with top-level entries from org file
;; - om-dash-command - generates a table from the output of a shell command
;; It also provides a minor mode (om-dash-mode) that applies highlighting to
;; the generated tables.
;; In addition, there is support for templates, which allows to create
;; reusable parameterized configurations of the above blocks.
;; Refer to README.org for examples and screenshots.
;;; Code:
(require 'cl-lib)
(require 'json)
(require 'org)
(require 'org-ql)
(require 's)
(require 'seq)
(require 'ts)
(when (featurep 'parse-csv)
;; https://github.com/mrc/el-csv
(require 'parse-csv))
(defvar om-dash-todo-keywords nil
"List of keywords considered as TODO.
If block has any of the TODO keywords, block's heading becomes TODO.
The first element from this list is used for block's heading in this case.
If a keyword from this list doesn't have a face in 'om-dash-keyword-faces',
it uses default TODO keyword face.
When nil, filled automatically from 'org-todo-keywords', 'org-done-keywords',
and pre-defined github keywords.")
(defvar om-dash-done-keywords nil
"List of keywords considered as DONE.
If block doesn't have any of the TODO keywords, block's heading becomes DONE.
The first element from this list is used for block's heading in this case.
If a keyword from this list doesn't have a face in 'om-dash-keyword-faces',
it uses default DONE keyword face.
When nil, filled automatically from 'org-todo-keywords', 'org-done-keywords',
and pre-defined github keywords.")
(defvar om-dash-keyword-faces
'(
;; org-mode
("TODO" . om-dash-todo-keyword)
("DONE" . om-dash-done-keyword)
;; github
("OPEN" . om-dash-open-keyword)
("MERGED" . om-dash-merged-keyword)
("CLOSED" . om-dash-closed-keyword)
)
"Assoc list to map keywords to faces.
If some keyword is not mapped to a face explicitly, default face is selected,
using face for TODO or DONE depending on whether that keyword is in
'om-dash-todo-keywords' or 'om-dash-done-keywords'.")
(defvar om-dash-tag-map nil
"Assoc list to remap or unmap tag names.
Defines how tags are displayed in table.
You can map tag name to a different string or to nil to hide it.")
(defvar om-dash-templates
'(
(milestone . om-dash-github:milestone)
(project-column . om-dash-github:project-column)
)
"Assoc list of expandable templates for om-dash dynamic blocks.
Each entry is a cons of two symbols: template name and template function.
When you pass ':template foo' as an argument to a dynamic block, it finds
a function in this list by key 'foo and uses it to \"expand\" the template.
This function is invoked with dynamic block parameters plist and should
return a new plist. The new plist is used to update the original
parameters by appending new values and overwriting existing values.
For example, if 'org-dblock-write:om-dash-github' block has parameters:
(:template project-column
:repo \"owner/repo\"
:type 'pr
:project 123
:column \"In progress\")
Dynamic block will use 'project-column' as a key in 'om-dash-templates'
and find 'om-dash-github:project-column' function.
The function is invoked with all the parameters above, and returns
something like:
(:repo \"owner/repo\"
:type 'pr
:open (\"project:owner/repo/123\"
\".projectCards[] | (.column.name == \\\"In progress\\\")\"))
Then this parameters are interpreted as usual.")
(defvar om-dash-table-width nil
"If non-nil, align tables to have given fixed width.
If nil, tables have minimum width that fits their contents.")
(defvar om-dash-squeeze-empty-columns t
"If non-nil, automatically remove empty columns from tables.
E.g. if every row has empty tags, :tags column is removed from this table.")
(defvar om-dash-link-style :cell
"How links are generated in om-dash tables.
Allowed values:
- :none - no links are inserted
- :text - only cell text becomes a link
- :cell - whole cell becomes a link")
(defvar om-dash-orgfile-columns
'(:state
:title-link)
"Column list for 'om-dash-orgfile' table.
Supported values:
| symbol | example |
|-------------+-----------------|
| :state | TODO, DONE, ... |
| :title | text |
| :title-link | [[link][text]] |
| :tags | :tag1:tag2:...: |
")
(defvar om-dash-github-columns
'(:state
:number
:author
:title-link)
"Column list for 'om-dash-github' table.
Supported values:
| symbol | example |
|-------------+-------------------|
| :state | OPEN, CLOSED, ... |
| :number | #123 |
| :author | @octocat |
| :title | text |
| :title-link | [[link][text]] |
| :tags | :tag1:tag2:...: |
")
(defvar om-dash-github-limit 200
"Default limit for github queries.
E.g. if you query \"all open issues\" or \"closed issues since january\",
only last 'om-dash-github-limit' results are returned.")
(defvar om-dash-github-fields
'(
(pr
.
("assignees"
"author"
"autoMergeRequest"
"baseRefName"
"body"
"closed"
"closedAt"
"createdAt"
"headRefName"
"headRefOid"
"headRepository"
"headRepositoryOwner"
"id"
"isCrossRepository"
"isDraft"
"labels"
"maintainerCanModify"
"mergeable"
"mergeCommit"
"mergedAt"
"mergedBy"
"mergeStateStatus"
"milestone"
"number"
"potentialMergeCommit"
"reviewDecision"
"reviewRequests"
"state"
"title"
"updatedAt"
"url"))
(issue
.
("assignees"
"author"
"closed"
"closedAt"
"createdAt"
"id"
"labels"
"milestone"
"number"
"state"
"title"
"updatedAt"
"url"
))
)
"List of json fields enabled by default in github queries.
This defines which fields are present in github responses and hence can
be used in jq selectors.
We don't enable all fields by default because some of them noticeably
slow down response times.
There is also 'om-dash-github-auto-enabled-fields', which defines fields
that are enabled automatically for a query if jq selector contains them.
In addition, 'org-dblock-write:om-dash-github' accepts ':fields'
parameter, which can be used to specify addition fields per-block.")
(defvar om-dash-github-auto-enabled-fields
'(
(pr
.
(
"additions"
"changedFiles"
"comments"
"commits"
"deletions"
"files"
"latestReviews"
"projectCards"
"projectItems"
"reactionGroups"
"reviews"
"statusCheckRollup"
))
(issue
.
(
"body"
"comments"
"projectCards"
"projectItems"
"reactionGroups"
))
)
"List of json fields automatically enabled on demand in github queries.
See 'om-dash-github-fields' for more details.")
(defvar om-dash-verbose nil
"Enable verbose logging.
If non-nill, all commands and queries are logged to '*om-dash*' buffer.")
(defgroup om-dash-faces nil
"Faces in om-dash mode.")
(defface om-dash-header-cell
'((t (:inherit default)))
"Face used for entire cell in om-dash table header.
You can use it so specify header background."
:group 'om-dash-faces)
(defface om-dash-header-text
'((t (:inherit org-table)))
"Face used for text in om-dash table header.
You can use it so specify header font."
:group 'om-dash-faces)
(defface om-dash-cell
'((t (:inherit default)))
"Face used for entire non-header cell in om-dash table.
You can use it so specify cell background."
:group 'om-dash-faces)
(defface om-dash-text
'((t (:inherit default)))
"Face used for text in om-dash table non-header cell.
You can use it so specify cell font."
:group 'om-dash-faces)
(defface om-dash-number
'((t (:inherit org-link)))
"Face used for issue or pull request numbers in om-dash tables."
:group 'om-dash-faces)
(defface om-dash-author
'((t (:inherit org-document-info)))
"Face used for issue or pull request authors in om-dash tables."
:group 'om-dash-faces)
(defface om-dash-todo-keyword
'((t (:inherit org-todo :weight normal)))
"Face used for 'TODO' keyword in om-dash tables."
:group 'om-dash-faces)
(defface om-dash-done-keyword
'((t (:inherit org-done :weight normal)))
"Face used for 'DONE' keyword in om-dash tables."
:group 'om-dash-faces)
(defface om-dash-open-keyword
'((t (:inherit om-dash-todo-keyword)))
"Face used for 'OPEN' keyword in om-dash tables."
:group 'om-dash-faces)
(defface om-dash-merged-keyword
'((t (:inherit om-dash-done-keyword)))
"Face used for 'MERGED' keyword in om-dash tables."
:group 'om-dash-faces)
(defface om-dash-closed-keyword
'((t (:inherit org-warning :weight normal)))
"Face used for 'CLOSED' keyword in om-dash tables."
:group 'om-dash-faces)
(defun om-dash--todo-keywords ()
"Get list of TODO keywords."
(unless om-dash-todo-keywords
(setq-local om-dash-todo-keywords
(seq-concatenate 'list
;; org
(seq-difference org-todo-keywords-1
org-done-keywords)
;; github
(list "OPEN"))))
om-dash-todo-keywords)
(defun om-dash--done-keywords ()
"Get list of DONE keywords."
(unless om-dash-done-keywords
(setq-local om-dash-done-keywords
(seq-concatenate 'list
;; org
org-done-keywords
;; github
(list "MERGED"
"CLOSED"))))
om-dash-done-keywords)
(defun om-dash--choose-keyword (is-todo)
"Select TODO/DONE keyword"
(let ((todo-keywords (om-dash--todo-keywords))
(done-keywords (om-dash--done-keywords)))
(if is-todo
(if todo-keywords
(car todo-keywords)
"TODO")
(if done-keywords
(car done-keywords)
"DONE"))))
(defun om-dash--choose-face (keyword)
"Select face for keyword"
(let ((om-face (cdr (assoc keyword om-dash-keyword-faces)))
(org-face (cdr (assoc keyword org-todo-keyword-faces))))
(cond
;; face from om-dash-keyword-faces
(om-face om-face)
;; face from org-todo-keyword-faces
(org-face
`(:inherit ,org-face :weight normal))
;; fallback to face for "TODO"
((and (seq-contains-p (om-dash--todo-keywords) keyword)
(not (string= keyword "TODO")))
(om-dash--choose-face "TODO"))
;; fallback to face for "DONE"
((and (seq-contains-p (om-dash--done-keywords) keyword)
(not (string= keyword "DONE")))
(om-dash--choose-face "DONE"))
;; give up
(t 'default))))
(defun om-dash--choose-level ()
"Select default outline level for a table."
(save-excursion
(while (om-dash--in-dblock-p)
(org-previous-visible-heading 1))
(1+ (org-outline-level))))
(defun om-dash--in-dblock-p ()
(let ((case-fold-search t))
(org-between-regexps-p "^[ \t]*#\\+BEGIN:"
"^[ \t]*#\\+END:"
(point-min)
(point-max))))
(defun om-dash--log (msg)
"Log line to *om-dash* buffer"
(if om-dash-verbose
(with-current-buffer (get-buffer-create "*om-dash*")
(goto-char (point-max))
(insert ">>> ")
(insert msg)
(insert "\n"))))
(cl-defstruct om-dash--cell
"Struct that represents single table cell."
text
link)
(defun om-dash--format-tags (tags)
"Format list of tags into string."
;; remap and remove tags according to om-dash-tag-map
(setq tags
(seq-remove 'not
(seq-map (lambda (tag)
(let ((mapping (assoc tag om-dash-tag-map)))
(if mapping
(cadr mapping)
tag)))
tags)))
;; fix tags names
(setq tags (seq-map (lambda (tag)
(s-replace-regexp "[^[:alnum:]_@#%:]" "_" tag))
tags))
;; format tagline
(if tags
(s-concat ":" (s-join ":" tags) ":")
""))
(defun om-dash--format-cell (text link width)
"Format cell contents into string."
(when (> (length text) width)
(setq text (s-truncate width text)))
(let ((padding
(if (< (length text) width)
(s-repeat (- width (length text)) " ")
"")))
(cond ((or (not link) (eq :none (or om-dash-link-style :none)))
(format "%s%s" text padding))
((eq :text om-dash-link-style)
(format "[[%s][%s]]%s" link text padding))
((eq :cell om-dash-link-style)
(format "[[%s][%s%s]]" link text padding))
(t
(error "om-dash: unknown om-dash-link-style %S" om-dash-link-style)))))
(defun om-dash--insert-heading (keyword headline level)
"Insert org heading with given text."
(let ((stars (s-repeat level "*")))
(insert (format "%s %s %s\n" stars keyword headline))))
(defun om-dash--insert-indent (level)
"Insert initial indentation for specified org level."
(let ((indent (s-repeat (1+ level) " ")))
(insert indent)))
(defun om-dash--insert-header (cols)
"Insert table header according to columns spec."
(dolist (col cols)
(let ((text (car col))
(width (cdr col)))
(insert "|")
(insert (s-concat " " (s-pad-right width " " text) " "))))
(insert "|\n"))
(defun om-dash--insert-ruler (cols)
"Insert table ruler according to columns spec."
(let ((col-num 0))
(dolist (col cols)
(let ((text (car col))
(width (cdr col)))
(if (eq col-num 0)
(insert "|")
(insert "+"))
(insert (s-repeat (+ 2 width) "-")))
(setq col-num (1+ col-num))))
(insert "|\n"))
(defun om-dash--insert-cell (cell width)
"Insert table cell, performing truncation, padding, and formatting link."
(let* ((text (om-dash--cell-text cell))
(link (om-dash--cell-link cell))
(contents
(om-dash--format-cell text link width)))
(insert contents)))
(defun om-dash--insert-row (cols cells)
"Insert table row according to columns spec and cell values."
(let ((pos 0))
(dolist (cell cells)
(let ((column-width (cdr (elt cols pos))))
(insert "| ")
(om-dash--insert-cell cell column-width)
(insert " ")
(setq pos (1+ pos))))
(insert "|\n")))
(defun om-dash--insert-table (column-names rows level)
"Generate table from column names and list of rows."
(let* (;; index of column to stretch - by default last one
(stretch-col (1- (length column-names)))
;; list of pairs ("title" . length)
(columns (seq-map-indexed
(lambda (name index)
(when (consp name)
;; if column name is ("name" . t) instead of "name",
;; it means that this is the column to stretch to
;; fit required table width
(when (cdr name)
(setq stretch-col index))
(setq name (car name)))
(cons name (length name)))
column-names)))
;; squeeze - remove empty columns
(when om-dash-squeeze-empty-columns
(let ((col-count (length columns)))
(dotimes (idx col-count)
(let ((col-num (- col-count idx 1)))
(unless (seq-some (lambda (row)
(not (s-blank-str-p (om-dash--cell-text
(elt row col-num)))))
rows)
;; this column is empty, remove it
(setq columns
(seq-remove-at-position columns col-num))
(setq rows
(seq-map (lambda (row)
(seq-remove-at-position row col-num))
rows))
(when (eq stretch-col col-num)
(setq stretch-col (1- stretch-col))))))))
;; adjust column widths to fit contents
(dolist (row rows)
(let* ((col-num 0))
(dolist (cell row)
(let* ((cell-text (om-dash--cell-text cell))
(cell-len (length cell-text))
(col-name (car (elt columns col-num)))
(col-width (cdr (elt columns col-num))))
(if (> cell-len col-width)
(setcdr (assoc col-name columns) cell-len)))
(setq col-num (1+ col-num)))))
;; stretch - truncate or pad one column to fit total table width
(when om-dash-table-width
(let ((total-width 1))
(dolist (col columns)
(setq total-width (+ total-width 3 (cdr col))))
(when (not (eq total-width om-dash-table-width))
(let ((col (elt columns stretch-col)))
(setcdr col (- om-dash-table-width
(- total-width (cdr col))))))))
;; |--------|
(om-dash--insert-indent level)
(om-dash--insert-ruler columns)
;; | header |
(om-dash--insert-indent level)
(om-dash--insert-header columns)
;; |--------|
(om-dash--insert-indent level)
(om-dash--insert-ruler columns)
;; | cell |
(dolist (row rows)
(om-dash--insert-indent level)
(om-dash--insert-row columns row))
;; |--------|
(om-dash--insert-indent level)
(om-dash--insert-ruler columns)))
(defun om-dash--insert-newline ()
"If current line is not empty, insert LF."
(unless (bolp)
(insert "\n")))
(defun om-dash--remove-empty-line ()
"If current line is empty, remove it."
(when (bolp)
(backward-delete-char 1)))
(defun om-dash--table-todo-p (table)
"Check if a table has a cell with value from 'om-dash-todo-keywords'."
(seq-some (lambda (row)
(seq-some (lambda (cell)
(seq-contains-p (om-dash--todo-keywords)
(om-dash--cell-text cell)))
row))
table))
(defun om-dash--shell-quote (arg)
"Quote argument for shell"
(let ((str (format "%s" arg)))
;; minimize quoting for more readable logs
(cond ((s-matches-p "^[a-zA-Z0-9/:.,_-]+$" str)
str)
((and (not (s-contains-p "'" str))
(eq system-type 'gnu/linux))
(format "'%s'" str))
(t
(shell-quote-argument str)))))
(defun om-dash--shell-run (command capture)
"Run shell command"
(om-dash--log command)
(with-output-to-string
(let ((status
(call-process-shell-command command nil
(if capture
standard-output
nil))))
(unless (eq status 0)
(om-dash--log (format "command exited with status %s" status))
(error "om-dash: command failed")))))
(defun om-dash--expand-template (params)
"Return params with expanded :template (if it's present)"
(if-let ((template-name (plist-get params :template)))
(let* ((template (or (assoc template-name om-dash-templates)
(error "om-dash: unknown :template %s"
template-name)))
(expanded-params (funcall (cdr template) params))
(merged-params (seq-copy params)))
(while expanded-params
(let ((key (car expanded-params))
(val (cadr expanded-params)))
(setq merged-params (plist-put merged-params key val))
(setq expanded-params (cddr expanded-params))))
merged-params)
params))
(defun om-dash--parse-json (columns raw-output)
"Parse json output to table."
(let ((parsed-output (json-read-from-string raw-output))
table)
(seq-do (lambda (json)
(let ((col-num 0)
row)
(dolist (col columns)
(let* ((field (format "%s"
(cdr (assoc (intern col) json)))))
(push (make-om-dash--cell :text field)
row))
(setq col-num (1+ col-num)))
(push (nreverse row)
table)))
parsed-output)
(nreverse table)))
(defun om-dash--parse-csv (columns raw-output)
"Parse csv output to table."
(unless (featurep 'parse-csv)
(error "parse-csv package not found"))
(let ((parsed-output (parse-csv-string-rows raw-output ?\, ?\" "\n"))
table)
(dolist (parsed-row parsed-output)
(when (seq-some 's-present-p parsed-row)
(let ((col-num 0)
row)
(dolist (col columns)
(let ((field (if (< col-num (length parsed-row))
(elt parsed-row col-num)
"")))
(push (make-om-dash--cell :text field)
row))
(setq col-num (1+ col-num)))
(push (nreverse row)
table))))
(nreverse table)))
(defun org-dblock-write:om-dash-command (params)
"Builds org heading with a table from output of a shell command.
Usage example:
#+BEGIN: om-dash-command :command \"curl -s https://api.github.com/users/octocat/repos\" :format json :columns (\"name\" \"forks_count\")
...
#+END:
| parameter | default | description |
|----------------+----------+-----------------------------------------|
| :command | required | shell command to run |
| :columns | required | column names (list of strings) |
| :format | 'json' | command output format ('json' or 'csv') |
| :headline | auto | text for generated org heading |
| :heading-level | auto | level for generated org heading |
If ':format' is 'json', command output should be a JSON array of
JSON objects, which have a value for every key from ':columns'.
If ':format' is 'csv', command output should be CSV. First column
of CSV becomes value of first column from ':columns', and so on.
Note: using CSV format requires installing 'parse-csv' package
from https://github.com/mrc/el-csv
"
;; expand template
(setq params
(om-dash--expand-template params))
;; parse params
(let* ((command (or (plist-get params :command)
(error "om-dash: missing :command")))
(format (or (plist-get params :format) 'json))
(columns (or (plist-get params :columns)
(error "om-dash: missing :columns")))
(headline (or (plist-get params :headline)
(file-name-nondirectory
(car (split-string-shell-command command)))))
(heading-level (or (plist-get params :heading-level)
(om-dash--choose-level))))
;; run command
(let* ((raw-output (om-dash--shell-run command t))
(table (cond ((eq format 'json)
(om-dash--parse-json columns raw-output))
((eq format 'csv)
(om-dash--parse-csv columns raw-output))
(t
(error "om-dash: bad :format %S" format))))
(is-todo (om-dash--table-todo-p table)))
(om-dash--insert-heading (om-dash--choose-keyword is-todo)
headline heading-level)
(om-dash--insert-table columns table heading-level)
(om-dash--remove-empty-line))))
(defun om-dash--gh-headline (type)
"Get name for github type."
(cond ((eq type 'issue) "issues")
((eq type 'pr) "pull requests")
((eq type 'any) "issues and pull requests")
(t (error "om-dash: bad type %S" type))))
(defun om-dash--gh-quote (str)
"Quote argument of github query search term."
(s-replace "\"" "\\\""
(s-replace "\\" "\\\\" str)))
(defun om-dash--gh-fields (type selector fields)
"Construct fields list for gh command."
;; if user didn't provide :fields, construct them automatically
(unless fields
;; add all fields enabled by default
(setq fields
(cdr (assoc type om-dash-github-fields)))
(if selector
;; add all fields that are disabled by default but are
;; present in jq selector
(dolist (field
(cdr (assoc type om-dash-github-auto-enabled-fields)))
(if (s-contains-p field selector)
(setq fields
(append fields (list field)))))))
(seq-uniq fields))
(defun om-dash--gh-query (state query)
"Construct query for gh --search option."
(let ((sub-queries
(list
(cond ((eq state 'any) "state:open state:closed")
((eq state 'open) "state:open")
((eq state 'closed) "-state:open")
(t (error "om-dash: bad state %S" state)))
(cond
;; "*"
((string= "*" query) "")
;; "-123d"
((string-match "^-\\([[:digit:]]+\\)\\([a-z][a-z]?\\)$" query)
(let ((count (string-to-number (match-string 1 query)))
(unit (match-string 2 query)))
(ts-format "updated:>%Y-%m-%d"
(cond
;; "-123d"
((string= unit "d")
(ts-adjust 'day (- count) (ts-now)))
;; "-123w"
((string= unit "w")
(ts-adjust 'day (- (* count 7)) (ts-now)))
;; "-123mo"
((string= unit "mo")
(ts-adjust 'month (- count) (ts-now)))
;; "-123y"
((string= unit "y")
(ts-adjust 'year (- count) (ts-now)))
(t
(error "om-dash: bad query %S" query))))))
;; passthrough
(t query)))))
(s-join " " (seq-remove 's-blank-p sub-queries))))
(defun om-dash--gh-command (repo type state filter fields limit)
"Construct gh command."
(let ((query (car filter))
(selector (cadr filter))
command)
(when (s-present-p query)
(let ((fields
(s-join "," (om-dash--gh-fields type selector fields)))
(subcmd (cond ((eq type 'pr) "pr")
((eq type 'issue) "issue")
(t (error "om-dash: bad :type %S" type))))
(search
(om-dash--gh-query state query)))
(setq command (format
"gh %s -R %s list --json %s --search %s --limit %s"
subcmd
(om-dash--shell-quote repo)
(om-dash--shell-quote fields)
(om-dash--shell-quote search)
(om-dash--shell-quote limit))))
(when (s-present-p selector)
(let ((expr (format "[.[] | select(%s)]"
selector)))
(setq command (format "%s | jq %s"
command
(om-dash--shell-quote expr)))))
command)))
(defun om-dash--jq-command (input-files sort-by)
"Construct jq command that joins and sorts output of gh commands."
(let* ((merge-expr
(s-join " + " (seq-map
(lambda (index) (format ".[%d]" index))
(number-sequence 0 (1- (length input-files))))))
(expr
(format "%s | sort_by(.%s)"
merge-expr
sort-by)))
(format "jq -s %s %s"
(om-dash--shell-quote expr)
(s-join " " (seq-map 'om-dash--shell-quote input-files)))))
(defun om-dash--github-run (repo type any-filter open-filter closed-filter
sort-by fields limit)
"Construct and run command for om-dash-github."
(let* ((gh-types
(if (eq type 'any) (list 'pr 'issue)
(list type)))
(gh-commands
(seq-remove 'not
(apply 'append
(seq-map
(lambda (type)
(list
(om-dash--gh-command ; :any
repo type 'any any-filter fields limit)
(om-dash--gh-command ; :open
repo type 'open open-filter fields limit)
(om-dash--gh-command ; :closed
repo type 'closed closed-filter fields limit)))
gh-types))))
(gh-outputs
(seq-map (lambda (cmd) (make-temp-file "om-dash-"))
gh-commands))
(jq-command
(om-dash--jq-command gh-outputs sort-by)))
(unwind-protect
(progn
;; run gh commands, save output to temp files
(seq-mapn (lambda (cmd out)
(let ((gh-command
(format "%s > %s" cmd out)))
(om-dash--shell-run gh-command nil)))
gh-commands
gh-outputs)
;; run jq command to merge and sort gh outputs, and return result
(om-dash--shell-run jq-command t))
;; delete temp files
(dolist (out gh-outputs)
(delete-file out)))))
(defun org-dblock-write:om-dash-github (params)
"Builds org heading with a table of github issues or pull requests.
Basic example:
#+BEGIN: om-dash-github :repo \"octocat/linguist\" :type pr :open \"*\" :closed \"-1w\"
...
#+END:
More advanced example:
#+BEGIN: om-dash-github :repo \"octocat/hello-world\" :type any :open (\"comments:>2\" \".title | contains(\\\"Hello\\\")\") :sort \"updatedAt\" :limit 100
...
#+END:
Parameters:
| parameter | default | description |
|----------------+--------------------------+--------------------------------------|
| :repo | required | github repo in form “<login>/<repo>“ |
| :type | required | topic type ('issue', 'pr', 'any') |
| :any | match none (““) | query for topics in any state |
| :open | match all (“*“) | query for topics in open state |
| :closed | match none (““) | query for topics in closed state |
| :sort | “createdAt“ | sort results by given field |
| :fields | 'om-dash-github-fields' | explicitly specify list of fields |
| :limit | 'om-dash-github-limit' | limit number of results |
| :table-columns | 'om-dash-github-columns' | list of columns to display |
| :headline | auto | text for generated org heading |
| :heading-level | auto | level for generated org heading |
A query for ':any', ':open', and ':closed' can have one of the two forms:
- \"github-query\"
- (\"github-query\" \"jq-selector\")
'github-query' is a string using github search syntax:
https://docs.github.com/en/search-github/searching-on-github/searching-issues-and-pull-requests
Besides standard syntax, a few extended forms are supported:
| form | description |
|----------+---------------------------------------|
| “*“ | match all |
| “-123d“ | match if updated during last 123 days |
| “-123w“ | same, but weeks |
| “-123mo“ | same, but months |
| “-123y“ | same, but years |
'jq-selector' is an optional selector to filter results using jq command:
https://jqlang.github.io/jq/
You can specify different queries for open and closed topics, e.g. to show all
open issues but only recently closed issues, use:
:open \"*\" :closed \"-1mo\"
Alternatively, you can use a single query regardless of topic state:
:any \"-1mo\"
Under the hood, the block uses combination of gh and jq commands like:
gh -R <repo> issue list \\
--json <fields> --search <github query> --limit <limit> \\
| jq '[.[] | select(<jq selector>)]'
(jq part is optional and is used only when the query has the second form when
both github and jq parts are present).
Exact commands being executed are printed to '*om-dash*' buffer
if 'om-dash-verbose' is set.
By default, github query uses all fields from 'om-dash-github-fields', plus any
field from 'om-dash-github-auto-enabled-fields' if it's present in jq selector.
The latter allows to exclude fields that makes queries slower, when they're
not used. To change this, you can specify ':fields' parameter explicitly.
"
;; expand template
(setq params
(om-dash--expand-template params))
;; parse params
(let* ((repo (or (plist-get params :repo) (error "om-dash: missing :repo")))
(type (or (plist-get params :type) (error "om-dash: missing :type")))
;; :any, :open, and :closed may be "query" or ("query" "selector")
;; in the first case, we transform it to ("query" nil)
;; query is for `gh --search`, optional selector is for `jq`
(any-param (or (plist-get params :any) nil))
(any-filter (cond ((listp any-param) any-param)
(t (list any-param nil))))
(open-param (or (plist-get params :open) "*"))
(open-filter (cond ((listp open-param) open-param)
(t (list open-param nil))))
(closed-param (or (plist-get params :closed) nil))
(closed-filter (cond ((listp closed-param) closed-param)
(t (list closed-param nil))))
(sort-by (or (plist-get params :sort) "createdAt"))
(fields (plist-get params :fields))
(limit (or (plist-get params :limit) om-dash-github-limit))
(table-columns (or (plist-get params :table-columns)
om-dash-github-columns))
(headline (or (plist-get params :headline)
(format "%s (%s)" (om-dash--gh-headline type) repo)))
(heading-level (or (plist-get params :heading-level)