-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
596 lines (522 loc) · 14.6 KB
/
main.go
File metadata and controls
596 lines (522 loc) · 14.6 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
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
"os/signal"
"path/filepath"
"strings"
"sync"
"syscall"
analyzer "github.com/nicolasgere/knit/lib/analyser"
"github.com/nicolasgere/knit/lib/git"
"github.com/nicolasgere/knit/lib/runner"
"github.com/nicolasgere/knit/lib/utils"
"github.com/urfave/cli/v2"
)
var defaultDir = "."
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
setupSignalHandling(cancel)
r := runner.NewRunner(ctx, 3)
app := createCliApp(&r)
if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
}
func setupSignalHandling(cancel context.CancelFunc) {
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sigChan
cancel()
}()
}
func createCliApp(r *runner.Runner) *cli.App {
return &cli.App{
Commands: []*cli.Command{
createCommand("fmt", "Format every modules", "go fmt ./...", r),
createCommand("test", "Test every modules", "go test ./...", r),
createAffectedCommand(),
createGraphCommand(),
},
}
}
// OutputFormat defines the format for the affected command output
type OutputFormat string
const (
FormatList OutputFormat = "list"
FormatGoArgs OutputFormat = "go-args"
FormatGitHubMatrix OutputFormat = "github-matrix"
)
// createAffectedCommand creates the 'affected' command
func createAffectedCommand() *cli.Command {
var (
path string
base string
useMergeBase bool
format string
includeDeps bool
)
return &cli.Command{
Name: "affected",
Usage: "List modules affected by changes since a git reference",
Description: `Detect which modules have changed compared to a git reference.
Examples:
knit affected # Compare against 'main' branch
knit affected --base origin/main # Compare against origin/main
knit affected --merge-base # Use merge-base (recommended for CI)
knit affected -f go-args # Output: -p module1 -p module2
knit affected -f github-matrix # Output: JSON matrix for GitHub Actions
knit affected --include-deps # Include dependencies of affected modules`,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "path",
Usage: "Path to the workspace root",
Aliases: []string{"p"},
Value: ".",
Destination: &path,
},
&cli.StringFlag{
Name: "base",
Usage: "Git reference to compare against (branch, tag, or commit)",
Aliases: []string{"b"},
Value: "main",
Destination: &base,
},
&cli.BoolFlag{
Name: "merge-base",
Usage: "Compare against merge-base (common ancestor) - recommended for CI/PRs",
Aliases: []string{"m"},
Destination: &useMergeBase,
},
&cli.StringFlag{
Name: "format",
Usage: "Output format: list (default), go-args, github-matrix",
Aliases: []string{"f"},
Value: "list",
Destination: &format,
},
&cli.BoolFlag{
Name: "include-deps",
Usage: "Include dependencies of affected modules",
Aliases: []string{"d"},
Destination: &includeDeps,
},
},
Action: func(c *cli.Context) error {
return runAffected(path, base, useMergeBase, OutputFormat(format), includeDeps)
},
}
}
func runAffected(path, base string, useMergeBase bool, format OutputFormat, includeDeps bool) error {
// Get absolute path to workspace
absPath, err := filepath.Abs(path)
if err != nil {
return fmt.Errorf("failed to get absolute path: %w", err)
}
// List all modules in the workspace
modules, err := analyzer.ListModule(absPath)
if err != nil {
return fmt.Errorf("failed to list modules: %w", err)
}
if len(modules) == 0 {
return fmt.Errorf("no modules found in workspace")
}
// Get changed files
changedFiles, err := git.GetChangedFiles(base, useMergeBase, absPath)
if err != nil {
return fmt.Errorf("failed to get changed files: %w", err)
}
// Get module directories
moduleDirs := make([]string, len(modules))
moduleDirToPath := make(map[string]string)
for i, m := range modules {
moduleDirs[i] = m.Dir
moduleDirToPath[m.Dir] = m.Path
}
// Find affected module directories
affectedDirs := git.FindAffectedModuleDirs(changedFiles, moduleDirs, absPath)
// Convert to module paths
affectedPaths := make([]string, 0, len(affectedDirs))
for _, dir := range affectedDirs {
if path, ok := moduleDirToPath[dir]; ok {
affectedPaths = append(affectedPaths, path)
}
}
// Include dependencies if requested
if includeDeps && len(affectedPaths) > 0 {
graph, err := analyzer.BuildDependencyGraph(modules)
if err != nil {
return fmt.Errorf("failed to build dependency graph: %w", err)
}
allAffected := make(map[string]bool)
for _, p := range affectedPaths {
allAffected[p] = true
}
// For each affected module, find its dependencies
for _, p := range affectedPaths {
deps, err := analyzer.GetDependencyPaths(graph, p)
if err != nil {
// Module might not have dependencies, continue
continue
}
for _, dep := range deps {
allAffected[dep] = true
}
}
// Convert back to slice
affectedPaths = make([]string, 0, len(allAffected))
for p := range allAffected {
affectedPaths = append(affectedPaths, p)
}
}
// Output in the requested format
return outputAffected(affectedPaths, format)
}
func outputAffected(modules []string, format OutputFormat) error {
switch format {
case FormatList:
for _, m := range modules {
fmt.Println(m)
}
case FormatGoArgs:
// Output: -p module1 -p module2 ...
var args []string
for _, m := range modules {
args = append(args, "-p", m)
}
fmt.Println(strings.Join(args, " "))
case FormatGitHubMatrix:
// Output: JSON for GitHub Actions matrix
type MatrixOutput struct {
Module []string `json:"module"`
}
matrix := MatrixOutput{Module: modules}
if len(modules) == 0 {
matrix.Module = []string{} // Ensure empty array, not null
}
data, err := json.Marshal(matrix)
if err != nil {
return fmt.Errorf("failed to marshal JSON: %w", err)
}
fmt.Println(string(data))
default:
return fmt.Errorf("unknown format: %s (use list, go-args, or github-matrix)", format)
}
return nil
}
// createGraphCommand creates the 'graph' command to visualize module dependencies
func createGraphCommand() *cli.Command {
var (
path string
format string
)
return &cli.Command{
Name: "graph",
Usage: "Display the dependency graph of all modules in the workspace",
Description: `Show all modules and their dependencies within the monorepo.
Examples:
knit graph # Show dependency graph
knit graph -f dot # Output in DOT format (for Graphviz)
knit graph -f json # Output in JSON format`,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "path",
Usage: "Path to the workspace root",
Aliases: []string{"p"},
Value: ".",
Destination: &path,
},
&cli.StringFlag{
Name: "format",
Usage: "Output format: tree (default), dot, json",
Aliases: []string{"f"},
Value: "tree",
Destination: &format,
},
},
Action: func(c *cli.Context) error {
return runGraph(path, format)
},
}
}
func runGraph(path, format string) error {
// Get absolute path to workspace
absPath, err := filepath.Abs(path)
if err != nil {
return fmt.Errorf("failed to get absolute path: %w", err)
}
// List all modules in the workspace
modules, err := analyzer.ListModule(absPath)
if err != nil {
return fmt.Errorf("failed to list modules: %w", err)
}
if len(modules) == 0 {
return fmt.Errorf("no modules found in workspace")
}
// Build dependency graph
g, err := analyzer.BuildDependencyGraph(modules)
if err != nil {
return fmt.Errorf("failed to build dependency graph: %w", err)
}
// Get adjacency map
adjMap, err := (*g).AdjacencyMap()
if err != nil {
return fmt.Errorf("failed to get adjacency map: %w", err)
}
// Output in requested format
switch format {
case "tree":
return outputGraphTree(modules, adjMap)
case "dot":
return outputGraphDot(modules, adjMap)
case "json":
return outputGraphJSON(modules, adjMap)
default:
return fmt.Errorf("unknown format: %s (use tree, dot, or json)", format)
}
}
func outputGraphTree[T any](modules []analyzer.Module, adjMap map[string]map[string]T) error {
fmt.Println("Module Dependency Graph")
fmt.Println("=======================")
fmt.Println()
for _, m := range modules {
deps := adjMap[m.Path]
if len(deps) == 0 {
fmt.Printf("📦 %s\n", m.Path)
fmt.Println(" (no workspace dependencies)")
} else {
fmt.Printf("📦 %s\n", m.Path)
depList := make([]string, 0, len(deps))
for dep := range deps {
depList = append(depList, dep)
}
for i, dep := range depList {
if i == len(depList)-1 {
fmt.Printf(" └── %s\n", dep)
} else {
fmt.Printf(" ├── %s\n", dep)
}
}
}
fmt.Println()
}
return nil
}
func outputGraphDot[T any](modules []analyzer.Module, adjMap map[string]map[string]T) error {
fmt.Println("digraph dependencies {")
fmt.Println(" rankdir=TB;")
fmt.Println(" node [shape=box, style=rounded];")
fmt.Println()
// Add all nodes
for _, m := range modules {
// Use short name for display
shortName := m.Path
if idx := strings.LastIndex(m.Path, "/"); idx != -1 {
shortName = m.Path[idx+1:]
}
fmt.Printf(" \"%s\" [label=\"%s\"];\n", m.Path, shortName)
}
fmt.Println()
// Add edges
for _, m := range modules {
deps := adjMap[m.Path]
for dep := range deps {
fmt.Printf(" \"%s\" -> \"%s\";\n", m.Path, dep)
}
}
fmt.Println("}")
return nil
}
func outputGraphJSON[T any](modules []analyzer.Module, adjMap map[string]map[string]T) error {
type ModuleNode struct {
Path string `json:"path"`
Dir string `json:"dir"`
Dependencies []string `json:"dependencies"`
}
type GraphOutput struct {
Modules []ModuleNode `json:"modules"`
}
output := GraphOutput{
Modules: make([]ModuleNode, 0, len(modules)),
}
for _, m := range modules {
deps := adjMap[m.Path]
depList := make([]string, 0, len(deps))
for dep := range deps {
depList = append(depList, dep)
}
output.Modules = append(output.Modules, ModuleNode{
Path: m.Path,
Dir: m.Dir,
Dependencies: depList,
})
}
data, err := json.MarshalIndent(output, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal JSON: %w", err)
}
fmt.Println(string(data))
return nil
}
func createCommand(name, usage, cmd string, r *runner.Runner) *cli.Command {
var target string
var useColor bool
var affected bool
var base string
return &cli.Command{
Name: name,
Usage: usage,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "Path",
Usage: "Path to the root directory of the project",
Aliases: []string{"p"},
Destination: &defaultDir,
},
&cli.StringFlag{
Name: "target",
Usage: "Targeted module",
Aliases: []string{"t"},
Destination: &target,
},
&cli.BoolFlag{
Name: "affected",
Usage: "Run only on affected modules (since merge-base)",
Aliases: []string{"a"},
Destination: &affected,
Value: false,
},
&cli.StringFlag{
Name: "base",
Usage: "Git reference to compare against when using --affected (default: main)",
Aliases: []string{"b"},
Value: "main",
Destination: &base,
},
&cli.BoolFlag{
Name: "color",
Usage: "Enable colored output for better readability",
Aliases: []string{"c"},
Destination: &useColor,
Value: false,
},
},
Action: func(*cli.Context) error {
// Enable color output if requested
utils.SetColorEnabled(useColor)
// Get absolute path to workspace
absPath, err := filepath.Abs(defaultDir)
if err != nil {
return fmt.Errorf("failed to get absolute path: %w", err)
}
modules, err := analyzer.ListModule(absPath)
if err != nil {
return err
}
modulesToRun := modules
// Filter by affected modules if requested
if affected {
changedFiles, err := git.GetChangedFiles(base, true, absPath)
if err != nil {
return fmt.Errorf("failed to get changed files: %w", err)
}
// Get module directories
moduleDirs := make([]string, len(modules))
moduleDirToPath := make(map[string]string)
for i, m := range modules {
moduleDirs[i] = m.Dir
moduleDirToPath[m.Dir] = m.Path
}
// Find affected module directories
affectedDirs := git.FindAffectedModuleDirs(changedFiles, moduleDirs, absPath)
// Convert to module list
affectedModules := make([]analyzer.Module, 0)
affectedPaths := make(map[string]bool)
for _, dir := range affectedDirs {
if path, ok := moduleDirToPath[dir]; ok {
affectedPaths[path] = true
}
}
for _, m := range modules {
if affectedPaths[m.Path] {
affectedModules = append(affectedModules, m)
}
}
modulesToRun = affectedModules
if len(modulesToRun) == 0 {
fmt.Println("No affected modules found")
return nil
}
}
// Filter by target if specified
if target != "" {
filteredModule := make([]analyzer.Module, 0)
for _, m := range modulesToRun {
if m.Path == target {
filteredModule = append(filteredModule, m)
}
}
modulesToRun = filteredModule
}
runOnModules(defaultDir, cmd, r, modulesToRun)
return nil
},
}
}
func runOnModules(dir, cmd string, r *runner.Runner, modules []analyzer.Module) {
tasks := createTasks(modules, cmd)
tfs := r.RunTasks(tasks)
var wg sync.WaitGroup
wg.Add(len(tfs))
for _, tf := range tfs {
go handleTaskFuture(tf, &wg)
}
wg.Wait()
return
}
func createTasks(modules []analyzer.Module, cmd string) []runner.Task {
tasks := make([]runner.Task, len(modules))
for i, module := range modules {
tasks[i] = runner.Task{
Id: module.Path,
Cmd: cmd,
Root: module.Dir,
}
}
return tasks
}
func handleTaskFuture(tf *runner.TaskFuture, wg *sync.WaitGroup) {
defer wg.Done()
for {
select {
case stdout, ok := <-tf.Stdout:
handleOutput(tf.Id, stdout, ok, &tf.Stdout)
case stderr, ok := <-tf.Stderr:
handleOutput(tf.Id, stderr, ok, &tf.Stderr)
case result := <-tf.Done:
isSuccess := result.Status == 0
statusMsg := fmt.Sprintf("Done with status %d", result.Status)
if isSuccess {
statusMsg = "✓ Done"
} else {
statusMsg = fmt.Sprintf("✗ Failed (exit %d)", result.Status)
}
utils.LogStatus(tf.Id, statusMsg, isSuccess)
return
}
}
}
func handleOutput(id string, output []byte, ok bool, channel *chan []byte) {
if !ok {
*channel = nil
return
}
if len(output) > 0 {
utils.LogWithTaskId(id, string(output), utils.INFO)
}
}