-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathgit.go
More file actions
3567 lines (3140 loc) · 105 KB
/
Copy pathgit.go
File metadata and controls
3567 lines (3140 loc) · 105 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
package main
import (
"context"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"slices"
"strconv"
"strings"
"sync"
"time"
"fiatjaf.com/nostr"
"fiatjaf.com/nostr/nip19"
"fiatjaf.com/nostr/nip34"
"fiatjaf.com/nostr/nip34/gitnaturalapi"
"fiatjaf.com/nostr/nip34/grasp"
"github.com/AlecAivazis/survey/v2"
"github.com/fatih/color"
"github.com/urfave/cli/v3"
)
var git = &cli.Command{
Name: "git",
Usage: "git-related operations",
Description: `this implements versions of common git commands, like 'clone', 'fetch', 'pull' and 'push', but differently from the normal git commands these never take a remote name, the remote is assumed to what is defined by nip34 events and specified in the (automatically hidden) nip34.json file.
aside from those, there is also:
- 'nak git init' for setting up nip34 repository metadata; and
- 'nak git sync' for getting the latest metadata update from nostr relays (called automatically by other commands)
`,
Commands: []*cli.Command{
{
Name: "init",
Usage: "initialize a nip34 repository configuration",
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "interactive",
Aliases: []string{"i"},
Usage: "prompt for repository details interactively",
},
&cli.BoolFlag{
Name: "force",
Aliases: []string{"f"},
Usage: "overwrite existing nip34.json file",
},
&cli.StringFlag{
Name: "identifier",
Usage: "unique identifier for the repository",
},
&cli.StringFlag{
Name: "name",
Usage: "repository name",
},
&cli.StringFlag{
Name: "description",
Usage: "repository description",
},
&cli.StringSliceFlag{
Name: "web",
Usage: "web URLs for the repository (can be used multiple times)",
},
&cli.StringFlag{
Name: "owner",
Usage: "owner public key",
},
&cli.StringSliceFlag{
Name: "grasp-servers",
Usage: "grasp servers (can be used multiple times)",
},
&cli.StringSliceFlag{
Name: "relays",
Usage: "relay URLs to publish to (can be used multiple times)",
},
&cli.StringFlag{
Name: "earliest-unique-commit",
Usage: "earliest unique commit of the repository",
},
},
Action: func(ctx context.Context, c *cli.Command) error {
// check if current directory is a git repository
cmd := exec.Command("git", "rev-parse", "--git-dir")
if err := cmd.Run(); err != nil {
// initialize a git repository
log("initializing git repository...\n")
initCmd := exec.Command("git", "init")
initCmd.Stderr = os.Stderr
initCmd.Stdout = os.Stdout
if err := initCmd.Run(); err != nil {
return fmt.Errorf("failed to initialize git repository: %w", err)
}
}
var defaultOwner string
var defaultIdentifier string
// check if nip34.json already exists
existingConfig, err := readNip34ConfigFile("")
if err == nil {
// file exists
if !c.Bool("force") && !c.Bool("interactive") {
return fmt.Errorf("nip34.json already exists, use --force to overwrite or --interactive to update")
}
defaultIdentifier = existingConfig.Identifier
defaultOwner = existingConfig.Owner
} else {
// extract info from nostr:// git remotes (this is just for migrating from ngit)
output, err := exec.Command("git", "remote", "-v").Output()
if err == nil {
for _, remote := range strings.Split(strings.TrimSpace(string(output)), "\n") {
if !strings.Contains(remote, "nostr://") {
continue
}
parts := strings.Fields(remote)
if len(parts) < 2 {
continue
}
// parse nostr://npub.../relay_hostname/identifier
remoteOwner, remoteIdentifier, relays, err := parseRepositoryAddress(ctx, parts[1])
if err != nil || len(relays) == 0 {
continue
}
defaultIdentifier = remoteIdentifier
defaultOwner = nip19.EncodeNpub(remoteOwner)
}
}
}
// get repository base directory name for defaults
if defaultIdentifier == "" {
cwd, err := os.Getwd()
if err != nil {
return fmt.Errorf("failed to get current directory: %w", err)
}
defaultIdentifier = filepath.Base(cwd)
}
// prompt for identifier first
var identifier string
if c.String("identifier") != "" {
identifier = c.String("identifier")
} else if c.Bool("interactive") {
if err := survey.AskOne(&survey.Input{
Message: "identifier",
Default: defaultIdentifier,
}, &identifier); err != nil {
return err
}
} else {
identifier = defaultIdentifier
}
// prompt for owner pubkey
var owner nostr.PubKey
var ownerStr string
if c.String("owner") != "" {
owner, err = parsePubKey(c.String("owner"))
if err != nil {
return fmt.Errorf("invalid owner pubkey: %w", err)
}
ownerStr = nip19.EncodeNpub(owner)
} else if c.Bool("interactive") {
for {
if err := survey.AskOne(&survey.Input{
Message: "owner (npub, nip05 or hex)",
Default: defaultOwner,
}, &ownerStr); err != nil {
return err
}
owner, err = parsePubKey(ownerStr)
if err == nil {
ownerStr = nip19.EncodeNpub(owner)
break
}
}
} else {
return fmt.Errorf("owner pubkey is required (use --owner or --interactive)")
}
// try to fetch existing repository announcement (kind 30617)
var fetchedRepo *nip34.Repository
if existingConfig.Identifier == "" {
log(" searching for existing events... ")
repo, _, _, _, err := fetchRepositoryAndState(ctx, owner, identifier, nil)
if err == nil && repo.Event.ID != nostr.ZeroID {
fetchedRepo = &repo
log("found one from %s.\n", repo.Event.CreatedAt.Time().Format(time.DateOnly))
} else {
log("none found.\n")
}
}
// set config with fetched values or defaults
var config Nip34Config
if fetchedRepo != nil {
config = RepositoryToConfig(*fetchedRepo)
} else if existingConfig.Identifier != "" {
config = existingConfig
} else {
// get earliest unique commit
var earliestCommit string
if output, err := exec.Command("git", "rev-list", "--max-parents=0", "HEAD").Output(); err == nil {
earliestCommit = strings.TrimSpace(string(output))
}
config = Nip34Config{
Identifier: identifier,
Owner: ownerStr,
Name: identifier,
Description: "",
GraspServers: []string{"gitnostr.com", "relay.ngit.dev"},
EarliestUniqueCommit: earliestCommit,
}
}
// helper to get value from flags, existing config, or default
getValue := func(existingVal, flagVal, defaultVal string) string {
if flagVal != "" {
return flagVal
}
if existingVal != "" {
return existingVal
}
return defaultVal
}
getSliceValue := func(existingVals, flagVals, defaultVals []string) []string {
if len(flagVals) > 0 {
return flagVals
}
if len(existingVals) > 0 {
return existingVals
}
return defaultVals
}
// override with flags and existing config
// (identifier and ownerStr already hold the flag value, the interactive answer or the default)
config.Identifier = identifier
config.Name = getValue(existingConfig.Name, c.String("name"), config.Name)
config.Description = getValue(existingConfig.Description, c.String("description"), config.Description)
config.Owner = ownerStr
config.GraspServers = getSliceValue(existingConfig.GraspServers, c.StringSlice("grasp-servers"), config.GraspServers)
config.EarliestUniqueCommit = getValue(existingConfig.EarliestUniqueCommit, c.String("earliest-unique-commit"), config.EarliestUniqueCommit)
if c.Bool("interactive") {
// prompt for name
if err := survey.AskOne(&survey.Input{
Message: "name",
Default: config.Name,
}, &config.Name); err != nil {
return err
}
// prompt for description
if err := survey.AskOne(&survey.Input{
Message: "description",
Default: config.Description,
}, &config.Description); err != nil {
return err
}
// prompt for grasp servers
graspServers, err := promptForStringList("grasp servers", config.GraspServers, []string{
"gitnostr.com",
"relay.ngit.dev",
"pyramid.fiatjaf.com",
"git.shakespeare.diy",
}, graspServerHost, nil)
if err != nil {
return err
}
config.GraspServers = graspServers
// prompt for earliest unique commit
if err := survey.AskOne(&survey.Input{
Message: "earliest unique commit",
Default: config.EarliestUniqueCommit,
}, &config.EarliestUniqueCommit); err != nil {
return err
}
log("\n")
}
if err := config.Validate(); err != nil {
return fmt.Errorf("invalid config: %w", err)
}
// write config file
if err := writeNip34ConfigFile("", config); err != nil {
return err
}
log("created %s\n", color.GreenString("nip34.json"))
// setup git remotes
gitSetupRemotes(ctx, "", config.ToRepository())
// gitignore it
excludeNip34ConfigFile("")
log("edit %s if needed, then run %s to publish.\n",
color.CyanString("nip34.json"),
color.CyanString("nak git sync"))
return nil
},
},
{
Name: "sync",
Usage: "sync repository with relays",
Action: func(ctx context.Context, c *cli.Command) error {
kr, _, _ := gatherKeyerFromArguments(ctx, c)
_, _, err := gitSync(ctx, kr, false)
return err
},
},
{
Name: "clone",
Usage: "clone a NIP-34 repository from a nostr:// URI",
Description: `the <repository> parameter maybe in the form "<npub, hex, nprofile or nip05>/<identifier>", ngit-style like "nostr://<npub>/<relay>/<identifier>" or "nostr://<npub>/<identifier>" or an "naddr1..." code.`,
ArgsUsage: "<repository> [directory]",
Action: func(ctx context.Context, c *cli.Command) error {
args := c.Args()
if args.Len() == 0 {
return fmt.Errorf("missing repository address")
}
owner, identifier, relayHints, err := parseRepositoryAddress(ctx, args.Get(0))
if err != nil {
return fmt.Errorf("failed to parse remote url '%s': %s", args.Get(0), err)
}
// fetch repository metadata and state
repo, _, _, state, err := fetchRepositoryAndState(ctx, owner, identifier, relayHints)
if err != nil {
return err
}
// determine target directory
targetDir := ""
if args.Len() >= 2 {
targetDir = args.Get(1)
} else {
targetDir = repo.ID
}
if targetDir == "" {
targetDir = repo.ID
}
// if targetDir exists and is non-empty, bail
if fi, err := os.Stat(targetDir); err == nil && fi.IsDir() {
entries, err := os.ReadDir(targetDir)
if err == nil && len(entries) > 0 {
return fmt.Errorf("target directory '%s' already exists and is not empty", targetDir)
}
}
// create directory
if err := os.MkdirAll(targetDir, 0755); err != nil {
return fmt.Errorf("failed to create directory '%s': %w", targetDir, err)
}
// initialize git inside the directory
initCmd := exec.Command("git", "init")
initCmd.Dir = targetDir
if err := initCmd.Run(); err != nil {
return fmt.Errorf("failed to initialize git repository: %w", err)
}
// write nip34.json inside cloned directory
localConfig := RepositoryToConfig(repo)
if err := localConfig.Validate(); err != nil {
return fmt.Errorf("invalid config: %w", err)
}
// write nip34.json
if err := writeNip34ConfigFile(targetDir, localConfig); err != nil {
return err
}
// add nip34.json to .git/info/exclude in cloned repo
excludeNip34ConfigFile(targetDir)
// setup git remotes
gitSetupRemotes(ctx, targetDir, repo)
// fetch from each grasp remote
fetchFromRemotes(ctx, targetDir, repo)
// if we have a state with a HEAD, try to reset to it
if state != nil && state.HEAD != "" {
if headCommit, ok := state.Branches[state.HEAD]; ok {
// check if we have that commit
checkCmd := exec.Command("git", "cat-file", "-e", headCommit)
checkCmd.Dir = targetDir
if err := checkCmd.Run(); err == nil {
// commit exists, reset to it
log("resetting to commit %s...\n", color.CyanString(headCommit))
resetCmd := exec.Command("git", "reset", "--hard", headCommit)
resetCmd.Dir = targetDir
resetCmd.Stderr = os.Stderr
if err := resetCmd.Run(); err != nil {
log("! failed to reset: %v\n", color.YellowString("%v", err))
}
}
}
}
// update refs from state
if state != nil {
gitUpdateRefs(ctx, targetDir, *state)
}
log("cloned into %s\n", color.GreenString(targetDir))
return nil
},
},
{
Name: "download",
Usage: "download a file from a NIP-34 repository",
ArgsUsage: "<repository> <path>",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "output",
Aliases: []string{"O"},
Usage: "output path (use '-' for stdout)",
},
&cli.StringFlag{
Name: "ref",
Aliases: []string{"r"},
Usage: "git ref/tag/branch/commit to read from",
},
},
Action: func(ctx context.Context, c *cli.Command) error {
args := c.Args()
if args.Len() < 2 {
return fmt.Errorf("missing repository and path")
}
repo := args.Get(0)
path := args.Get(1)
outputPath := c.String("output")
ref := strings.TrimSpace(c.String("ref"))
if outputPath == "" {
cleaned := strings.TrimRight(path, "/")
base := filepath.Base(cleaned)
if base == "." || base == "/" || base == "" {
return fmt.Errorf("cannot determine output filename from path '%s', use --output", path)
}
outputPath = base
}
if outputPath != "-" {
if fi, err := os.Stat(outputPath); err == nil && fi.IsDir() {
return fmt.Errorf("output path '%s' is a directory", outputPath)
}
}
var gitURLs []string
if strings.HasPrefix(repo, "http://") || strings.HasPrefix(repo, "https://") {
gitURLs = []string{strings.TrimRight(repo, "/")}
} else {
owner, identifier, relayHints, err := parseRepositoryAddress(ctx, repo)
if err != nil {
return fmt.Errorf("failed to parse repository address '%s': %w", repo, err)
}
repo, _, _, state, err := fetchRepositoryAndState(ctx, owner, identifier, relayHints)
if err != nil {
var stateErr *StateErr
if ref == "" || !errors.As(err, &stateErr) {
return err
}
}
if ref == "" && state != nil && state.HEAD != "" {
ref = state.HEAD
}
for _, url := range repo.Clone {
if strings.HasPrefix(url, "http") {
gitURLs = append(gitURLs, url)
}
}
}
if len(gitURLs) == 0 {
return fmt.Errorf("no HTTP git URLs found for repository")
}
var lastErr error
for _, url := range gitURLs {
if lastErr != nil {
log("%s\n", color.HiRedString(lastErr.Error()))
}
lastErr = nil
{
printUrl := color.BlueString(url)
if grasp.IsGraspURL(url) {
printUrl = color.HiYellowString(strings.Split(url, "/")[2])
}
log("attempting download from %s... ", printUrl)
}
info, err := gitnaturalapi.GetInfoRefs(url)
if err != nil {
lastErr = err
continue
}
var commitHash string
if ref == "" {
if symref, ok := info.Symrefs["HEAD"]; ok && symref != "" {
commitHash, _ = info.Refs[symref]
} else if head, ok := info.Refs["HEAD"]; ok && head != "" {
commitHash = head
} else {
lastErr = fmt.Errorf("could not resolve default ref for %s", url)
continue
}
}
if gitHashRe.MatchString(ref) {
commitHash = ref
} else if strings.HasPrefix(ref, "refs/") {
if ch, ok := info.Refs[ref]; ok {
commitHash = ch
}
} else {
if ch, ok := info.Refs["refs/heads/"+ref]; ok {
commitHash = ch
} else if ch, ok := info.Refs["refs/tags/"+ref]; ok {
commitHash = ch
} else if sr, ok := info.Symrefs[ref]; ok {
commitHash = info.Refs[sr]
}
}
if commitHash == "" {
lastErr = fmt.Errorf("couldn't get a commit hash for ref '%s'", ref)
continue
}
if !gitHashRe.MatchString(commitHash) {
lastErr = fmt.Errorf("couldn't invalid commit hash for ref '%s': '%s'", ref, commitHash)
continue
}
entry, err := gitnaturalapi.GetObjectByPath(url, commitHash, path)
if err != nil {
lastErr = err
continue
}
if entry == nil {
lastErr = fmt.Errorf("path '%s' not found", path)
continue
}
if entry.IsDir {
lastErr = fmt.Errorf("path '%s' is a directory", path)
continue
}
obj, err := gitnaturalapi.GetObject(url, entry.Hash)
if err != nil {
lastErr = fmt.Errorf("download error: %s", err)
continue
}
if obj == nil {
lastErr = fmt.Errorf("object for '%s' not found", path)
continue
}
if obj.Type != gitnaturalapi.ObjectTypeBlob {
lastErr = fmt.Errorf("object at '%s' is not a file", path)
continue
}
if outputPath == "-" {
if _, err = os.Stdout.Write(obj.Data); err != nil {
return err
}
log("\nprinted object %s to stdout\n", color.CyanString(obj.Hash))
return nil
}
if err := os.WriteFile(outputPath, obj.Data, 0644); err != nil {
return fmt.Errorf("failed to write %s: %w", outputPath, err)
}
log("\nsaved object %s to %s\n", color.CyanString(obj.Hash), color.GreenString(outputPath))
return nil
}
if lastErr != nil {
log("%s\n", color.HiRedString(lastErr.Error()))
}
return fmt.Errorf("failed to download '%s' from '%s'", path, repo)
},
},
{
Name: "push",
Usage: "push git changes",
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "force",
Aliases: []string{"f"},
Usage: "force push to git remotes",
},
&cli.BoolFlag{
Name: "tags",
Usage: "push all refs under refs/tags",
},
&cli.BoolFlag{
Name: "no-announcement",
Usage: "skip publishing updated repository announcement event",
},
},
Action: func(ctx context.Context, c *cli.Command) error {
// setup signer
kr, _, err := gatherKeyerFromArguments(ctx, c)
if err != nil {
return fmt.Errorf("failed to gather keyer: %w", err)
}
// log publishing as npub
currentPk, _ := kr.GetPublicKey(ctx)
currentNpub := nip19.EncodeNpub(currentPk)
log("publishing as %s\n", color.CyanString(currentNpub))
// sync to ensure everything is up to date
repo, state, err := gitSync(ctx, kr, c.Bool("no-announcement"))
if err != nil {
return fmt.Errorf("failed to sync: %w", err)
}
currentPk, err = ensureGitRepositoryOwner(ctx, kr, repo, "push")
if err != nil {
return err
}
// figure out which branches to push
localBranch, remoteBranch, err := figureOutBranches(c, c.Args().First(), true)
if err != nil {
return err
}
// get commit for the local branch
res, err := exec.Command("git", "rev-parse", localBranch).Output()
if err != nil {
return fmt.Errorf("failed to get commit for branch %s: %w", localBranch, err)
}
currentCommit := strings.TrimSpace(string(res))
logverbose("pushing branch %s to remote branch %s, commit: %s\n", localBranch, remoteBranch, currentCommit)
// create a new state if we didn't find any
if state == nil {
state = &nip34.RepositoryState{
ID: repo.ID,
Branches: make(map[string]string),
Tags: make(map[string]string),
}
}
// update the branch
if !c.Bool("force") {
if prevCommit, exists := state.Branches[remoteBranch]; exists {
// check if prevCommit is an ancestor of currentCommit (fast-forward check)
cmd := exec.Command("git", "merge-base", "--is-ancestor", prevCommit, currentCommit)
if err := cmd.Run(); err != nil {
return fmt.Errorf("non-fast-forward push not allowed, use --force to override")
}
}
}
state.Branches[remoteBranch] = currentCommit
log("- setting branch %s to commit %s\n", color.CyanString(remoteBranch), color.CyanString(currentCommit))
// set the HEAD to the local branch if none is set
if state.HEAD == "" {
state.HEAD = remoteBranch
log("- setting HEAD to branch %s\n", color.CyanString(remoteBranch))
}
if c.Bool("tags") {
// add all refs/tags
output, err := exec.Command("git", "show-ref", "--tags").Output()
if err != nil && err.Error() != "exit status 1" {
// exit status 1 is returned when there are no tags, which should be ok for us
return fmt.Errorf("failed to get local tags: %s", err)
} else {
lines := strings.Split(strings.TrimSpace(string(output)), "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if line == "" {
continue
}
parts := strings.Fields(line)
if len(parts) != 2 {
continue
}
commitHash := parts[0]
ref := parts[1]
tagName := strings.TrimPrefix(ref, "refs/tags/")
if !c.Bool("force") {
// if --force is not passed then we can't overwrite tags
if existingHash, exists := state.Tags[tagName]; exists && existingHash != commitHash {
return fmt.Errorf("tag %s that is already published pointing to %s, call with --force to overwrite", tagName, existingHash)
}
}
state.Tags[tagName] = commitHash
log("- setting tag %s to commit %s\n", color.CyanString(tagName), color.CyanString(commitHash))
}
}
}
// create and sign the new state event
newStateEvent := state.ToEvent()
err = kr.SignEvent(ctx, &newStateEvent)
if err != nil {
return fmt.Errorf("error signing state event: %w", err)
}
log("- publishing updated repository state to " + color.CyanString("%v", repo.Relays) + "\n")
for res := range sys.Pool.PublishMany(ctx, repo.Relays, newStateEvent) {
if res.Error != nil {
log("! error publishing event to %s: %v\n", color.YellowString(res.RelayURL), res.Error)
} else {
log("> published to %s\n", color.GreenString(res.RelayURL))
}
}
// push to each grasp remote
pushSuccesses := 0
for _, relay := range repo.Relays {
relayURL := nostr.NormalizeURL(relay)
remoteName := gitRemoteName(relayURL)
log("pushing to %s...\n", color.CyanString(remoteName))
pushArgs := []string{"push", remoteName, fmt.Sprintf("%s:refs/heads/%s", localBranch, remoteBranch)}
if c.Bool("force") {
pushArgs = append(pushArgs, "--force")
}
if c.Bool("tags") {
pushArgs = append(pushArgs, "--tags")
}
pushCmd := exec.Command("git", pushArgs...)
pushCmd.Stderr = os.Stderr
pushCmd.Stdout = os.Stdout
if err := pushCmd.Run(); err != nil {
log("! failed to push to %s: %v\n", color.YellowString(remoteName), err)
} else {
log("> pushed to %s\n", color.GreenString(remoteName))
pushSuccesses++
}
}
if pushSuccesses == 0 {
return fmt.Errorf("failed to push to any remote")
}
gitUpdateRefs(ctx, "", *state)
return nil
},
},
{
Name: "pull",
Usage: "pull git changes",
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "rebase",
Usage: "rebase instead of merge",
},
&cli.BoolFlag{
Name: "ff-only",
Usage: "only allow fast-forward merges",
},
&cli.BoolFlag{
Name: "ff",
Usage: "allow fast-forward merges",
},
&cli.BoolFlag{
Name: "no-ff",
Usage: "always perform a merge instead of fast-forwarding",
},
},
Action: func(ctx context.Context, c *cli.Command) error {
// sync to fetch latest state and metadata
_, state, err := gitSync(ctx, nil, false)
if err != nil {
return fmt.Errorf("failed to sync: %w", err)
}
// figure out which branches to pull
localBranch, remoteBranch, err := figureOutBranches(c, c.Args().First(), false)
if err != nil {
return err
}
// get the commit from state for the remote branch
if state == nil || state.Event.ID == nostr.ZeroID {
return fmt.Errorf("no repository state found")
}
targetCommit, ok := state.Branches[remoteBranch]
if !ok {
return fmt.Errorf("branch '%s' not found in repository state", remoteBranch)
}
// check if the commit exists locally
checkCmd := exec.Command("git", "cat-file", "-e", targetCommit)
if err := checkCmd.Run(); err != nil {
return fmt.Errorf("commit %s not found locally, try 'nak git fetch' first", targetCommit)
}
// determine merge strategy
var strategy string
strategiesSpecified := 0
if c.Bool("rebase") {
strategy = "rebase"
strategiesSpecified++
}
if c.Bool("ff-only") {
strategy = "ff-only"
strategiesSpecified++
}
if c.Bool("no-ff") {
strategy = "no-ff"
strategiesSpecified++
}
if c.Bool("ff") {
strategy = "ff"
strategiesSpecified++
}
if strategiesSpecified > 1 {
return fmt.Errorf("flags --rebase, --ff-only, --ff, --no-ff are mutually exclusive")
}
if strategy == "" {
// check git config for pull.rebase
cmd := exec.Command("git", "config", "--get", "pull.rebase")
output, err := cmd.Output()
if err == nil && strings.TrimSpace(string(output)) == "true" {
strategy = "rebase"
} else if err == nil && strings.TrimSpace(string(output)) == "false" {
strategy = "ff"
} else {
// check git config for pull.ff
cmd := exec.Command("git", "config", "--get", "pull.ff")
output, err := cmd.Output()
if err == nil && strings.TrimSpace(string(output)) == "only" {
strategy = "ff-only"
}
}
}
// execute the merge or rebase
switch strategy {
case "rebase":
log("rebasing %s onto %s...\n", color.CyanString(localBranch), color.CyanString(targetCommit))
rebaseCmd := exec.Command("git", "rebase", targetCommit)
rebaseCmd.Stderr = os.Stderr
rebaseCmd.Stdout = os.Stdout
if err := rebaseCmd.Run(); err != nil {
return fmt.Errorf("rebase failed: %w", err)
}
case "ff-only":
log("pulling %s into %s (fast-forward only)...\n", color.CyanString(targetCommit), color.CyanString(localBranch))
mergeCmd := exec.Command("git", "merge", "--ff-only", targetCommit)
mergeCmd.Stderr = os.Stderr
mergeCmd.Stdout = os.Stdout
if err := mergeCmd.Run(); err != nil {
return fmt.Errorf("merge failed: %w", err)
}
case "no-ff":
log("pulling %s into %s (no fast-forward)...\n", color.CyanString(targetCommit), color.CyanString(localBranch))
mergeCmd := exec.Command("git", "merge", "--no-ff", targetCommit)
mergeCmd.Stderr = os.Stderr
mergeCmd.Stdout = os.Stdout
if err := mergeCmd.Run(); err != nil {
return fmt.Errorf("merge failed: %w", err)
}
case "ff":
log("pulling %s into %s...\n", color.CyanString(targetCommit), color.CyanString(localBranch))
mergeCmd := exec.Command("git", "merge", "--ff", targetCommit)
mergeCmd.Stderr = os.Stderr
mergeCmd.Stdout = os.Stdout
if err := mergeCmd.Run(); err != nil {
return fmt.Errorf("merge failed: %w", err)
}
default:
// get current commit
res, err := exec.Command("git", "rev-parse", localBranch).Output()
if err != nil {
return fmt.Errorf("failed to get current commit for branch %s: %w", localBranch, err)
}
currentCommit := strings.TrimSpace(string(res))
// check if fast-forward possible
cmd := exec.Command("git", "merge-base", "--is-ancestor", currentCommit, targetCommit)
if err := cmd.Run(); err != nil {
return fmt.Errorf("fast-forward merge not possible, specify --rebase, --ff-only, --ff, or --no-ff; or use git config")
}
// do fast-forward
log("fast-forwarding to %s...\n", color.CyanString(targetCommit))
mergeCmd := exec.Command("git", "merge", "--ff-only", targetCommit)
mergeCmd.Stderr = os.Stderr
mergeCmd.Stdout = os.Stdout
if err := mergeCmd.Run(); err != nil {
return fmt.Errorf("fast-forward failed: %w", err)
}
}
log("pull complete\n")
return nil
},
},
{
Name: "fetch",
Usage: "fetch git data",
Action: func(ctx context.Context, c *cli.Command) error {
_, _, err := gitSync(ctx, nil, false)
return err
},
},
{
Name: "patch",
Usage: "patch-related operations",
Description: "when called directly, lists open patches; with an patch id prefix, displays that patch with threaded discussions.",
ArgsUsage: "[id-prefix]",
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "applied",
Usage: "list only applied/merged patches",
},
&cli.BoolFlag{
Name: "closed",
Usage: "list only closed patches",
},
&cli.BoolFlag{
Name: "all",
Usage: "list all patches, including applied and closed",
},
},
Action: func(ctx context.Context, c *cli.Command) error {
repo, err := readGitRepositoryFromConfig()
if err != nil {
return err
}
events, err := fetchGitRepoRelatedEvents(ctx, repo, 1617)
if err != nil {
return err
}
prefix := strings.TrimSpace(c.Args().First())
if prefix == "" {
// list
statuses, err := fetchIssueStatus(ctx, repo, events)
if err != nil {
return err
}
if len(events) == 0 {
log("no patches found\n")
return nil
}
showApplied := c.Bool("applied")
showClosed := c.Bool("closed")
showAll := c.Bool("all")
// preload metadata from everybody
wg := sync.WaitGroup{}
for _, evt := range events {
wg.Go(func() {
sys.FetchProfileMetadata(ctx, evt.PubKey)
})
}
wg.Wait()
// now render
for _, evt := range events {
id := evt.ID.Hex()