-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
863 lines (715 loc) · 20.8 KB
/
main.go
File metadata and controls
863 lines (715 loc) · 20.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
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
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"sort"
"strconv"
"strings"
)
const version = "0.2.1"
type Command struct {
Name string
Usage string
Description string
Run func(args []string) error
}
var commands = map[string]Command{}
func registerCommand(cmd Command) {
commands[cmd.Name] = cmd
}
func init() {
// list
registerCommand(Command{
Name: "list",
Usage: "packager list",
Description: "List all cloned packages",
Run: func(args []string) error {
return listPackages()
},
})
// clone <repo-url>
registerCommand(Command{
Name: "clone",
Usage: "packager clone <repo-url>",
Description: "Clone a package from a git repository",
Run: func(args []string) error {
if len(args) < 1 {
return errors.New("missing <repo-url> for clone")
}
return clonePackage(args[0])
},
})
// pull <repo-url>
registerCommand(Command{
Name: "pull",
Usage: "packager pull <repo-url>",
Description: "Pull latest changes from a cloned package",
Run: func(args []string) error {
if len(args) < 1 {
return errors.New("missing <repo-url> for pull")
}
return pullPackage(args[0])
},
})
// push <repo-url>
registerCommand(Command{
Name: "push",
Usage: "packager push <repo-url>",
Description: "Push local changes to a cloned package",
Run: func(args []string) error {
if len(args) < 1 {
return errors.New("missing <repo-url> for push")
}
return pushPackage(args[0])
},
})
// sync <repo-url>
registerCommand(Command{
Name: "sync",
Usage: "packager sync <repo-url>",
Description: "Pull and then push changes to a cloned package",
Run: func(args []string) error {
if len(args) < 1 {
return errors.New("missing <repo-url> for sync")
}
return syncPackage(args[0])
},
})
// fix-repositories
registerCommand(Command{
Name: "fix-repositories",
Usage: "packager fix-repositories",
Description: "Ensure composer.json has a path repository for local packages",
Run: func(args []string) error {
return ensurePathRepositoryConfigured()
},
})
// version
registerCommand(Command{
Name: "version",
Usage: "packager version",
Description: "Show Packager version",
Run: func(args []string) error {
fmt.Printf("Packager %s\n", version)
return nil
},
})
// doctor
registerCommand(Command{
Name: "doctor",
Usage: "packager doctor",
Description: "Inspect local packages and composer configuration",
Run: func(args []string) error {
return runDoctor()
},
})
// pull-all
registerCommand(Command{
Name: "pull-all",
Usage: "packager pull-all",
Description: "Pull all local subrepos under packages/*/*",
Run: func(args []string) error {
return runPullAll()
},
})
// push-all
registerCommand(Command{
Name: "push-all",
Usage: "packager push-all",
Description: "Push all local subrepos under packages/*/*",
Run: func(args []string) error {
return runPushAll()
},
})
}
func main() {
if len(os.Args) < 2 {
printHelp("")
os.Exit(1)
}
subcommand := os.Args[1]
args := os.Args[2:]
// help alias
if subcommand == "help" || subcommand == "-h" || subcommand == "--help" {
if len(args) > 0 {
printHelp(args[0])
} else {
printHelp("")
}
return
}
cmd, ok := commands[subcommand]
if !ok {
fmt.Printf("Unknown command: %s\n\n", subcommand)
printHelp("")
os.Exit(1)
}
// Shared pre-flight checks
if err := ensureProjectRoot(); err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
if err := ensureBinaries("git", "composer"); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
if err := ensureGitSubrepo(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
if err := cmd.Run(args); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
func printHelp(forCommand string) {
fmt.Println()
fmt.Println("Packager: a bare bones workbench for local package development")
fmt.Println()
fmt.Println("Usage:")
fmt.Println(" packager <command> [<args>]")
fmt.Println()
if forCommand != "" {
cmd, ok := commands[forCommand]
if !ok {
fmt.Printf("Unknown command: %s\n\n", forCommand)
} else {
fmt.Printf("Command: %s\n", cmd.Name)
fmt.Printf("Usage: %s\n", cmd.Usage)
fmt.Printf("About: %s\n", cmd.Description)
fmt.Println()
return
}
}
fmt.Println("Commands:")
names := make([]string, 0, len(commands))
for name := range commands {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
cmd := commands[name]
fmt.Printf(" %-16s %s\n", cmd.Name, cmd.Description)
}
fmt.Println()
fmt.Println("Use \"packager help <command>\" for more information about a command.")
fmt.Println()
}
func ensureProjectRoot() error {
if !fileExists("composer.json") {
return errors.New("Error: Not in a project root (no composer.json found)")
}
if !dirExists(".git") {
return errors.New("Error: Not in a git repository (no .git directory found)")
}
return nil
}
func ensureBinaries(names ...string) error {
for _, name := range names {
if _, err := exec.LookPath(name); err != nil {
return fmt.Errorf("required binary %q not found in PATH", name)
}
}
return nil
}
func ensureGitSubrepo() error {
// Quick probe: `git subrepo --version`
cmd := exec.Command("git", "subrepo", "--version")
cmd.Stdout = nil
cmd.Stderr = nil
if err := cmd.Run(); err != nil {
return errors.New("git-subrepo does not appear to be installed or available (\"git subrepo --version\" failed)")
}
return nil
}
// ensurePathRepositoryConfigured makes sure composer.json has a path repository
// pointing to "packages/*/*" with options.symlink = true.
func ensurePathRepositoryConfigured() error {
const pathURL = "packages/*/*"
data, err := os.ReadFile("composer.json")
if err != nil {
return fmt.Errorf("could not read composer.json: %w", err)
}
dec := json.NewDecoder(bytes.NewReader(data))
// We verwachten een top-level object: `{ ... }`
tok, err := dec.Token()
if err != nil {
return fmt.Errorf("could not parse composer.json: %w", err)
}
delim, ok := tok.(json.Delim)
if !ok || delim != '{' {
return fmt.Errorf("composer.json does not contain a top-level JSON object")
}
// Ordered opslag van keys en values
keys := make([]string, 0)
values := make(map[string]json.RawMessage)
for dec.More() {
tKey, err := dec.Token()
if err != nil {
return fmt.Errorf("error reading key from composer.json: %w", err)
}
key, ok := tKey.(string)
if !ok {
return fmt.Errorf("expected string key in composer.json, got %T", tKey)
}
keys = append(keys, key)
var raw json.RawMessage
if err := dec.Decode(&raw); err != nil {
return fmt.Errorf("error decoding value for key %q: %w", key, err)
}
values[key] = raw
}
// Closing `}`
if tok, err = dec.Token(); err != nil {
return fmt.Errorf("error reading closing brace of composer.json: %w", err)
} else if delim, ok := tok.(json.Delim); !ok || delim != '}' {
return fmt.Errorf("composer.json top-level object not properly closed")
}
// Repositories uitlezen/bouwen
var repos []map[string]interface{}
_, hasRepos := values["repositories"]
if hasRepos {
if err := json.Unmarshal(values["repositories"], &repos); err != nil {
// Onverwachte shape -> niet rommelen om niets stuk te maken
return nil
}
} else {
repos = []map[string]interface{}{}
}
// Path repo zoeken of toevoegen
found := false
for i, r := range repos {
t, _ := r["type"].(string)
u, _ := r["url"].(string)
if t == "path" && u == pathURL {
found = true
opts, _ := r["options"].(map[string]interface{})
if opts == nil {
opts = map[string]interface{}{}
}
if val, ok := opts["symlink"].(bool); !ok || !val {
opts["symlink"] = true
}
r["options"] = opts
repos[i] = r
break
}
}
if !found {
repos = append(repos, map[string]interface{}{
"type": "path",
"url": pathURL,
"options": map[string]interface{}{
"symlink": true,
},
})
}
// Nieuwe repositories JSON
reposJSON, err := json.Marshal(repos)
if err != nil {
return fmt.Errorf("could not encode repositories: %w", err)
}
values["repositories"] = json.RawMessage(reposJSON)
if !hasRepos {
keys = append(keys, "repositories")
}
// composer.json met bewaarde key-volgorde opnieuw opbouwen
var buf bytes.Buffer
buf.WriteString("{\n")
for i, key := range keys {
raw := values[key]
buf.WriteString(" ")
buf.WriteString(strconv.Quote(key))
buf.WriteString(": ")
// Value netjes indenten op een nieuwe regelstructuur
var indented bytes.Buffer
if err := json.Indent(&indented, raw, " ", " "); err != nil {
// fallback: raw zoals-ie is
buf.Write(raw)
} else {
s := indented.String()
// json.Indent met prefix " " geeft de eerste regel met 4 spaties;
// die halen we weg omdat we hierboven al " \"key\": " hebben geschreven.
if strings.HasPrefix(s, " ") {
s = s[4:]
}
buf.WriteString(s)
}
if i < len(keys)-1 {
buf.WriteString(",\n")
} else {
buf.WriteString("\n")
}
}
buf.WriteString("}\n")
if err := os.WriteFile("composer.json", buf.Bytes(), 0o644); err != nil {
return fmt.Errorf("could not write composer.json: %w", err)
}
fmt.Println("Updated composer.json repositories for local path packages.")
return nil
}
type rootComposerDeps struct {
Require map[string]bool
RequireDev map[string]bool
}
func loadRootComposerDeps() (rootComposerDeps, error) {
var deps rootComposerDeps
deps.Require = make(map[string]bool)
deps.RequireDev = make(map[string]bool)
data, err := os.ReadFile("composer.json")
if err != nil {
return deps, fmt.Errorf("could not read composer.json: %w", err)
}
var raw map[string]interface{}
if err := json.Unmarshal(data, &raw); err != nil {
return deps, fmt.Errorf("could not parse composer.json: %w", err)
}
if reqVal, ok := raw["require"]; ok {
if m, ok := reqVal.(map[string]interface{}); ok {
for name := range m {
deps.Require[name] = true
}
}
}
if reqDevVal, ok := raw["require-dev"]; ok {
if m, ok := reqDevVal.(map[string]interface{}); ok {
for name := range m {
deps.RequireDev[name] = true
}
}
}
return deps, nil
}
func readPackageNameFromComposer(dir string) (string, error) {
path := filepath.Join(dir, "composer.json")
data, err := os.ReadFile(path)
if err != nil {
return "", err
}
var tmp struct {
Name string `json:"name"`
}
if err := json.Unmarshal(data, &tmp); err != nil {
return "", err
}
return tmp.Name, nil
}
type doctorResult struct {
Path string
Vendor string
Repo string
PackageName string
HasGitrepo bool
HasComposer bool
InRequire bool
InRequireDev bool
}
func runDoctor() error {
deps, err := loadRootComposerDeps()
if err != nil {
return err
}
packagesRoot := "packages"
info, err := os.Stat(packagesRoot)
if os.IsNotExist(err) {
fmt.Println("No packages directory found; nothing to check.")
return nil
}
if err != nil {
return fmt.Errorf("could not stat packages directory: %w", err)
}
if !info.IsDir() {
return fmt.Errorf("%s exists but is not a directory", packagesRoot)
}
var results []doctorResult
err = filepath.Walk(packagesRoot, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
return nil
}
// Relatief pad vanaf "packages"
rel, err := filepath.Rel(packagesRoot, path)
if err != nil {
return err
}
if rel == "." {
return nil
}
// We willen alleen dirs van de vorm packages/vendor/repo -> depth 2
parts := strings.Split(filepath.ToSlash(rel), "/")
if len(parts) != 2 {
return nil
}
vendor := parts[0]
repo := parts[1]
r := doctorResult{
Path: path,
Vendor: vendor,
Repo: repo,
}
if fileExists(filepath.Join(path, ".gitrepo")) {
r.HasGitrepo = true
}
if fileExists(filepath.Join(path, "composer.json")) {
r.HasComposer = true
if name, err := readPackageNameFromComposer(path); err == nil && name != "" {
r.PackageName = name
}
}
if r.PackageName == "" {
r.PackageName = vendor + "/" + repo
}
if deps.Require[r.PackageName] {
r.InRequire = true
}
if deps.RequireDev[r.PackageName] {
r.InRequireDev = true
}
results = append(results, r)
return nil
})
if err != nil {
return fmt.Errorf("error scanning packages: %w", err)
}
fmt.Println()
fmt.Println("Packager doctor report")
fmt.Println("----------------------")
fmt.Println()
if len(results) == 0 {
fmt.Println("No packages found under packages/*/*.")
return nil
}
sort.Slice(results, func(i, j int) bool {
return results[i].PackageName < results[j].PackageName
})
var okCount, warnCount int
for _, r := range results {
status := "[OK]"
if !r.HasGitrepo || !r.HasComposer || (!r.InRequire && !r.InRequireDev) {
status = "[WARN]"
warnCount++
} else {
okCount++
}
fmt.Printf("%s %s (%s)\n", status, r.PackageName, filepath.ToSlash(r.Path))
fmt.Printf(" .gitrepo: %s\n", boolToStatus(r.HasGitrepo))
fmt.Printf(" composer.json: %s\n", boolToStatus(r.HasComposer))
depStatus := "none"
if r.InRequire && r.InRequireDev {
depStatus = "require + require-dev"
} else if r.InRequire {
depStatus = "require"
} else if r.InRequireDev {
depStatus = "require-dev"
}
fmt.Printf(" in root deps: %s\n", depStatus)
fmt.Println()
}
fmt.Printf("Summary: %d OK, %d with warnings\n", okCount, warnCount)
fmt.Println()
return nil
}
func boolToStatus(v bool) string {
if v {
return "ok"
}
return "missing"
}
// fileExists checks if a file exists and is not a directory.
func fileExists(path string) bool {
info, err := os.Stat(path)
if err != nil {
return false
}
return !info.IsDir()
}
func dirExists(path string) bool {
info, err := os.Stat(path)
if err != nil {
return false
}
return info.IsDir()
}
// parseRepoInfo extracts vendor and repo from a Git URL.
func parseRepoInfo(url string) (vendor, repo string) {
clean := url
// Strip protocol schemes
if idx := strings.Index(clean, "://"); idx != -1 {
clean = clean[idx+3:]
}
// For [email protected]:vendor/repo.git, keep part after ":"
if idx := strings.LastIndex(clean, ":"); idx != -1 {
if idx > strings.Index(clean, "github.com") {
clean = clean[idx+1:]
}
}
parts := strings.Split(clean, "/")
if len(parts) >= 2 {
vendor = parts[len(parts)-2]
repo = parts[len(parts)-1]
} else {
vendor = "vendor"
repo = clean
}
repo = strings.TrimSuffix(repo, ".git")
return vendor, repo
}
// runCommand executes an external command and streams IO.
func runCommand(name string, args ...string) error {
cmd := exec.Command(name, args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
return cmd.Run()
}
func clonePackage(url string) error {
vendor, repo := parseRepoInfo(url)
subdirectory := filepath.Join("packages", vendor, repo)
fmt.Printf("Cloning package: %s/%s\n", vendor, repo)
if err := os.MkdirAll(subdirectory, 0o755); err != nil {
return fmt.Errorf("could not create directory %s: %w", subdirectory, err)
}
if err := runCommand("git", "subrepo", "clone", url, subdirectory, "-b", "master", "--quiet"); err != nil {
return fmt.Errorf("git subrepo clone failed: %w", err)
}
// Ensure path repository exists in composer.json
if err := ensurePathRepositoryConfigured(); err != nil {
return fmt.Errorf("could not ensure path repository in composer.json: %w", err)
}
packageName := fmt.Sprintf("%s/%s:@dev", vendor, repo)
if err := runCommand("composer", "require", packageName); err != nil {
return fmt.Errorf("composer require failed: %w", err)
}
return nil
}
func pullPackage(url string) error {
vendor, repo := parseRepoInfo(url)
subdirectory := filepath.Join("packages", vendor, repo)
fmt.Printf("Pulling package: %s/%s\n", vendor, repo)
if !dirExists(subdirectory) {
return fmt.Errorf("could not find a local subrepo of %s/%s", vendor, repo)
}
if err := runCommand("git", "subrepo", "pull", subdirectory, "-b", "master", "--quiet"); err != nil {
return fmt.Errorf("git subrepo pull failed: %w", err)
}
return nil
}
func pushPackage(url string) error {
vendor, repo := parseRepoInfo(url)
subdirectory := filepath.Join("packages", vendor, repo)
fmt.Printf("Pushing package: %s/%s\n", vendor, repo)
if !dirExists(subdirectory) {
return fmt.Errorf("could not find a local subrepo of %s/%s", vendor, repo)
}
if err := runCommand("git", "subrepo", "push", subdirectory, "-b", "master", "--quiet"); err != nil {
return fmt.Errorf("git subrepo push failed: %w", err)
}
return nil
}
func syncPackage(url string) error {
if err := pullPackage(url); err != nil {
return err
}
if err := pushPackage(url); err != nil {
return err
}
return nil
}
func listPackages() error {
root := "packages"
fmt.Println()
fmt.Println("Cloned packages:")
fmt.Println()
var entries []string
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
if info.Name() == ".gitrepo" {
rel, relErr := filepath.Rel(root, filepath.Dir(path))
if relErr != nil {
return relErr
}
entries = append(entries, filepath.ToSlash(rel))
}
return nil
})
if os.IsNotExist(err) {
fmt.Println("No packages directory found.")
return nil
}
if err != nil {
return err
}
sort.Strings(entries)
if len(entries) == 0 {
fmt.Println("No cloned packages found.")
return nil
}
for _, e := range entries {
fmt.Println(e)
}
return nil
}
func runPullAll() error {
return iteratePackages("pull", func(path string, vendor string, repo string) error {
fmt.Printf("📥 Pulling %s/%s...\n", vendor, repo)
return runCommand("git", "subrepo", "pull", path, "-b", "master", "--quiet")
})
}
func runPushAll() error {
return iteratePackages("push", func(path string, vendor string, repo string) error {
fmt.Printf("📤 Pushing %s/%s...\n", vendor, repo)
return runCommand("git", "subrepo", "push", path, "-b", "master", "--quiet")
})
}
func iteratePackages(action string, fn func(path string, vendor string, repo string) error) error {
packagesRoot := "packages"
found := 0
skipped := 0
failed := 0
err := filepath.Walk(packagesRoot, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
return nil
}
rel, err := filepath.Rel(packagesRoot, path)
if err != nil {
return err
}
parts := strings.Split(filepath.ToSlash(rel), "/")
if len(parts) != 2 {
return nil
}
vendor := parts[0]
repo := parts[1]
gitrepo := filepath.Join(path, ".gitrepo")
if !fileExists(gitrepo) {
skipped++
return nil
}
found++
if err := fn(path, vendor, repo); err != nil {
fmt.Fprintf(os.Stderr, "❌ Error in %s/%s: %v\n", vendor, repo, err)
failed++
}
return nil
})
if err != nil {
return fmt.Errorf("error walking packages: %w", err)
}
fmt.Printf("\nDone. %s attempted on %d package(s), %d skipped, %d failed.\n", strings.Title(action), found, skipped, failed)
return nil
}