Repository navigation
Expand file tree
/
Copy pathshare.go
More file actions
450 lines (409 loc) · 12.8 KB
/
Copy pathshare.go
File metadata and controls
450 lines (409 loc) · 12.8 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
package main
import (
"context"
"crypto/sha256"
"encoding/hex"
"flag"
"fmt"
"log"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
"github.com/fsnotify/fsnotify"
)
func runShare(args []string) error {
return runShareWithCtx(context.Background(), args)
}
func runWatchCmd(args []string) error {
return runWatchCmdWithCtx(context.Background(), args)
}
func runWatchCmdWithCtx(ctx context.Context, args []string) error {
return runShareWithCtx(ctx, append([]string{"--watch"}, args...))
}
const shareUsage = "usage: gander share [--watch] [--foreground] [--silent] [--existing] [--no-recursive] [--glob=pattern] [--yes] [--visibility=anyone|private|hidden] [--private] [--comments=anyone|private|disabled] [--no-comments] [--label name] [--no-labels] [--source cli|skill|plugin-claude|plugin-cursor|plugin-grok|unknown] <file.md|dir>"
func runShareWithCtx(ctx context.Context, args []string) error {
fs := flag.NewFlagSet("share", flag.ContinueOnError)
watch := fs.Bool("watch", false, "live-update the shared page as the file changes")
foreground := fs.Bool("foreground", false, "keep share --watch in-process instead of handing off to the runner")
silent := fs.Bool("silent", false, "create or refresh the share without opening a browser")
existing := fs.Bool("existing", false, "with a directory, also onboard unmatched .md files already in the folder")
noRecursive := fs.Bool("no-recursive", false, "with a directory, do not watch subdirectories")
glob := fs.String("glob", "", "with a directory, filename glob (default **/*.md)")
yes := fs.Bool("yes", false, "confirm onboarding more than 50 existing files")
comments := fs.String("comments", "", "who may comment: anyone, private, or disabled")
visibility := fs.String("visibility", "", "who may see the document: anyone, private, or hidden")
private := fs.Bool("private", false, "make the document private (alias for --visibility private)")
noComments := fs.Bool("no-comments", false, "turn off commenting (alias for --comments disabled)")
var labels stringList
fs.Var(&labels, "label", "set a label (repeatable; replaces the set)")
noLabels := fs.Bool("no-labels", false, "clear labels")
sourceFlag := fs.String("source", "", "install source (cli, skill, plugin-claude, plugin-cursor, plugin-grok, unknown); default GANDER_SOURCE")
if err := fs.Parse(args); err != nil {
return err
}
rest := fs.Args()
if len(rest) != 1 {
return fmt.Errorf("%s", shareUsage)
}
opts, err := shareOptsFromFlags(fs, *comments, *visibility, *private, *noComments, labels, *noLabels)
if err != nil {
return err
}
opts.InstallSource, err = resolveInstallSource(*sourceFlag)
if err != nil {
return err
}
canonical, err := canonicalPath(rest[0])
if err != nil {
return err
}
fi, err := os.Stat(canonical)
if err != nil {
return fmt.Errorf("stat %s: %w", canonical, err)
}
dirFlags := *existing || *noRecursive || *glob != "" || *yes
if fi.IsDir() {
return runWatchDir(canonical, *watch, *foreground, *existing, *noRecursive, *glob, *yes, opts)
}
if dirFlags {
return fmt.Errorf("--existing, --no-recursive, --glob, and --yes only apply to directories")
}
cfg, err := requireAuth()
if err != nil {
return err
}
content, err := os.ReadFile(canonical)
if err != nil {
return fmt.Errorf("read %s: %w", canonical, err)
}
cli := newAPIClient(cfg.APIURL, cfg.APIToken)
_, hadLocal := cfg.Shares[canonical]
opts, err = applyShareConfigDefaults(opts, cfg, !hadLocal)
if err != nil {
return err
}
opts = applyShareLabels(opts, canonical, string(content), !hadLocal, *silent || runningUnderAgent())
sh, created, err := cli.CreateShare(filepath.Base(canonical), canonical, string(content), *watch, opts)
if err != nil {
return fmt.Errorf("create: %w", err)
}
if err := checkSharePolicyEcho(opts, sh); err != nil {
return err
}
cfg.Shares[canonical] = sh.ShortID
if err := WriteConfig(cfg); err != nil {
return fmt.Errorf("save mapping: %w", err)
}
_ = touchInboxPollWindow()
if !created || hadLocal {
fmt.Printf("Already shared %s as %s — refreshing content in place.\n", canonical, sh.URL)
} else {
fmt.Printf("Shared %s as %s\n", canonical, sh.URL)
}
if !*silent && opts.DocVisibility != "hidden" {
openBrowserURL(sh.URL)
}
if *watch {
if *foreground {
return runWatchAndPushCtx(ctx, canonical, sh, cfg)
}
return handOffShareWatch(ctx, canonical, sh, cfg)
}
return nil
}
// handOffShareWatch registers the share with the runner daemon and exits.
// The daemon owns the fsnotify loop and pushes content updates to gandermd
// over the watcher's lifetime; the CLI returns immediately.
func handOffShareWatch(_ context.Context, absPath string, sh *shareResp, cfg Config) error {
home, err := runnerHomeForCLI()
if err != nil {
return err
}
if _, err := ensureRunner(home); err != nil {
return err
}
resp, err := ipcRoundTrip(home, ipcRequest{
Op: "watch",
Path: absPath,
Mode: "share",
UUID: sh.UUID,
ShortID: sh.ShortID,
ShareURL: sh.URL,
})
if err != nil {
return err
}
if !resp.OK {
return fmt.Errorf("runner rejected share watch: %s", resp.Error)
}
fmt.Printf("runner: pushing changes to %s from %s\n", sh.URL, resp.ID)
return nil
}
func runWatchDir(canonical string, watch, foreground, existing, noRecursive bool, glob string, yes bool, opts shareOpts) error {
if !watch {
return fmt.Errorf("sharing a directory requires --watch")
}
if foreground {
return fmt.Errorf("directory watches require the runner; drop --foreground")
}
if glob != "" {
if _, err := filepath.Match(glob, "x"); err != nil {
return fmt.Errorf("invalid --glob: %w", err)
}
}
if _, err := requireAuth(); err != nil {
return err
}
return handOffWatchDir(canonical, string(modeDirShare), dirWatchOpts{
Recursive: !noRecursive,
Glob: glob,
Existing: existing,
Yes: yes,
Policy: opts,
})
}
func canonicalPath(p string) (string, error) {
abs, err := filepath.Abs(p)
if err != nil {
return "", fmt.Errorf("resolve path: %w", err)
}
if resolved, err := filepath.EvalSymlinks(abs); err == nil {
abs = resolved
}
return filepath.Clean(abs), nil
}
func lookupShare(cli *apiClient, shortID string) (*shareResp, error) {
all, err := cli.ListShares()
if err != nil {
return nil, err
}
for i := range all {
if all[i].ShortID == shortID {
return &all[i], nil
}
}
return nil, fmt.Errorf("local mapping points at %s but it is not in your account; run `gander list` to sync", shortID)
}
func runWatchAndPush(absPath string, sh *shareResp, cfg Config) error {
return runWatchAndPushCtx(context.Background(), absPath, sh, cfg)
}
func runWatchAndPushCtx(ctx context.Context, absPath string, sh *shareResp, cfg Config) error {
sigCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
runCtx, runCancel := context.WithCancel(ctx)
defer runCancel()
go func() {
select {
case <-sigCtx.Done():
runCancel()
case <-runCtx.Done():
}
}()
pusher := &watchPusher{
absPath: absPath,
shareUUID: sh.UUID,
shortID: sh.ShortID,
cli: newAPIClient(cfg.APIURL, cfg.APIToken),
onArchived: runCancel,
}
fmt.Printf("Watching %s — pushing changes to %s. Press Ctrl+C to stop.\n", absPath, sh.URL)
return serveShareWatcher(runCtx, pusher, absPath, cfg.DebounceMs)
}
// serveShareWatcher runs fsnotify on absPath and pushes content updates via pusher.push
// until ctx is cancelled. Returns nil on clean cancellation; an fsnotify init error
// otherwise. The runner will invoke this from a goroutine per registered watch.
func serveShareWatcher(ctx context.Context, pusher *watchPusher, absPath string, debounceMs int) error {
debounce := time.Duration(debounceMs) * time.Millisecond
if debounce < 50*time.Millisecond {
debounce = 50 * time.Millisecond
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Printf("watcher init: %v", err)
return err
}
defer watcher.Close()
if err := watcher.Add(absPath); err != nil {
log.Printf("watch %s: %v", absPath, err)
return err
}
var pending *time.Timer
for {
select {
case <-ctx.Done():
if pending != nil {
pending.Stop()
}
return nil
case ev, ok := <-watcher.Events:
if !ok {
return nil
}
if ev.Op&(fsnotify.Write|fsnotify.Create) == 0 {
continue
}
if pending != nil {
pending.Stop()
}
pending = time.AfterFunc(debounce, pusher.push)
case _, ok := <-watcher.Errors:
if !ok {
return nil
}
}
}
}
func openBrowserURL(url string) {
if err := openBrowser(url); err != nil {
fmt.Fprintf(os.Stderr, "warning: could not open browser: %v\n", err)
}
}
type watchPusher struct {
absPath string
shareUUID string
shortID string
cli *apiClient
onArchived func()
lastHash string
}
func (w *watchPusher) push() {
data, err := os.ReadFile(w.absPath)
if err != nil {
log.Printf("read: %v", err)
return
}
sum := sha256.Sum256(data)
h := hex.EncodeToString(sum[:])
if h == w.lastHash {
return
}
w.lastHash = h
if _, err := w.cli.UpdateShare(w.shareUUID, string(data)); err != nil {
if isArchivedConflict(err) {
log.Printf("share archived; stopping watch %s", w.absPath)
if w.onArchived != nil {
w.onArchived()
}
return
}
log.Printf("push to gandermd: %v", err)
return
}
fmt.Println("Pushed update.")
}
func signalNotify(ch chan<- os.Signal) {
signal.Notify(ch, os.Interrupt, syscall.SIGTERM)
}
func requireAuth() (Config, error) {
cfg, err := LoadConfig()
if err != nil {
return cfg, err
}
if cfg.APIToken == "" {
return cfg, fmt.Errorf("not signed up — run `gander signup --email you@example.com` first")
}
return cfg, nil
}
func flagSetVisited(fs *flag.FlagSet, name string) bool {
found := false
fs.Visit(func(f *flag.Flag) {
if f.Name == name {
found = true
}
})
return found
}
func shareOptsFromFlags(fs *flag.FlagSet, comments, visibility string, private, noComments bool, labels stringList, noLabels bool) (shareOpts, error) {
commentsSet := flagSetVisited(fs, "comments")
visibilitySet := flagSetVisited(fs, "visibility")
if commentsSet {
switch comments {
case "anyone", "private", "disabled":
default:
return shareOpts{}, fmt.Errorf("--comments must be anyone, private, or disabled")
}
}
if visibilitySet {
switch visibility {
case "anyone", "private", "hidden":
default:
return shareOpts{}, fmt.Errorf("--visibility must be anyone, private, or hidden")
}
}
if noComments && commentsSet && comments != "disabled" {
return shareOpts{}, fmt.Errorf("--no-comments cannot be combined with --comments %s", comments)
}
if private && visibilitySet && visibility != "private" {
return shareOpts{}, fmt.Errorf("--private cannot be combined with --visibility %s", visibility)
}
access := ""
if commentsSet {
access = comments
} else if noComments {
access = "disabled"
}
doc := ""
if visibilitySet {
doc = visibility
} else if private {
doc = "private"
}
if access == "anyone" && (doc == "private" || doc == "hidden") {
if private && !visibilitySet {
return shareOpts{}, fmt.Errorf("--comments anyone cannot be combined with --private")
}
return shareOpts{}, fmt.Errorf("--comments anyone cannot be combined with --visibility %s", doc)
}
if noLabels && len(labels) > 0 {
return shareOpts{}, fmt.Errorf("--no-labels cannot be combined with --label")
}
opts := shareOpts{CommentAccess: access, DocVisibility: doc}
if noLabels {
empty := []string{}
opts.Labels = &empty
} else if len(labels) > 0 {
cp := append([]string{}, labels...)
opts.Labels = &cp
}
return opts, nil
}
func applyShareConfigDefaults(opts shareOpts, cfg Config, isNew bool) (shareOpts, error) {
if !isNew {
return opts, nil
}
if opts.DocVisibility == "" && cfg.DocVisibility != "" {
switch cfg.DocVisibility {
case "anyone", "private", "hidden":
opts.DocVisibility = cfg.DocVisibility
default:
return shareOpts{}, fmt.Errorf("doc_visibility must be anyone, private, or hidden")
}
}
if opts.CommentAccess == "" && cfg.CommentAccess != "" {
switch cfg.CommentAccess {
case "anyone", "private", "disabled":
opts.CommentAccess = cfg.CommentAccess
default:
return shareOpts{}, fmt.Errorf("comment_access must be anyone, private, or disabled")
}
}
if opts.CommentAccess == "anyone" && (opts.DocVisibility == "private" || opts.DocVisibility == "hidden") {
return shareOpts{}, fmt.Errorf("comment_access anyone cannot be combined with doc_visibility %s", opts.DocVisibility)
}
return opts, nil
}
func checkSharePolicyEcho(opts shareOpts, sh *shareResp) error {
if opts.CommentAccess != "" && sh.CommentAccess == "" {
return fmt.Errorf("gandermd does not support --comments; upgrade the server")
}
if opts.DocVisibility != "" && sh.DocVisibility == "" {
return fmt.Errorf("gandermd does not support --visibility; upgrade the server")
}
if opts.Labels != nil && sh.Labels == nil {
return fmt.Errorf("gandermd does not support --label; upgrade the server")
}
return nil
}
var _ = context.Background