forked from agzam/remoto.el
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremoto.el
More file actions
3600 lines (3345 loc) · 162 KB
/
Copy pathremoto.el
File metadata and controls
3600 lines (3345 loc) · 162 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
;;; remoto.el --- Browse GitHub repos without cloning -*- lexical-binding: t; -*-
;;
;; Copyright (C) 2026 Ag Ibragimov
;;
;; Author: Ag Ibragimov <agzam.ibragimov@gmail.com>
;; Assisted-by: ECA:claude-opus-5
;; Maintainer: Ag Ibragimov <agzam.ibragimov@gmail.com>
;; Created: April 24, 2026
;; Version: 2.0.0
;; Keywords: tools vc
;; Homepage: https://github.com/agzam/remoto.el
;; Package-Requires: ((emacs "29.1") (ghub "4.0.0"))
;;
;; SPDX-License-Identifier: GPL-3.0-or-later
;;
;; This file is not part of GNU Emacs.
;;; Commentary:
;; remoto.el lets you browse any GitHub repository in Emacs as if it were
;; cloned locally - without cloning it. It registers a virtual filesystem
;; via `file-name-handler-alist' that translates Emacs file operations into
;; GitHub API calls via the `ghub' library.
;;
;; Loading this file defines things and changes nothing. `global-remoto-mode'
;; is the switch: it installs the file-name handler, the `find-file' and
;; `dired' URL rewriting, the completion metadata, and the auto-enabling of
;; `remoto-mode' in remoto buffers, and removes all of them when turned off.
;;
;; Usage:
;; C-x C-f /github:torvalds/linux RET
;; M-x remoto-browse RET https://github.com/torvalds/linux RET
;;
;; Both turn the mode on when it is off: `remoto-browse' itself, and the
;; path through `remoto-autoload-file-name-handler', which the package
;; autoloads register for `/github:' and `/gh:' paths the way TRAMP
;; autoloads on a remote path. `(global-remoto-mode 1)' in the init file
;; turns it on ahead of time. `remoto-browse' supports pasting any GitHub
;; URL, git remote URL, or owner/repo shorthand.
;;; Code:
(require 'cl-lib)
(require 'files-x)
(require 'format-spec)
(require 'ghub)
;;;; Path parsing
(defconst remoto--path-regexp
(rx bos "/github:"
(group (+ (not (in "/@")))) ; owner
"/"
(group (+ (not (in "/@:")))) ; repo
(? "@" (group (+ (not (in ":/"))))) ; ref (optional)
":"
(group (* anything)) ; path
eos)
"Regexp matching canonical remoto paths.
Groups: 1=owner, 2=repo, 3=ref (maybe nil), 4=path.")
(defconst remoto--handler-regexp "\\`/\\(?:github\\|gh\\):"
"Regexp matching remoto file paths.
Matches the canonical /github: prefix and its /gh: shorthand alias.
Spelled out rather than built with `rx' because the autoload cookie on
`remoto-autoload-file-name-handler' repeats it as a literal.")
(defconst remoto--repo-delimiters
'((?/ . files-default)
(?@ . branches)
(?# . issues))
"Alist mapping delimiter characters after OWNER/REPO to completion levels.
`/' means browse files on default branch, `@' means pick a branch/tag,
`#' means browse issues/PRs.")
(cl-defstruct (remoto-path (:constructor remoto-path-create)
(:copier nil))
"Parsed components of a remoto path."
owner repo ref path)
(defun remoto--parse-path (filename)
"Parse canonical remoto FILENAME into a `remoto-path' struct.
Returns nil if FILENAME does not match the canonical format."
(when (string-match remoto--path-regexp filename)
(remoto-path-create
:owner (match-string 1 filename)
:repo (match-string 2 filename)
:ref (match-string 3 filename)
:path (let ((p (match-string 4 filename)))
(if (or (null p) (string-empty-p p)) "/" p)))))
(defun remoto--canonical-path (parsed)
"Build a canonical remoto path string from PARSED `remoto-path'."
(format "/github:%s/%s%s:%s"
(remoto-path-owner parsed)
(remoto-path-repo parsed)
(if (remoto-path-ref parsed)
(concat "@" (remoto-path-ref parsed))
"")
(or (remoto-path-path parsed) "/")))
(defun remoto--repo-key (parsed)
"Return cache key string for PARSED `remoto-path'.
Format: owner/repo@ref."
(format "%s/%s@%s"
(remoto-path-owner parsed)
(remoto-path-repo parsed)
(or (remoto-path-ref parsed) "HEAD")))
;;;; GitHub API
(declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
(defgroup remoto nil
"Browse GitHub repos without cloning."
:group 'tools
:prefix "remoto-")
(defcustom remoto-github-auth nil
"Auth token source for GitHub API requests via ghub.
nil means use the default ghub token (USERNAME^ghub in auth-source).
A symbol like `forge' uses that package's token instead.
A string is used as a literal token.
See ghub documentation for auth-source setup."
:type '(choice (const :tag "Default ghub token" nil)
(symbol :tag "Package token name")
(string :tag "Literal token"))
:group 'remoto)
(defcustom remoto-auth-timeout 10
"Seconds to wait for auth-source token lookup before giving up.
When ghub's token lookup (which may trigger GPG decryption of
authinfo) exceeds this limit, remoto falls back to unauthenticated
access for that request. Use `remoto-reset-auth' to retry after
adding a token."
:type 'number
:group 'remoto)
(defcustom remoto-search-cache-ttl 300
"Seconds before cached API results expire.
Set to 0 to disable caching. Applies to the search, branch, and
directory-listing caches. Defined early so functions above the
\"Repository search\" section can reference it at byte-compile time."
:type 'integer
:group 'remoto)
(defvar remoto--auth-failed nil
"Non-nil when authenticated GitHub access has permanently failed.
Set on actual auth errors (missing token, 401), NOT on timeouts.
Causes `remoto--api' to skip token lookup and use unauthenticated
requests. Reset with `remoto-reset-auth'.")
(defvar remoto--effective-auth nil
"Resolved auth value that actually works, or nil if not yet probed.
Set by `remoto--warm-auth' after trying `remoto-github-auth' and
falling back to `forge' if available. Cleared by `remoto-reset-auth'.")
(defvar remoto--authenticated-user nil
"Cached GitHub login of the authenticated user, or nil if unknown.
Set by `remoto--get-authenticated-user' on first successful lookup.
Cleared by `remoto-reset-auth'.")
(defun remoto--json-reader (_status)
"Parse JSON response with list-type arrays for remoto compatibility.
Finds the JSON body by scanning for the first `{' or `[',
handling both header-present and header-stripped response buffers
across different ghub and url.el versions."
(goto-char (point-min))
(when (re-search-forward "[{[]" nil t)
(backward-char 1)
(let ((body (buffer-substring-no-properties (point) (point-max))))
(unless (string-empty-p body)
(condition-case nil
(json-parse-string
(decode-coding-string body 'utf-8)
:object-type 'alist
:array-type 'list
:null-object nil
:false-object nil)
(json-error nil))))))
;;;; Fetch indicator
(defcustom remoto-show-fetch-indicator t
"When non-nil, show a \"fetching\" indicator during GitHub requests.
While completing a remoto path (e.g. with \\[find-file]) or at the
`remoto-browse' prompt, it is drawn as minibuffer text, so it works with
any completion UI (vertico, icomplete, default, ...). A fetch that
blocks with no such prompt up, as when the chosen path opens, shows it
in the echo area instead."
:type 'boolean
:group 'remoto)
(defvar remoto--inflight-count 0
"Number of API requests the minibuffer overlay stands for.
Every async request of the completion counts, and so does a blocking
fetch that runs while a remoto prompt is up.")
(defvar remoto--status-overlay nil
"Overlay holding the fetch indicator slot in the active minibuffer.")
(defconst remoto--fetch-indicator-text
(propertize "⟳" 'face 'shadow)
"Circle arrow shown by the fetch indicator in both contexts.
Reused by the minibuffer slot and the echo-area message so the two read
identically. One character, because a word in the minibuffer scrolls
the line as it comes and goes; a text character rather than an emoji,
because a color glyph is taller than the line it sits in and ignores
the `shadow' face.")
(defconst remoto--fetch-indicator-blank
(make-string (string-width remoto--fetch-indicator-text) ?\s)
"What the indicator's slot holds between requests.")
(defun remoto--clear-status ()
"Remove the fetch indicator slot, if any."
(when (overlayp remoto--status-overlay)
(delete-overlay remoto--status-overlay))
(setq remoto--status-overlay nil))
(defun remoto--render-status (buffer busy)
"Draw the fetch indicator slot in BUFFER, filled when BUSY.
The slot sits between the prompt and the input, never after it. Emacs
draws the cursor after any string that follows point, and a completion
UI that opens its candidate list there claims the `cursor' property for
its own string - Vertico does - so an indicator after the input drags
the cursor sideways on every request. The blank keeps the slot's width
between requests, so the input does not shift either."
(with-current-buffer buffer
(let ((pos (minibuffer-prompt-end)))
(unless (and (overlayp remoto--status-overlay)
(eq (overlay-buffer remoto--status-overlay) buffer))
(remoto--clear-status)
(setq remoto--status-overlay (make-overlay pos pos)))
(move-overlay remoto--status-overlay pos pos)
(overlay-put remoto--status-overlay 'priority 1000)
(overlay-put remoto--status-overlay 'before-string
(concat (if busy
remoto--fetch-indicator-text
remoto--fetch-indicator-blank)
" ")))))
(defun remoto--hide-status ()
"Blank the fetch indicator, keeping its slot while the prompt is up.
A slot that came and went would shift the input left and right as
requests come and go, which is what drawing it at all has to avoid."
(let ((buf (and (overlayp remoto--status-overlay)
(overlay-buffer remoto--status-overlay))))
(if (and (buffer-live-p buf) (minibufferp buf))
(remoto--render-status buf nil)
(remoto--clear-status))))
(defun remoto--completion-minibuffer ()
"Return the active minibuffer when it is completing for remoto, else nil.
That is a file name inside a remoto path, with either prefix and possibly
behind a shadowed directory (\"~/x//gh:o/\") the way `read-file-name'
reads it, or the `remoto-browse' prompt, whose collection is
`remoto--repo-completion-table'. A prompt opened inside a remoto
directory counts even with nothing typed: `read-file-name' puts its DIR
argument in the minibuffer's `default-directory', and completion keeps
fetching from there after \\[move-beginning-of-line] \\[kill-line]."
(when-let* ((win (active-minibuffer-window))
(buf (window-buffer win)))
(with-current-buffer buf
(and (or (eq minibuffer-completion-table #'remoto--repo-completion-table)
(string-match-p remoto--handler-regexp
(condition-case nil
(substitute-in-file-name
(minibuffer-contents-no-properties))
(error "")))
(string-match-p remoto--handler-regexp
(or default-directory "")))
buf))))
(defun remoto--show-status ()
"Show the in-flight fetch indicator in the active remoto minibuffer.
No-op unless `remoto-show-fetch-indicator' is non-nil and the active
minibuffer is one that `remoto--completion-minibuffer' recognizes.
Drawn as minibuffer text so it works with any completion UI."
(when remoto-show-fetch-indicator
(when-let* ((buf (remoto--completion-minibuffer)))
(remoto--render-status buf t))))
(defun remoto--inflight-inc ()
"Register a new in-flight async request and show the indicator."
(setq remoto--inflight-count (1+ remoto--inflight-count))
(remoto--show-status))
(defun remoto--inflight-dec ()
"Mark one in-flight async request as finished.
Blank the indicator once no requests remain."
(setq remoto--inflight-count (max 0 (1- remoto--inflight-count)))
(when (zerop remoto--inflight-count)
(remoto--hide-status)))
(defun remoto--minibuffer-exit-cleanup ()
"Reset in-flight indicator state when a minibuffer exits."
(remoto--clear-status)
(setq remoto--inflight-count 0))
(defvar remoto--sync-fetch-depth 0
"Nesting depth of `remoto--with-fetch-indicator' bodies.
Only the outermost body draws and clears the indicator, so a command
wrapped as a whole and the API calls inside it draw it once.")
(defvar remoto--sync-fetch-overlay nil
"Non-nil while the outermost blocking fetch is drawn as the minibuffer overlay.
Decides which of the two indicators the end of that fetch clears.")
(defun remoto--sync-fetch-begin ()
"Draw the indicator for the blocking fetch about to begin.
In a remoto completion minibuffer that is the overlay of the async
fetches, painted at once because nothing redisplays while the fetch
blocks; anywhere else it is an echo-area message, which the echo area
shows at once."
(setq remoto--sync-fetch-depth (1+ remoto--sync-fetch-depth))
(when (= remoto--sync-fetch-depth 1)
(setq remoto--sync-fetch-overlay (and (remoto--completion-minibuffer) t))
(if remoto--sync-fetch-overlay
(progn (remoto--inflight-inc)
(redisplay))
(let ((message-log-max nil))
(message "Remoto %s" remoto--fetch-indicator-text)))))
(defun remoto--sync-fetch-end ()
"Clear the indicator once the outermost blocking fetch is over.
A message that something else put up meanwhile is left alone."
(setq remoto--sync-fetch-depth (max 0 (1- remoto--sync-fetch-depth)))
(when (zerop remoto--sync-fetch-depth)
(if remoto--sync-fetch-overlay
(remoto--inflight-dec)
(when (equal (current-message)
(format "Remoto %s" remoto--fetch-indicator-text))
(let ((message-log-max nil))
(message nil))))
(setq remoto--sync-fetch-overlay nil)))
(defmacro remoto--with-fetch-indicator (&rest body)
"Run BODY, a blocking GitHub round-trip, with the fetch indicator up.
Every synchronous API call goes through this, so `remoto-browse' and a
path at `find-file' or `dired' show the same thing: the minibuffer
overlay while completing, the echo area once the prompt is gone.
Honors `remoto-show-fetch-indicator' and does nothing in batch, where
there is no display. Returns BODY's value."
(declare (indent 0) (debug t))
`(if (or noninteractive (not remoto-show-fetch-indicator))
(progn ,@body)
(remoto--sync-fetch-begin)
(unwind-protect
(progn ,@body)
(remoto--sync-fetch-end))))
(cl-defstruct (remoto--request (:constructor remoto--request-create))
"A GitHub request started under `while-no-input'."
(status 'pending)
buffer
value)
(defvar remoto--pending-requests (make-hash-table :test 'equal)
"Requests started under `while-no-input', keyed by (RESOURCE . AUTH).
Such a request outlives the completion call that started it: the reply
lands in its `remoto--request', and the next call for the same key
waits on that request or reads the landed reply instead of asking
GitHub again. A failed request leaves the table, so the next call
retries.")
(defun remoto--request-condition (err resource)
"Turn ERR, as ghub hands it to an errorback, into the condition ghub signals.
RESOURCE names the request in the condition data."
(pcase err
(`(error http ,code . ,rest)
(list 'ghub-http-error code (nth 2 (assq code url-http-codes))
(concat "https://api.github.com" resource) (car rest)))
(`(error . ,data) (cons 'ghub-error data))
(_ err)))
(defun remoto--request-start (key resource auth)
"Start a callback request for RESOURCE with AUTH and register it under KEY."
(let ((req (remoto--request-create)))
(setf (remoto--request-buffer req)
(ghub-get resource nil
:auth auth
:reader #'remoto--json-reader
:host "api.github.com"
:callback (lambda (value &rest _)
(setf (remoto--request-value req) value
(remoto--request-status req) 'done))
:errorback (lambda (err &rest _)
(remhash key remoto--pending-requests)
(setf (remoto--request-value req)
(remoto--request-condition err resource)
(remoto--request-status req) 'error))))
(puthash key req remoto--pending-requests)
req))
(defun remoto--auth-key (auth)
"Return a stable identity for AUTH that is not the credential itself.
`remoto--pending-requests' only has to tell two callers apart, and its
keys are readable in a backtrace or a variable dump, so a token string
goes in hashed. A symbol such as `none' is no secret and stays as is."
(if (stringp auth) (secure-hash 'sha256 auth) auth))
(defun remoto--ghub-get-interruptible (resource auth)
"GET RESOURCE with AUTH through a callback, waiting in a way input can end.
`url-retrieve-synchronously' leaves its buffer behind when `while-no-input'
throws past it, and the reply nobody reads keeps the buffer alive; ghub
kills the buffer of a callback request itself once the reply is handled.
Return the value or signal the condition the synchronous call would."
(let* ((key (cons resource (remoto--auth-key auth)))
(req (or (gethash key remoto--pending-requests)
(remoto--request-start key resource auth))))
(while (and (eq (remoto--request-status req) 'pending)
(buffer-live-p (remoto--request-buffer req)))
(accept-process-output nil 0.1))
(remhash key remoto--pending-requests)
(pcase (remoto--request-status req)
('done (remoto--request-value req))
('error (let ((err (remoto--request-value req)))
(signal (car err) (cdr err))))
(_ (error "Remoto: no reply for %s" resource)))))
(defun remoto--ghub-get (resource auth endpoint)
"Call `ghub-get' on RESOURCE with AUTH, translating errors.
ENDPOINT is used in error messages for context. Always passes
`:host \"api.github.com\"' explicitly - ghub's default host
resolution can resolve to github.com (HTML) instead of the
JSON API endpoint."
(condition-case err
(remoto--with-fetch-indicator
(let ((inhibit-message (not ghub-debug)))
;; `while-no-input' binds `throw-on-input'; only then can input
;; abandon the call, and only then is the callback path needed.
(if throw-on-input
(remoto--ghub-get-interruptible resource auth)
(ghub-get resource nil
:auth auth
:reader #'remoto--json-reader
:host "api.github.com"))))
;; ghub signals every HTTP failure as (ghub-http-error CODE MESSAGE URL
;; PAYLOAD); there are no per-status error symbols to match on.
(ghub-http-error
(pcase (cadr err)
(404 (user-error "Remoto: not found: %s" endpoint))
(403 (user-error "Remoto: access denied (rate limit or permissions): %s"
endpoint))
(401 (user-error "Remoto: authentication failed; \
configure ghub token in auth-source"))
(_ (user-error "Remoto: API error: %s" (error-message-string err)))))
(json-error
(user-error "Remoto: could not parse API response for %s" endpoint))))
(defun remoto--api (endpoint)
"Call GitHub REST API ENDPOINT via ghub, return parsed JSON.
ENDPOINT should not have a leading slash - one is prepended
automatically. Auth resolution order: `remoto--effective-auth',
`remoto-github-auth', ghub's built-in auth-source lookup,
`remoto--find-github-token' (last resort). When every avenue
fails, signals `user-error'. Public repos work without any
setup via unauthenticated fallback."
(let* ((resource (concat "/" endpoint))
(auth (cond (remoto--auth-failed 'none)
(remoto--effective-auth remoto--effective-auth)
((stringp remoto-github-auth) remoto-github-auth)
;; Try our own auth-source search before ghub's
;; resolution, which uses different host/user
;; patterns and often fails on fresh sessions.
(t (or (when-let* ((token (remoto--find-github-token)))
(setq remoto--effective-auth token)
token)
;; A lookup that fails inside sets the flag; this
;; call must go unauthenticated too, or ghub's own
;; lookup hits the same broken backend and errors.
(and remoto--auth-failed 'none))))))
(if (eq auth 'none)
(remoto--ghub-get resource 'none endpoint)
(condition-case err
;; Only apply the auth timeout on the first call (before we
;; know whether auth works). Once the authenticated user is
;; cached, auth-source won't block, so skip the timeout to
;; avoid aborting slow HTTP responses.
(if remoto--authenticated-user
(remoto--ghub-get resource auth endpoint)
(let ((result (with-timeout (remoto-auth-timeout 'remoto--timed-out)
(remoto--ghub-get resource auth endpoint))))
(when (eq result 'remoto--timed-out)
(message "Remoto: auth lookup timed out; retrying next call (see `remoto-auth-timeout')")
(setq result (remoto--ghub-get resource 'none endpoint)))
result))
;; Re-raise API errors (404, 403, etc.) from remoto--ghub-get;
;; these are not auth failures.
(user-error
(if (string-prefix-p "Remoto:" (cadr err))
(signal (car err) (cdr err))
;; ghub auth config error (e.g. "Cannot determine
;; username"). Every avenue exhausted - fail loudly.
(setq remoto--auth-failed t)
(user-error "Remoto: authentication failed for %s; \
configure a GitHub token in auth-source, then M-x remoto-reset-auth"
endpoint)))
(error
;; ghub could not resolve auth at all. Fail loudly so the
;; user knows auth is the problem, not a missing repo.
(setq remoto--auth-failed t)
(user-error "Remoto: authentication failed for %s (%s); \
configure a GitHub token in auth-source, then M-x remoto-reset-auth"
endpoint (error-message-string err)))))))
(defun remoto--paginated-api (endpoint per-page &optional max-pages)
"Fetch all pages of paginated GitHub API ENDPOINT via `remoto--api'.
Request PER-PAGE items per page, following pages until a short page is
returned or MAX-PAGES (default 10) is reached. The cap bounds latency
and request count on very large repositories."
(let ((query-endpoint (concat endpoint (if (cl-search "?" endpoint) "&" "?"))))
(cl-loop for page from 1 to (or max-pages 10)
for page-data = (remoto--api
(format "%sper_page=%d&page=%d"
query-endpoint per-page page))
append page-data
until (< (length page-data) per-page))))
(defun remoto-reset-auth ()
"Clear the auth failure cache, retrying token lookup on next API call.
Use after adding a GitHub token to auth-source."
(interactive)
(setq remoto--auth-failed nil
remoto--effective-auth nil
remoto--authenticated-user nil)
(message "Remoto: auth cache cleared; will retry token lookup on next request"))
(defun remoto--default-branch (owner repo)
"Fetch the default branch for OWNER/REPO."
(let ((data (remoto--api (format "repos/%s/%s" owner repo))))
(alist-get 'default_branch data)))
(defconst remoto--dir-entry
'((type . "tree") (size . 0) (sha . "") (mode . "040000"))
"Alist for synthesized directory entries (root, intermediates, `.', `..').")
;;;; Tree cache
(defvar remoto--tree-cache (make-hash-table :test 'equal)
"Cache: \"owner/repo@ref\" -> hash table of path -> entry plist.")
(defvar remoto--default-branch-cache (make-hash-table :test 'equal)
"Cache: \"owner/repo\" -> default branch name.")
(defvar remoto--branches-cache (make-hash-table :test 'equal)
"Cache: \"owner/repo\" -> (TIMESTAMP . BRANCH-NAMES).")
(defvar remoto--users-cache (make-hash-table :test 'equal)
"Cache: query string -> (TIMESTAMP . USER-NAMES).
Entries expire after `remoto-search-cache-ttl' seconds.")
(defun remoto--resolve-ref (parsed)
"Ensure PARSED `remoto-path' has a concrete ref, resolving if needed.
Returns a new `remoto-path' with ref filled in."
(if (remoto-path-ref parsed)
parsed
(let* ((owner (remoto-path-owner parsed))
(repo (remoto-path-repo parsed))
(repo-id (format "%s/%s" owner repo))
(branch (or (gethash repo-id remoto--default-branch-cache)
(let ((b (remoto--default-branch owner repo)))
(puthash repo-id b remoto--default-branch-cache)
b))))
(remoto-path-create
:owner owner :repo repo :ref branch
:path (remoto-path-path parsed)))))
(defun remoto--fetch-tree (owner repo ref)
"Fetch full tree for OWNER/REPO at REF from GitHub API.
Returns a hash table of path -> alist with keys type, size, sha, mode."
(let* ((endpoint (format "repos/%s/%s/git/trees/%s?recursive=1" owner repo ref))
(data (remoto--api endpoint))
(entries (alist-get 'tree data))
(truncated (alist-get 'truncated data))
(table (make-hash-table :test 'equal :size (length entries))))
(when (eq truncated t)
(puthash "\0truncated" t table)
(message "Remoto: tree truncated for %s/%s@%s, fetching dirs on demand"
owner repo ref))
;; Root entry
(puthash "" remoto--dir-entry table)
(puthash "/" remoto--dir-entry table)
;; All entries from API
(dolist (entry entries)
(let ((path (alist-get 'path entry))
(plist (list (cons 'type (alist-get 'type entry))
(cons 'size (or (alist-get 'size entry) 0))
(cons 'sha (alist-get 'sha entry))
(cons 'mode (alist-get 'mode entry)))))
(puthash path plist table)
;; Synthesize intermediate directories
(let ((parts (split-string path "/" t)))
(when (< 1 (length parts))
(cl-loop for i from 1 below (length parts)
for dir = (mapconcat #'identity (seq-take parts i) "/")
unless (gethash dir table)
do (puthash dir remoto--dir-entry table))))))
table))
(defun remoto--ensure-tree (parsed)
"Ensure tree is cached for PARSED path, return the tree hash table."
(let* ((resolved (remoto--resolve-ref parsed))
(key (remoto--repo-key resolved)))
(or (gethash key remoto--tree-cache)
(let* ((tree (remoto--fetch-tree
(remoto-path-owner resolved)
(remoto-path-repo resolved)
(remoto-path-ref resolved))))
(puthash key tree remoto--tree-cache)
tree))))
(defun remoto--fetch-directory-contents (parsed dir-key tree)
"Fetch DIR-KEY via Contents API for PARSED repo, merge into TREE.
On-demand fallback for repos whose recursive tree was truncated."
(let* ((resolved (remoto--resolve-ref parsed))
(endpoint (if (string-empty-p dir-key)
(format "repos/%s/%s/contents?ref=%s"
(remoto-path-owner resolved)
(remoto-path-repo resolved)
(remoto-path-ref resolved))
(format "repos/%s/%s/contents/%s?ref=%s"
(remoto-path-owner resolved)
(remoto-path-repo resolved)
(url-hexify-string dir-key)
(remoto-path-ref resolved))))
(data (condition-case nil
(remoto--api endpoint)
(user-error nil))))
(puthash (concat "\0fetched:" dir-key) t tree)
;; Contents API returns a list of alists for directories
(when (and (consp data) (consp (caar data)))
(dolist (entry data)
(let* ((path (alist-get 'path entry))
(api-type (alist-get 'type entry))
(type (if (equal api-type "dir") "tree" "blob"))
(plist (list (cons 'type type)
(cons 'size (or (alist-get 'size entry) 0))
(cons 'sha (or (alist-get 'sha entry) ""))
(cons 'mode (if (equal type "tree") "040000" "100644")))))
;; Keep existing entries from Trees API (they have richer mode info)
(unless (gethash path tree)
(puthash path plist tree)))))))
(defvar remoto--dir-contents-cache (make-hash-table :test 'equal)
"Cache: \"owner/repo@ref:dir\" -> (TIMESTAMP . CHILDREN-LIST).
Stores lightweight directory listings from Contents API.")
(defun remoto--fetch-dir-children-light (owner repo ref dir-path)
"Fetch direct children of DIR-PATH in OWNER/REPO@REF via Contents API.
Returns a list of (NAME . PLIST) pairs, capped at 20 entries.
Uses cache when available. Much faster than recursive tree fetch."
(let* ((key (format "%s/%s@%s:%s" owner repo ref (or dir-path "")))
(entry (gethash key remoto--dir-contents-cache))
(now (float-time)))
(if (and entry
(or (zerop remoto-search-cache-ttl)
(< (- now (car entry)) remoto-search-cache-ttl)))
(cdr entry)
(condition-case nil
(let* ((endpoint (if (or (null dir-path) (string-empty-p dir-path))
(format "repos/%s/%s/contents?ref=%s"
owner repo ref)
(format "repos/%s/%s/contents/%s?ref=%s"
owner repo (url-hexify-string dir-path) ref)))
(data (remoto--api endpoint))
(children
(when (and (consp data) (consp (caar data)))
(let ((result nil))
(dolist (item (seq-take data 20))
(let* ((name (alist-get 'name item))
(api-type (alist-get 'type item))
(type (if (equal api-type "dir") "tree" "blob"))
(plist (list (cons 'type type)
(cons 'size (or (alist-get 'size item) 0))
(cons 'sha (or (alist-get 'sha item) ""))
(cons 'mode (if (equal type "tree")
"040000" "100644")))))
(push (cons name plist) result)))
(nreverse result)))))
(puthash key (cons now children) remoto--dir-contents-cache)
children)
(error nil)))))
(defun remoto--tree-lookup-key (path)
"Normalize PATH for tree hash-table lookup.
Strips leading/trailing slashes and collapses runs of slashes."
(let ((p (replace-regexp-in-string "/+" "/" path)))
(when (string-prefix-p "/" p)
(setq p (substring p 1)))
(when (and (not (string-empty-p p))
(string-suffix-p "/" p))
(setq p (substring p 0 (1- (length p)))))
p))
(defun remoto--tree-entry (parsed)
"Look up the tree entry for PARSED path. Return plist or nil.
For truncated trees, fetches the parent directory on demand."
(let* ((tree (remoto--ensure-tree parsed))
(key (remoto--tree-lookup-key (remoto-path-path parsed))))
(or (gethash key tree)
(when (and (gethash "\0truncated" tree)
(not (string-empty-p key)))
(let ((parent (if (string-search "/" key)
(remoto--tree-lookup-key
(file-name-directory (directory-file-name key)))
"")))
(unless (gethash (concat "\0fetched:" parent) tree)
(remoto--fetch-directory-contents parsed parent tree))
(gethash key tree))))))
(defun remoto--tree-children (parsed)
"List direct children of directory at PARSED path.
Returns list of (NAME . PLIST) for each child.
For truncated trees, fetches the directory on demand."
(let* ((tree (remoto--ensure-tree parsed))
(dir-path (remoto--tree-lookup-key (remoto-path-path parsed)))
(_ (when (and (gethash "\0truncated" tree)
(not (gethash (concat "\0fetched:" dir-path) tree)))
(remoto--fetch-directory-contents parsed dir-path tree)))
(prefix (if (string-empty-p dir-path) "" (concat dir-path "/")))
(prefix-len (length prefix)))
(thread-last (hash-table-keys tree)
(seq-filter (lambda (path)
(and (not (string-prefix-p "\0" path))
(string-prefix-p prefix path)
(not (equal path dir-path))
;; Direct child: no more slashes after prefix
(not (string-search "/" (substring path prefix-len))))))
(mapcar (lambda (path)
(cons (substring path prefix-len)
(gethash path tree))))
(seq-remove (lambda (child) (string-empty-p (car child))))
(seq-sort (lambda (a b) (string< (car a) (car b)))))))
;;;; Path normalization helpers
(defun remoto--normalize-path (path)
"Clean up PATH component: collapse double slashes, resolve . and .."
(let* ((parts (split-string path "/" t))
(result nil))
(dolist (p parts)
(cond
((equal p "."))
((equal p "..")
(when result (pop result)))
(t (push p result))))
(let ((normalized (concat "/" (mapconcat #'identity (nreverse result) "/"))))
;; Preserve trailing slash for directories
(if (and (string-suffix-p "/" path)
(not (string-suffix-p "/" normalized)))
(concat normalized "/")
normalized))))
(defun remoto--file-name-prefix (filename)
"Extract the /github:owner/repo@ref: prefix from FILENAME."
(when (string-match (rx bos "/github:"
(+ (not ":"))
":")
filename)
(match-string 0 filename)))
;;;; File-name handler
(defconst remoto--shorthand-prefix "/gh:"
"Shorthand alias for the canonical /github: prefix.")
(defun remoto--normalize-shorthand (arg)
"Rewrite a leading /gh: shorthand in ARG to the canonical /github:.
A non-string ARG, or a string lacking the shorthand prefix, is returned
unchanged so downstream handlers only ever see canonical paths."
(if (and (stringp arg)
(string-prefix-p remoto--shorthand-prefix arg))
(concat "/github:" (substring arg (length remoto--shorthand-prefix)))
arg))
(defun remoto-file-name-handler (operation &rest args)
"Handle file OPERATION for remoto paths.
Dispatches to `remoto--handle-OPERATION' or falls through to defaults.
The /gh: shorthand in ARGS is normalized to /github: first, so every
resolved handler receives only canonical paths."
(let ((args (mapcar #'remoto--normalize-shorthand args)))
(if-let* ((handler (intern-soft (format "remoto--handle-%s" operation)))
((fboundp handler)))
(apply handler args)
;; Fall through to default handler
(let ((inhibit-file-name-handlers
(cons #'remoto-file-name-handler
(and (eq inhibit-file-name-operation operation)
inhibit-file-name-handlers)))
(inhibit-file-name-operation operation))
(apply operation args)))))
;;;; Read operations
(defun remoto--handle-file-exists-p (filename)
"Return t if FILENAME exists or is openable.
Returns nil for mid-completion paths (no selection made yet),
triggering variable `confirm-nonexistent-file-or-buffer' on RET."
(cond
;; /github: and /github:owner/ - directory-like, exist for navigation
((string-match (rx bos "/github:" (? "/") eos) filename) t)
((string-match (rx bos "/github:"
(+ (not (in "/:@#")))
"/" eos)
filename) t)
;; /github:owner/repo/ - openable as dired on default branch
((string-match (rx bos "/github:"
(+ (not (in "/:@#")))
"/"
(+ (not (in "/:@#")))
"/")
filename) t)
;; /github:owner/repo#NUM - specific issue ref, openable
((string-match (rx bos "/github:"
(+ (not (in "/:@#")))
"/"
(+ (not (in "/:@#")))
"#"
(+ digit) eos)
filename) t)
;; /github:owner/repo (bare) - NOT openable, still needs delimiter
((string-match (rx bos "/github:"
(+ (not (in "/:@#")))
"/"
(+ (not (in "/:@#")))
eos)
filename)
nil)
;; /github:owner/repo# or /github:owner/repo@ - delimiter without selection
((string-match (rx bos "/github:"
(+ (not (in "/:@#")))
"/"
(+ (not (in "/:@#")))
(in "@#") eos)
filename)
nil)
;; /github:owner# or /github:owner@ - no repo, invalid
((and (string-prefix-p "/github:" filename)
(not (remoto--parse-path filename))
(string-match (rx (in "@#") eos) filename))
nil)
;; Full canonical path - check tree
(t
(when-let* ((parsed (remoto--parse-path filename)))
;; The repository root at a ref is openable on its shape alone, the
;; way /github:owner/repo/ above is. Answering it from the tree
;; would cost one recursive tree per ref, because completion asks
;; this of every candidate it offers at the @ level.
(if (string-empty-p (remoto--tree-lookup-key (remoto-path-path parsed)))
t
(and (remoto--tree-entry parsed) t))))))
(defun remoto--handle-access-file (filename string)
"Return nil when FILENAME can be read, else signal `file-missing'.
STRING names the caller's purpose, as `access-file' documents. Without
this the operation falls through to the local primitive, which sees no
such file and always signals, and `recentf' then drops every remoto
path."
(unless (remoto--handle-file-exists-p filename)
(signal 'file-missing
(list string "No such file or directory" filename))))
(defun remoto--handle-file-directory-p (filename)
"Return t if FILENAME is a directory in the remote repo.
Also returns t for partial paths like /github: and /github:OWNER/."
(cond
;; /github: is a virtual directory root
((string-match (rx bos "/github:" (? "/") eos) filename) t)
;; /github:owner/ is a virtual owner directory
((remoto--parse-partial-github-path
(remoto--handle-file-name-as-directory filename))
t)
(t
(when-let* ((parsed (remoto--parse-path filename))
(entry (remoto--tree-entry parsed)))
(equal "tree" (alist-get 'type entry))))))
(defun remoto--handle-file-accessible-directory-p (filename)
"Return t if FILENAME is an accessible directory.
Delegates to `file-directory-p' - remote dirs are always readable."
(remoto--handle-file-directory-p filename))
(defun remoto--handle-file-regular-p (filename)
"Return t if FILENAME is a regular file in the remote repo."
(when-let* ((parsed (remoto--parse-path filename))
(entry (remoto--tree-entry parsed)))
(equal "blob" (alist-get 'type entry))))
(defun remoto--handle-file-readable-p (filename)
"Return non-nil if remote FILENAME is readable."
(remoto--handle-file-exists-p filename))
(defun remoto--handle-file-writable-p (_filename)
"Remote repos are never writable."
nil)
(defun remoto--handle-file-attributes (filename &optional _id-format)
"Return file attributes for FILENAME.
Synthesized from tree cache - timestamps are epoch 0."
(when-let* ((parsed (remoto--parse-path filename))
(entry (remoto--tree-entry parsed)))
(let* ((dir? (equal "tree" (alist-get 'type entry)))
(size (or (alist-get 'size entry) 0))
(mode-str (or (alist-get 'mode entry) "100644"))
(mode (string-to-number mode-str 8))
;; Use epoch 0 for all timestamps
(time '(0 0 0 0)))
;; Return vector matching `file-attributes' format:
;; (type links uid gid atime mtime ctime size mode
;; gid-change inode device)
(list (if dir? t nil) ; type: t=dir, nil=file
1 ; links
0 ; uid
0 ; gid
time ; atime
time ; mtime
time ; ctime
size ; size
(format "%05o" mode) ; mode string
nil ; gid-change
0 ; inode
0)))) ; device
(defun remoto--handle-directory-files (directory &optional full match nosort count)
"List files in remote DIRECTORY.
FULL, MATCH, NOSORT, COUNT as per `directory-files'."
(when-let* ((parsed (remoto--parse-path directory)))
(let ((names (append '("." "..")
(mapcar #'car (remoto--tree-children parsed)))))
(when match
(setq names (seq-filter (lambda (name)
(string-match-p match name))
names)))
(unless nosort
(setq names (sort names #'string<)))
(when count
(setq names (seq-take names count)))
(if full
(let ((prefix (remoto--file-name-prefix directory))
(dir-path (remoto-path-path parsed)))
(mapcar (lambda (name)
(concat prefix
(remoto--normalize-path
(concat dir-path "/" name))))
names))
names))))
(defun remoto--handle-directory-files-and-attributes
(directory &optional full match nosort id-format)
"Like `directory-files-and-attributes' for remote DIRECTORY.
Pass FULL, MATCH, NOSORT, and ID-FORMAT through unchanged."
(let* ((parsed (remoto--parse-path directory))
(prefix (remoto--file-name-prefix directory))
(base-path (lambda (f)
(concat prefix
(remoto--normalize-path
(concat (remoto-path-path parsed) "/" f))))))
(thread-last
(remoto--handle-directory-files directory full match nosort)
(mapcar (lambda (f)
(cons f (remoto--handle-file-attributes
(if full f (funcall base-path f))
id-format)))))))
(defun remoto--parse-partial-github-path (directory)
"Parse a partial /github: DIRECTORY for pre-repo completion.
Returns a plist with :level plus context keys, or nil.
Levels: `root', `owner', `repo' (branches/tags), `files-default', `issues'."
(when (stringp directory)
(cond
;; /github:
((string-match (rx bos "/github:" eos) directory)
(list :level 'root :owner nil))
;; /github:owner/repo# - issues level (repo must contain no /:@#)
((string-match (rx bos "/github:"
(group (+ (not (in "/:@#"))))
"/"
(group (+ (not (in "/:@#"))))
"#" eos)
directory)
(list :level 'issues
:owner (match-string 1 directory)
:repo (match-string 2 directory)))
;; /github:owner/repo@ - branches/tags level
((string-match (rx bos "/github:"
(group (+ (not (in "/:@#"))))
"/"
(group (+ (not (in "/:@#"))))
"@" (? "/") eos)
directory)
(list :level 'repo
:owner (match-string 1 directory)
:repo (match-string 2 directory)))
;; /github:owner/repo/ or /github:owner/repo/subdir/ - files-default
((string-match (rx bos "/github:"
(group (+ (not (in "/:@#"))))
"/"