-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgnaw.el
More file actions
5352 lines (4922 loc) · 235 KB
/
Copy pathgnaw.el
File metadata and controls
5352 lines (4922 loc) · 235 KB
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
;;; gnaw.el --- Browse and manage BONE reports in Emacs -*- lexical-binding: t; -*-
;; Copyright (C) 2026 Bastien Guerry
;; Author: Bastien Guerry <bzg@gnu.org>
;; Maintainer: Bastien Guerry <bzg@gnu.org>
;; Keywords: mail, news
;; URL: https://codeberg.org/bzg/gnaw.el
;; Version: 0.36.2
;; Package-Requires: ((emacs "28.1") (transient "0.3.7"))
;; This file is not part of GNU Emacs.
;; 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 <http://www.gnu.org/licenses/>.
;;
;;; Commentary:
;;
;; 3==3 GNAW -- GNAW is Not Another Workflow
;;
;; BONE (Backlog Of Notable Emails, <https://codeberg.org/bzg/bone>)
;; is a bug tracker that never asks anyone to file a bug: it watches a
;; project's mailing list, turns the mails tagged [BUG], [PATCH] or
;; [FR] into reports, updates them from the replies and publishes the
;; result as plain reports.json files anyone can fetch.
;;
;; gnaw.el is the Emacs way to work with those files. `M-x gnaw'
;; opens a report browser: search the reports, read their emails, view
;; or apply their patches and attachments, keep local sticky and
;; dismiss marks. The same data layer backs the mail front-ends
;; gnus-gnaw, notmuch-gnaw and mu4e-gnaw. This library:
;;
;; - reads the gnaw configuration (`config.edn') and report sources,
;; - manages the local cache of remote `reports.json' files,
;; - parses and serializes the EDN config and `state.edn' files shared
;; with the gnaw CLI,
;; - exposes the report list, the local-mark API and the MUA-independent
;; presentation helpers (annotation string, topic filtering) the
;; front-ends use.
;;
;; Front-ends provide the message metadata (an INFO plist with keys
;; :type :subject :date :from :from-name, plus display keys :flags
;; :priority :votes :deadline :expiry :last-activity :replies :topic) and
;; the presentation; this library provides everything independent of
;; the mail user agent.
;;
;; Entry points:
;;
;; `gnaw' browse reports (interactive)
;; `gnaw-reports' collect open reports from all sources
;; `gnaw-update' refresh the local cache; C-u forces a re-download
;; `gnaw-toggle-mark' toggle :sticky/:dismiss for a message-id
;; `gnaw-read-state' / `gnaw-write-state' read and write state.edn
;; `gnaw-annotation' build the fixed-width annotation for MUA lines
;;
;;; Code:
(require 'url)
(require 'cl-lib)
(require 'seq)
(require 'subr-x)
(require 'time-date)
(require 'transient)
;; `json-parse-buffer' and friends only exist when Emacs was built
;; with JSON support, which is optional before Emacs 30.
(unless (json-available-p)
(error "GNAW needs an Emacs built with native JSON support"))
(defvar url-http-response-status)
(defgroup gnaw nil
"Read and manage BONE reports shared with the gnaw CLI."
:group 'mail)
(defconst gnaw-version (or (package-get-version) "0.36.2")
"Version of gnaw.el, read from its package header.")
;;;###autoload
(defun gnaw-version ()
"Display the version of gnaw.el."
(interactive)
(message "gnaw.el %s" gnaw-version))
(defcustom gnaw-config-dir "~/.config/gnaw"
"Directory containing gnaw configuration and state/cache files."
:type 'directory
:group 'gnaw)
(defcustom gnaw-after-update-hook nil
"Functions run once `gnaw-update' finished refreshing the local cache.
The update downloads in the background, so the hook runs from its
callbacks, after `gnaw-update' itself returned. Front-ends can use
this to re-apply their display."
:type 'hook
:group 'gnaw)
(defconst gnaw-supported-bone-format "0.9.2"
"Minimum reports.json bone-format gnaw.el reads without warning.")
;;; EDN reader/writer (the subset emitted by gnaw's config.edn and state.edn)
(defun gnaw-edn--skip-ws ()
"Skip EDN whitespace, commas and line comments at point."
(skip-chars-forward " \t\n\r,")
(while (eq (char-after) ?\;)
(forward-line 1)
(skip-chars-forward " \t\n\r,")))
(defun gnaw-edn--read ()
"Read one EDN value at point."
(gnaw-edn--skip-ws)
(let ((c (char-after)))
(cond
((null c) (error "EDN: unexpected EOF"))
((eq c ?\") (read (current-buffer)))
((eq c ?:) (gnaw-edn--read-keyword))
((eq c ?\{) (gnaw-edn--read-map))
((eq c ?\[) (gnaw-edn--read-vector))
((or (and (>= c ?0) (<= c ?9))
(and (eq c ?-) (let ((d (char-after (1+ (point)))))
(and d (>= d ?0) (<= d ?9)))))
(gnaw-edn--read-number))
(t (gnaw-edn--read-symbol)))))
(defun gnaw-edn--read-keyword ()
"Read an EDN keyword at point."
(forward-char 1)
(let ((start (1- (point))))
(skip-chars-forward "a-zA-Z0-9._/?!+*<>=&%$-")
(intern (buffer-substring-no-properties start (point)))))
(defun gnaw-edn--read-symbol ()
"Read an EDN symbol at point.
Signal an error on a character that starts no known EDN value (such
as dispatch forms like #inst), which would otherwise loop forever."
(let ((start (point)))
(skip-chars-forward "a-zA-Z0-9._/?!+*<>=&%$-")
(when (= (point) start)
(error "EDN: unexpected character %c" (char-after)))
(pcase (buffer-substring-no-properties start (point))
("nil" nil)
("true" t)
("false" nil)
(s (intern s)))))
(defun gnaw-edn--read-number ()
"Read an EDN number at point."
(let ((start (point)))
(skip-chars-forward "0-9.eE+-")
(string-to-number (buffer-substring-no-properties start (point)))))
(defun gnaw-edn--read-map ()
"Read an EDN map at point."
(forward-char 1)
(let ((acc nil))
(gnaw-edn--skip-ws)
(while (not (eq (char-after) ?\}))
(let ((k (gnaw-edn--read)))
(gnaw-edn--skip-ws)
(push (cons k (gnaw-edn--read)) acc))
(gnaw-edn--skip-ws))
(forward-char 1)
(nreverse acc)))
(defun gnaw-edn--read-vector ()
"Read an EDN vector at point."
(forward-char 1)
(let ((acc nil))
(gnaw-edn--skip-ws)
(while (not (eq (char-after) ?\]))
(push (gnaw-edn--read) acc)
(gnaw-edn--skip-ws))
(forward-char 1)
(nreverse acc)))
(defun gnaw-edn--map-p (x)
"Non-nil if list X is an alist to write as an EDN map (not a vector).
True when every element is a cons whose car is an atom (a key)."
(and (consp x) (cl-every (lambda (e) (and (consp e) (atom (car e)))) x)))
(defun gnaw--edn-write (v)
"Serialize EDN value V (maps, vectors and scalars) to a string."
(cond
((stringp v) (format "%S" v))
((keywordp v) (symbol-name v))
((eq v t) "true")
((null v) "nil")
((numberp v) (number-to-string v))
((symbolp v) (symbol-name v))
((gnaw-edn--map-p v)
(concat "{" (mapconcat (lambda (kv)
(concat (gnaw--edn-write (car kv)) " "
(gnaw--edn-write (cdr kv))))
v " ")
"}"))
((listp v) (concat "[" (mapconcat #'gnaw--edn-write v " ") "]"))
(t (error "EDN: cannot serialize %S" v))))
(defun gnaw-edn-read-buffer ()
"Read one EDN map from the current buffer if it starts with `{'.
Return nil on parse failure or when no map is present."
(goto-char (point-min))
(gnaw-edn--skip-ws)
(when (eq (char-after) ?\{)
(gnaw-edn--read-map)))
(defun gnaw--read-edn-file (file)
"Read FILE and return its top-level EDN map, or nil.
Return nil when FILE is unreadable or does not parse, reporting parse
errors as a message."
(when (file-readable-p file)
(condition-case err
(with-temp-buffer
(insert-file-contents file)
(gnaw-edn-read-buffer))
(error
(message "gnaw: cannot parse %s: %s" file (error-message-string err))
nil))))
(defun gnaw--read-edn-map-or-signal (file)
"Return FILE's top-level EDN map, or nil when FILE is missing or empty.
Unlike `gnaw--read-edn-file', signal a `user-error' when FILE exists
but cannot be parsed: callers rewrite FILE, and a state derived from a
misread file would silently drop its existing contents."
(when (file-readable-p file)
(condition-case err
(with-temp-buffer
(insert-file-contents file)
(goto-char (point-min))
(gnaw-edn--skip-ws)
(cond ((eobp) nil)
((eq (char-after) ?\{) (gnaw-edn--read-map))
(t (error "Not an EDN map"))))
(error (user-error "Not updating unreadable %s (%s)"
file (error-message-string err))))))
;;; Configuration and report sources
(defun gnaw--uri-to-path (uri)
"Convert file:// URI to local path, otherwise return URI."
(if (string-prefix-p "file://" uri)
(url-unhex-string (substring uri 7))
uri))
(defun gnaw--file-mtime (file)
"Return FILE's modification time, or nil when FILE is absent.
The mtime caches below compare it with `equal' to decide freshness."
(file-attribute-modification-time (file-attributes file)))
(defvar gnaw--config-cache nil
"Cons (MTIME . PLIST) caching the last `gnaw-load-config' result.")
(defun gnaw-load-config ()
"Load `config.edn' and return a plist.
Keys: :addresses :skip-columns :source-configs (raw `:sources' maps)
and :sources (their URLs). The result is cached until config.edn
changes."
(let* ((file (expand-file-name "config.edn" gnaw-config-dir))
(mtime (gnaw--file-mtime file)))
(if (and gnaw--config-cache (equal (car gnaw--config-cache) mtime))
(cdr gnaw--config-cache)
(let* ((cfg (gnaw--read-edn-file file))
(addresses (alist-get :my-addresses cfg))
(skip (alist-get :skip-columns cfg))
(src-cfgs (alist-get :sources cfg))
(sources (mapcan (lambda (s) (append (alist-get :urls s) nil)) src-cfgs))
(plist (list :addresses addresses :skip-columns skip
:source-configs src-cfgs :sources sources)))
(setq gnaw--config-cache (cons mtime plist))
plist))))
(defun gnaw-sources ()
"Return report sources from config.edn as URLs or absolute local paths.
Relative paths are resolved against `gnaw-config-dir'."
(mapcar #'gnaw--resolve-source
(plist-get (gnaw-load-config) :sources)))
(defun gnaw--http-url-p (source)
"Return non-nil if SOURCE is an HTTP(S) URL."
(string-match-p "\\`https?://" source))
(defun gnaw--resolve-source (source)
"Resolve SOURCE to an HTTP(S) URL or an absolute local path.
HTTP(S) URLs are returned unchanged; other sources are file paths,
relative ones resolved against `gnaw-config-dir'."
(if (gnaw--http-url-p source)
source
(expand-file-name (gnaw--uri-to-path source)
(expand-file-name gnaw-config-dir))))
(defun gnaw--source-config-entry (info)
"Return the config.edn source entry matching report INFO, or nil.
Matched by URL or by `:name'."
(let ((url (plist-get info :source))
(name (plist-get info :source-name)))
(seq-find
(lambda (s)
(or (and url (member url (mapcar #'gnaw--resolve-source
(alist-get :urls s))))
(and name (equal name (alist-get :name s)))))
(plist-get (gnaw-load-config) :source-configs))))
(defun gnaw--entry-repos (entry)
"Return config.edn source ENTRY's `:repo' as a list of directories.
The entry holds a directory string or a vector of them."
(mapcar #'expand-file-name (ensure-list (alist-get :repo entry))))
(defun gnaw--source-repos (info)
"Return the local git repos for report INFO's source, as a list.
Reads `:repo' from the matching config.edn `:sources' entry, which
holds a directory string or a vector of them."
(gnaw--entry-repos (gnaw--source-config-entry info)))
(defun gnaw--source-repo (info)
"Return the first local git repo for report INFO's source, or nil.
The directory the save commands propose; `gnaw--target-repo' asks
which repo to apply in when the source lists several."
(car (gnaw--source-repos info)))
(defun gnaw--multi-source-p ()
"Return non-nil when config.edn defines more than one source."
(> (length (plist-get (gnaw-load-config) :source-configs)) 1))
(defun gnaw--source-letter (info)
"Return the letter identifying report INFO's source, or nil.
Reads `:letter' from the matching config.edn `:sources' entry."
(alist-get :letter (gnaw--source-config-entry info)))
(defun gnaw--suggest-source-letter (name taken)
"Suggest a letter identifying source NAME, avoiding the TAKEN ones.
Try NAME's letters and digits in order (so \"Org mode ML\" suggests
O), then A to Z. TAKEN is a list of downcased single-character
strings; return an upcased one, or nil when everything is taken."
(seq-some (lambda (ch)
(let ((s (upcase (char-to-string ch))))
(and (not (member (downcase s) taken)) s)))
(append (seq-filter (lambda (ch)
(string-match-p "[[:alnum:]]"
(char-to-string ch)))
(or name ""))
(number-sequence ?A ?Z))))
(defun gnaw--source-match-p (entry urls name)
"Return non-nil when config source ENTRY shares one of URLS or is NAME.
This is the rule deciding which config.edn entry a
`gnaw--config-add-source' call replaces."
(or (seq-intersection urls (alist-get :urls entry))
(and name (equal name (alist-get :name entry)))))
(defun gnaw--taken-source-letters (entries)
"Return the downcased letters the config source ENTRIES define."
(mapcar #'downcase
(delq nil (mapcar (lambda (s) (alist-get :letter s)) entries))))
(defun gnaw--read-source-letter (name taken &optional default)
"Read the letter identifying source NAME in the browser's S column.
TAKEN is a list of downcased letters already identifying another
source; DEFAULT preempts the `gnaw--suggest-source-letter' suggestion.
Insist until the answer is a single letter or digit not in TAKEN --
the query syntax gives other characters a meaning (\"|\", quotes,
spaces), which would break the S: filters built from the letter."
(let ((def (or default (gnaw--suggest-source-letter name taken)))
letter)
(while (not letter)
(let ((s (string-trim
(read-string (format "Letter for source %s%s: " name
(if def (format " (default %s)" def) ""))
nil nil def))))
(cond ((not (string-match-p "\\`[[:alnum:]]\\'" s))
(message "gnaw: a single letter or digit, please")
(sit-for 1))
((member (downcase s) taken)
(message "gnaw: %s already identifies another source" s)
(sit-for 1))
(t (setq letter (upcase s))))))
letter))
(defun gnaw--ensure-source-letters ()
"Ask for the missing source letters and save them to config.edn.
With several sources, the browser's S column identifies each
report's source by the `:letter' of its config.edn entry: ask
interactively for the entries not defining one. No-op with zero
or one source. Quitting mid-prompts still saves the letters
answered so far, so they are not asked again."
(let* ((raw (gnaw--read-config-raw))
(cfgs (alist-get :sources raw)))
(when (and (> (length cfgs) 1)
(seq-some (lambda (s) (not (alist-get :letter s))) cfgs))
(let ((taken (gnaw--taken-source-letters cfgs))
(done nil)
(changed nil))
(unwind-protect
(dolist (s cfgs)
(push (if (alist-get :letter s)
s
(let ((letter (gnaw--read-source-letter
(or (alist-get :name s)
(car (alist-get :urls s)))
taken)))
(push (downcase letter) taken)
(setq changed t)
(append s (list (cons :letter letter)))))
done))
(when changed
;; A quit leaves the entries not reached in their old form.
(let ((rest (nthcdr (length done) cfgs)))
(gnaw--write-config
(gnaw--alist-put raw :sources
(append (nreverse done) rest))))))))))
(defun gnaw--java-hash (str)
"Calculate Java String hashCode of STR as an unsigned 32-bit integer."
(let ((h 0)
(len (length str)))
(dotimes (i len)
(setq h (logand (+ (* h 31) (aref str i)) #xffffffff)))
h))
(defun gnaw--source-to-cache-file (src)
"Return cache file path for remote source SRC."
(let* ((h (format "%08x" (gnaw--java-hash src)))
(safe (replace-regexp-in-string "[^a-zA-Z0-9._-]" "_" src))
(prefix (substring safe 0 (min 80 (length safe)))))
(expand-file-name
(concat "cache/reports/" prefix "-" h ".json")
gnaw-config-dir)))
(defcustom gnaw-http-timeout 30
"Seconds before a synchronous HTTP fetch gives up, nil to wait forever."
:type '(choice (const :tag "No timeout" nil) (integer :tag "Seconds"))
:group 'gnaw)
(defcustom gnaw-cache-attachments-max-age nil
"Days before `gnaw-cache-cleanup' discards a cached attachment.
An attachment directory is discarded once every file in it is older.
Nil, the default, keeps attachments forever."
:type '(choice (const :tag "Keep forever" nil) (integer :tag "Days"))
:group 'gnaw)
(defun gnaw--http-parse-reply (url)
"Parse the `url-retrieve' reply in the current buffer.
Return a plist (:status :body :etag); signal an error on HTTP
errors or a malformed reply, naming URL."
(let ((status (bound-and-true-p url-http-response-status)))
(when (and status (>= status 400))
(error "HTTP error %d from %s" status url))
(goto-char (point-min))
(unless (re-search-forward "\r?\n\r?\n" nil t)
(error "Malformed HTTP response from %s" url))
(let ((header-end (point)))
(list :status status
:etag (save-excursion
(goto-char (point-min))
(let ((case-fold-search t))
(when (re-search-forward
"^ETag:[ \t]*\\([^\r\n]*\\)"
header-end t)
(match-string 1))))
:body (buffer-substring-no-properties
header-end (point-max))))))
(defun gnaw--http-fetch (url &optional head)
"Fetch URL and return a plist (:status :body :etag).
Non-nil HEAD sends a HEAD request instead of GET: the reply carries
the same headers but no body, which is enough to read :etag cheaply.
Signal an error on HTTP errors or after `gnaw-http-timeout' seconds
without a response."
(let* ((coding-system-for-read 'binary)
(url-request-method (if head "HEAD" "GET"))
(buf (url-retrieve-synchronously url t nil gnaw-http-timeout)))
(unless buf (error "Failed to fetch %s" url))
(unwind-protect
(with-current-buffer buf (gnaw--http-parse-reply url))
(kill-buffer buf))))
(defun gnaw--http-fetch-async (url head callback)
"Fetch URL in the background, then pass CALLBACK one reply plist.
The plist carries :status :body :etag like `gnaw--http-fetch', or
just :error with a description when the fetch failed. Non-nil HEAD
sends a HEAD request. A watchdog enforces `gnaw-http-timeout':
`url-retrieve' alone would wait on a hung connection forever."
(let* ((coding-system-for-read 'binary)
(url-request-method (if head "HEAD" "GET"))
(finished nil)
timer buf)
(cl-flet ((finish (reply)
(unless finished
(setq finished t)
(when (timerp timer) (cancel-timer timer))
(funcall callback reply))))
(setq buf (url-retrieve
url
(lambda (status)
(let ((reply (condition-case err
(if-let* ((e (plist-get status :error)))
(list :error (error-message-string e))
(gnaw--http-parse-reply url))
(error (list :error (error-message-string
err))))))
(kill-buffer (current-buffer))
(finish reply)))
nil t))
;; `run-at-time' fires a nil delay immediately: no timeout
;; configured means no watchdog at all. None either when the
;; callback already ran synchronously.
(unless finished
(setq timer
(and gnaw-http-timeout
(run-at-time
gnaw-http-timeout nil
(lambda ()
(when (buffer-live-p buf)
(when-let* ((proc (get-buffer-process buf)))
(delete-process proc))
(kill-buffer buf))
(finish (list :error
(format "no response after %ss"
gnaw-http-timeout)))))))))))
(defun gnaw--http-body (url)
"Return the raw HTTP body bytes of URL.
Signal an error after `gnaw-http-timeout' seconds without a response."
(plist-get (gnaw--http-fetch url) :body))
(defconst gnaw--json-parse-args
'(:object-type alist :array-type list :false-object nil :null-object nil)
"Keyword arguments shaping how gnaw parses JSON into Lisp data.
Objects become alists with symbol keys and arrays become lists.
Both `false' and `null' map to nil: downstream code tests report
fields with plain nil checks and cannot tell them apart.")
(defun gnaw--parse-json-string (string)
"Parse STRING, JSON text, into Lisp data."
(apply #'json-parse-string string gnaw--json-parse-args))
(defun gnaw--parse-json-file (file)
"Parse FILE, UTF-8 encoded JSON, into Lisp data."
(with-temp-buffer
(let ((coding-system-for-read 'utf-8))
(insert-file-contents file))
(apply #'json-parse-buffer gnaw--json-parse-args)))
(defun gnaw--validators-file (cache-file)
"Return the file storing HTTP validators for CACHE-FILE."
(concat cache-file ".headers"))
(defun gnaw--read-validators (cache-file)
"Return the plist (:etag ...) saved for CACHE-FILE, or nil.
Validators are only meaningful while CACHE-FILE itself exists."
(when (file-exists-p cache-file)
(let ((file (gnaw--validators-file cache-file)))
(when (file-exists-p file)
(ignore-errors
(with-temp-buffer
(insert-file-contents file)
(read (current-buffer))))))))
(defun gnaw--save-validators (cache-file etag)
"Persist ETAG for CACHE-FILE, or drop the saved one when ETAG is nil."
(let ((file (gnaw--validators-file cache-file)))
(if etag
(progn
(make-directory (file-name-directory file) t)
(with-temp-file file
(prin1 (list :etag etag) (current-buffer))))
(when (file-exists-p file)
(delete-file file)))))
(defun gnaw--etag-equal (a b)
"Weakly compare ETags A and B, ignoring the W/ prefix.
The origin may weaken an ETag (gzip does) between two requests, so
only the opaque value decides whether the content changed."
(and a b (equal (string-remove-prefix "W/" a)
(string-remove-prefix "W/" b))))
(defun gnaw--commit-json-reply (reply cache-file)
"Write the JSON body of HTTP REPLY to CACHE-FILE, then its ETag.
Parse before writing -- a malformed download (truncated body, error
page) must not replace a valid cache -- and save the ETag only
after, so a failed write leaves the old one and the next refresh
still sees the stale cache. Return `changed' when CACHE-FILE's
content changed, `refetched' when it was byte-identical."
(let ((body (decode-coding-string (plist-get reply :body) 'utf-8)))
(gnaw--parse-json-string body)
(let ((wrote (gnaw--write-json-to-file body cache-file)))
(gnaw--save-validators cache-file (plist-get reply :etag))
(if wrote 'changed 'refetched))))
(defun gnaw--refresh-cache (url cache-file &optional force)
"Refresh CACHE-FILE from URL, revalidating with a HEAD request.
When an ETag was saved by a previous refresh (and FORCE is nil),
first ask the server for the headers only and compare ETags locally:
an unchanged source costs a HEAD round-trip instead of a download.
Otherwise download and commit (see `gnaw--commit-json-reply').
Return `unchanged' when the saved ETag is still current, else the
commit's outcome."
(let ((etag (unless force
(plist-get (gnaw--read-validators cache-file) :etag))))
(if (and etag
;; Revalidation is only an optimization: when the HEAD
;; fails (proxy rejecting the method, timeout), fall
;; through to the full GET instead of failing the
;; refresh.
(gnaw--etag-equal etag
(plist-get (ignore-errors
(gnaw--http-fetch url 'head))
:etag)))
'unchanged
(gnaw--commit-json-reply (gnaw--http-fetch url) cache-file))))
(defun gnaw--update-source (source force callback)
"Refresh SOURCE's cache in the background; CALLBACK gets the outcome.
The outcome is `changed', `unchanged', `refetched' as in
`gnaw--refresh-cache', or `failed' -- the failure is also messaged.
Follows the same sequence asynchronously: HEAD revalidation by saved
ETag unless FORCE, then a download parsed before it may overwrite
the cache."
(let* ((cache-file (gnaw--source-to-cache-file source))
(etag (unless force
(plist-get (gnaw--read-validators cache-file) :etag))))
(cl-flet ((download ()
(gnaw--http-fetch-async
source nil
(lambda (reply)
(funcall
callback
(condition-case err
(if-let* ((e (plist-get reply :error)))
(error "%s" e)
(gnaw--commit-json-reply reply cache-file))
(error
(message "gnaw: failed updating %s: %s"
source (error-message-string err))
'failed)))))))
(if etag
;; Revalidation is only an optimization: when the HEAD fails
;; (proxy rejecting the method, timeout), fall through to the
;; full GET instead of failing the refresh.
(gnaw--http-fetch-async
source 'head
(lambda (reply)
(if (and (not (plist-get reply :error))
(gnaw--etag-equal etag (plist-get reply :etag)))
(funcall callback 'unchanged)
;; This runs from an async callback, outside the
;; dispatch guard of `gnaw-update': a synchronous error
;; here must still reach CALLBACK, or the pending
;; counter never comes down.
(condition-case err
(download)
(error
(message "gnaw: failed updating %s: %s"
source (error-message-string err))
(funcall callback 'failed))))))
(download)))))
(defun gnaw--write-json-to-file (json file)
"Write JSON, a string, to FILE as UTF-8.
Leave an already-identical FILE untouched; return non-nil when its
content actually changed."
(make-directory (file-name-directory file) t)
(unless (and (file-exists-p file)
(equal json
(with-temp-buffer
(let ((coding-system-for-read 'utf-8))
(insert-file-contents file))
(buffer-string))))
(let ((coding-system-for-write 'utf-8))
(with-temp-file file
(insert json)))
t))
(defun gnaw--read-json (source)
"Read JSON from SOURCE, using local cache for remote URLs if available."
(if (gnaw--http-url-p source)
(let ((cache-file (gnaw--source-to-cache-file source)))
;; First read of this source: populate the cache (and its
;; ETag), then read it back like any other cached source.
(unless (file-exists-p cache-file)
(gnaw--refresh-cache source cache-file))
(gnaw--parse-json-file cache-file))
(gnaw--parse-json-file source)))
(defun gnaw-normalize-mid (mid)
"Ensure MID has angle brackets."
(if (string-match-p "\\`<.*>\\'" mid)
mid
(concat "<" mid ">")))
(defconst gnaw--relation-keys
'(resolves resolved-by
supersedes superseded-by
duplicates duplicated-by
related-to)
"Per-kind relation fields of a report, as emitted by BONE.
`related-to' comes last: BONE poses a `related-to' companion edge
next to each closure relation, and `gnaw--report-related' dedups
by message-id keeping the first entry seen -- the specific kind
must win over the companion.")
(defun gnaw--report-related (r)
"Merge report R's per-kind relation entries, deduped by message-id.
Each entry is annotated with a `kind' key naming the relation field
it came from."
(let (mids entries)
(dolist (k gnaw--relation-keys (nreverse entries))
(dolist (e (alist-get k r))
(when-let* ((mid (alist-get 'message-id e)))
(unless (member mid mids)
(push mid mids)
(push (cons (cons 'kind k) e) entries)))))))
(defun gnaw--relation-kind-label (kind)
"Describe a related report of relation KIND, seen from the origin.
The phrasing follows the BONE JSON: under a report, the `supersedes'
field lists the reports superseding it, `resolved-by' the patches
resolving it, and so on."
(pcase kind
('related-to "related to it")
('supersedes "supersedes it")
('superseded-by "superseded by it")
('resolves "resolved by it")
('resolved-by "resolves it")
('duplicates "duplicated by it")
('duplicated-by "duplicates it")
(_ (and kind (format "%s" kind)))))
(defvar gnaw--reports-cache (make-hash-table :test 'equal)
"Cache of `gnaw--extract-reports' results, keyed by source.
Each value is (FILE-MTIME CONFIG-MTIME PAIRS), the modification
times of the source's file and of config.edn (which carries the
source letters) when PAIRS was extracted.")
(defun gnaw--config-mtime ()
"Return config.edn's modification time, or nil when absent."
(gnaw--file-mtime (expand-file-name "config.edn" gnaw-config-dir)))
(defun gnaw--extract-reports (source)
"Extract published reports from SOURCE as (MID . INFO) pairs.
Closed reports (status below 4, flags C, R, E or S) are kept when
SOURCE lists them, as an all.json does; the list hides them until
a query asks for them (see `gnaw-list--display-reports').
The result is cached until the source's file or config.edn changes
on disk, so a reload does not re-parse unchanged JSON. Callers get
the cached list itself: copy before mutating (as `gnaw-reports'
does for `mapcan')."
(let* ((file (if (gnaw--http-url-p source)
(gnaw--source-to-cache-file source)
source))
(mtime (gnaw--file-mtime file))
(cmtime (gnaw--config-mtime))
(cached (gethash source gnaw--reports-cache)))
(if (and mtime
(equal (nth 0 cached) mtime)
(equal (nth 1 cached) cmtime))
(nth 2 cached)
(let ((pairs (gnaw--extract-reports-1 source)))
;; Re-stat: `gnaw--read-json' populates a missing cache file.
(puthash source
(list (gnaw--file-mtime file) cmtime pairs)
gnaw--reports-cache)
pairs))))
(defun gnaw--extract-reports-1 (source)
"Parse SOURCE and extract its report pairs (see `gnaw--extract-reports')."
(let* ((data (gnaw--read-json source))
(fv (alist-get 'bone-format data))
(sname (alist-get 'source data))
(letter (gnaw--source-letter (list :source source
:source-name sname)))
(reports (alist-get 'reports data))
(result '()))
(when (and fv (version< fv gnaw-supported-bone-format))
(message "gnaw: %s has format %s, min supported is %s"
source fv gnaw-supported-bone-format))
(dolist (r reports)
(let ((mid (alist-get 'message-id r))
(status (alist-get 'status r))
(type (alist-get 'type r))
(acked (alist-get 'acked r))
(acked-name (alist-get 'acked-name r))
(owned (alist-get 'owned r))
(closed (alist-get 'closed r))
(owned-name (alist-get 'owned-name r))
(close-reason (alist-get 'close-reason r))
(priority (alist-get 'priority r))
(votes (alist-get 'votes r))
(deadline (alist-get 'deadline r))
(expiry (alist-get 'expiry r))
(last-activity (alist-get 'last-activity r))
(replies (alist-get 'replies r))
(topic (alist-get 'topic r))
(subject (alist-get 'subject r))
(from (alist-get 'from r))
(from-name (alist-get 'from-name r))
(date (alist-get 'date r))
(archived-at (alist-get 'archived-at r))
(patches (alist-get 'patches r))
(events (alist-get 'events r))
(texts (alist-get 'texts r))
(awaiting (alist-get 'awaiting r))
(related (gnaw--report-related r))
(series (alist-get 'series r))
(patch-seq (alist-get 'patch-seq r))
(trailers (alist-get 'trailers r)))
(when (and mid (numberp status))
(let ((flags (concat (if acked "A" "-")
(if owned "O" "-")
(pcase close-reason
("canceled" "C")
("resolved" "R")
("expired" "E")
("superseded" "S")
(_ (if closed "R" "-")))))
(norm-mid (gnaw-normalize-mid mid)))
(push (cons norm-mid (list :type (or type "bug")
:flags flags
:priority (or priority 0)
:votes votes
:deadline deadline
:expiry expiry
:last-activity last-activity
:replies replies
:topic topic
:subject subject
:from from
:from-name from-name
:date date
:source source
:source-name sname
:source-letter letter
:archived-at archived-at
:patches patches
:events events
:texts texts
:awaiting awaiting
:related related
:series series
:patch-seq patch-seq
:trailers trailers
:acked acked
:acked-name acked-name
:owned owned
:owned-name owned-name
:closed closed))
result)))))
(nreverse result)))
(defun gnaw-reports ()
"Collect report pairs from all sources, tolerating failures.
A source that fails to load is skipped and reported through
`display-warning' -- a transient `message' would be clobbered by
the rendering that follows, leaving an empty listing with no
visible explanation."
(mapcan
(lambda (source)
(condition-case err
;; Copy: `mapcan' splices destructively, and the extracted
;; list belongs to `gnaw--reports-cache' -- nconc'ing it in
;; place would chain the caches together, then loop them.
(append (gnaw--extract-reports source) nil)
(error
(display-warning
'gnaw
(format "failed loading source %s: %s"
source (error-message-string err))
:error)
nil)))
(gnaw-sources)))
(defvar gnaw--update-pending nil
"Number of sources the running `gnaw-update' still waits on, or nil.")
(defun gnaw-update (&optional force callback)
"Refresh the local cache from remote JSON sources, in the background.
The sources download in parallel while Emacs stays responsive; each
is first revalidated with a HEAD request comparing the server's ETag
to the saved one, so an unchanged source costs no download. With a
prefix argument FORCE, skip the revalidation and re-download every
source. Once every source finished, run `gnaw-after-update-hook',
then CALLBACK when non-nil."
(interactive "P")
(when gnaw--update-pending
(user-error "An update is already running"))
(let* ((sources (cl-remove-if-not #'gnaw--http-url-p (gnaw-sources)))
(changed 0)
(failed 0)
(done (lambda (msg)
(setq gnaw--update-pending nil)
(run-hooks 'gnaw-after-update-hook)
(message "%s" msg)
(when callback (funcall callback))))
(finish (lambda (outcome)
(pcase outcome
('changed (cl-incf changed))
('failed (cl-incf failed)))
(when (zerop (cl-decf gnaw--update-pending))
(funcall done
(format "gnaw: cache refreshed%s%s."
(if (zerop changed)
", no changes"
(format " (%d source%s changed)"
changed
(if (= changed 1) "" "s")))
(if (zerop failed)
""
(format ", %d failed" failed))))))))
(if (null sources)
(funcall done "gnaw: no remote source to update")
(setq gnaw--update-pending (length sources))
(message "gnaw: updating %d source%s in the background..."
(length sources) (if (cdr sources) "s" ""))
(dolist (source sources)
;; A synchronous failure (malformed URL) must still count
;; down, or `gnaw--update-pending' would block updates forever.
(condition-case err
(gnaw--update-source source force finish)
(error
(message "gnaw: failed updating %s: %s"
source (error-message-string err))
(funcall finish 'failed)))))))
(defun gnaw--tree-size (path)
"Return the total byte size of PATH, a file or a directory."
(if (file-directory-p path)
(apply #'+ (mapcar (lambda (f)
(or (file-attribute-size (file-attributes f)) 0))
(directory-files-recursively path "")))
(or (file-attribute-size (file-attributes path)) 0)))
(defun gnaw--meta-url (source)
"Return the URL of reports SOURCE's sibling meta.json."
(concat (file-name-directory source) "meta.json"))
(defun gnaw--source-cache-files (source)
"Return the files a remote SOURCE owns under cache/reports/.
Its reports cache and its sibling meta.json's (see
`gnaw-source-meta'), each with its validators file. The one place
enumerating a source's cache artifacts: a new sidecar written next
to the cache must join this list, or `gnaw-cache-cleanup' deletes
it as an orphan."
(when (gnaw--http-url-p source)
(mapcan (lambda (url)
(let ((f (gnaw--source-to-cache-file url)))
(list f (gnaw--validators-file f))))
(list source (gnaw--meta-url source)))))
(defun gnaw--cache-report-files (&optional all)
"Return the files under cache/reports/ that no configured source owns.
Non-nil ALL returns every file there, the configured sources' own
caches and validators included. Only regular files either way: a
stray directory is left alone rather than aborting the deletions."
(let* ((dir (expand-file-name "cache/reports" gnaw-config-dir))
(files (when (file-directory-p dir)
(cl-remove-if-not
#'file-regular-p
(directory-files dir t
directory-files-no-dot-files-regexp)))))
(if all
files
(let ((keep (mapcan #'gnaw--source-cache-files (gnaw-sources))))
(cl-remove-if (lambda (f) (member f keep)) files)))))
(defconst gnaw--attachment-subdirs
'((patch . "patches/") (event . "events/") (text . "text/"))
"Attachment TYPE to BONE export subdir, siblings of reports/.
Read by `gnaw--attachment-subdir'; `gnaw-cache-cleanup' sweeps
every subdir listed here, so a new attachment type joins the
cleanup by joining this table.")
(defun gnaw--cache-stale-attachments ()
"Return the cached attachments the max age discards.
Under the `gnaw--attachment-subdirs' of cache/, a report directory
is stale when it holds files all older than
`gnaw-cache-attachments-max-age' days -- an empty one may belong to
a fetch in flight and stays -- and a flat single-component
attachment file ages out on its own mtime (see `gnaw-cache-cleanup')."
(when gnaw-cache-attachments-max-age
(let ((cutoff (time-subtract (current-time)
(days-to-time
gnaw-cache-attachments-max-age)))
stale)
(dolist (subdir (mapcar #'cdr gnaw--attachment-subdirs)
(nreverse stale))
(let ((base (expand-file-name (concat "cache/" subdir)
gnaw-config-dir)))
(when (file-directory-p base)
(dolist (srcdir (directory-files
base t directory-files-no-dot-files-regexp))