|
| 1 | +package commands |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "github.com/bmatcuk/doublestar" |
| 7 | + "github.com/jessevdk/go-flags" |
| 8 | + devspacecontext "github.com/loft-sh/devspace/pkg/devspace/context" |
| 9 | + "github.com/loft-sh/devspace/pkg/devspace/pipeline/engine" |
| 10 | + "github.com/loft-sh/devspace/pkg/devspace/pipeline/types" |
| 11 | + "github.com/loft-sh/devspace/pkg/util/log" |
| 12 | + "github.com/loft-sh/devspace/pkg/util/tomb" |
| 13 | + "github.com/loft-sh/notify" |
| 14 | + "github.com/pkg/errors" |
| 15 | + "mvdan.cc/sh/v3/interp" |
| 16 | + "os" |
| 17 | + "path/filepath" |
| 18 | + "strings" |
| 19 | + "time" |
| 20 | +) |
| 21 | + |
| 22 | +type WatchOptions struct { |
| 23 | + FailOnError bool `long:"fail-on-error" description:"If true the command will fail on an error while running the sub command"` |
| 24 | + |
| 25 | + Paths []string `long:"path" short:"p" description:"The paths to watch. Can be patterns in the form of ./**/my-file.txt"` |
| 26 | +} |
| 27 | + |
| 28 | +func Watch(devCtx *devspacecontext.Context, pipeline types.Pipeline, args []string, newHandler NewHandlerFn) error { |
| 29 | + devCtx.Log.Debugf("watch %s", strings.Join(args, " ")) |
| 30 | + options := &WatchOptions{} |
| 31 | + args, err := flags.ParseArgs(options, args) |
| 32 | + if err != nil { |
| 33 | + return errors.Wrap(err, "parse args") |
| 34 | + } |
| 35 | + if len(options.Paths) == 0 { |
| 36 | + return fmt.Errorf("usage: watch --path MY_PATH -- my_command") |
| 37 | + } |
| 38 | + if len(args) == 0 { |
| 39 | + return fmt.Errorf("usage: watch --path MY_PATH -- my_command") |
| 40 | + } |
| 41 | + |
| 42 | + w := &watcher{} |
| 43 | + hc := interp.HandlerCtx(devCtx.Context) |
| 44 | + return w.Watch(devCtx.Context, options.Paths, options.FailOnError, func(ctx context.Context) error { |
| 45 | + devCtx := devCtx.WithContext(ctx) |
| 46 | + _, err := engine.ExecutePipelineShellCommand(ctx, args[0]+" $@", args[1:], hc.Dir, false, hc.Stdout, hc.Stderr, hc.Stdin, hc.Env, newHandler(devCtx, hc.Stdout, pipeline)) |
| 47 | + return err |
| 48 | + }, devCtx.Log) |
| 49 | +} |
| 50 | + |
| 51 | +type watcher struct{} |
| 52 | + |
| 53 | +func (w *watcher) Watch(ctx context.Context, patterns []string, failOnError bool, action func(ctx context.Context) error, log log.Logger) error { |
| 54 | + // prepare patterns |
| 55 | + for i, p := range patterns { |
| 56 | + patterns[i] = strings.TrimSuffix(strings.TrimPrefix(strings.TrimSpace(p), "./"), "/") |
| 57 | + } |
| 58 | + |
| 59 | + // get folders from patterns |
| 60 | + pathsToWatch := map[string]bool{} |
| 61 | + for _, p := range patterns { |
| 62 | + patternsSplitted := strings.Split(filepath.ToSlash(p), "/") |
| 63 | + lastIndex := len(patternsSplitted) - 1 |
| 64 | + for i, s := range patternsSplitted { |
| 65 | + if strings.Contains(s, "*") { |
| 66 | + lastIndex = i |
| 67 | + break |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + targetPath := strings.Join(patternsSplitted[:lastIndex], "/") |
| 72 | + if targetPath == "" { |
| 73 | + targetPath = "." |
| 74 | + } |
| 75 | + |
| 76 | + absolutePath, err := filepath.Abs(filepath.FromSlash(targetPath)) |
| 77 | + if err != nil { |
| 78 | + return errors.Wrap(err, "error resolving "+targetPath) |
| 79 | + } |
| 80 | + |
| 81 | + absolutePath, err = filepath.EvalSymlinks(absolutePath) |
| 82 | + if err != nil { |
| 83 | + return errors.Wrap(err, "eval symlinks") |
| 84 | + } |
| 85 | + |
| 86 | + pathsToWatch[absolutePath] = true |
| 87 | + } |
| 88 | + |
| 89 | + watchTree := notify.NewTree() |
| 90 | + defer watchTree.Close() |
| 91 | + |
| 92 | + globalChannel := make(chan string, 100) |
| 93 | + for targetPath := range pathsToWatch { |
| 94 | + stat, err := os.Stat(targetPath) |
| 95 | + if err != nil { |
| 96 | + if os.IsNotExist(err) { |
| 97 | + return fmt.Errorf("cannot watch %s as the directory or file must exist", targetPath) |
| 98 | + } |
| 99 | + |
| 100 | + return errors.Wrap(err, "stat watch path "+targetPath) |
| 101 | + } |
| 102 | + |
| 103 | + // watch recursive if target path is a directory |
| 104 | + watchPath := targetPath |
| 105 | + if stat.IsDir() { |
| 106 | + watchPath = filepath.Join(watchPath, "...") |
| 107 | + } |
| 108 | + |
| 109 | + // start watching |
| 110 | + eventChannel := make(chan notify.EventInfo, 100) |
| 111 | + log.Debugf("Start watching %v", targetPath) |
| 112 | + err = watchTree.Watch(watchPath, eventChannel, func(s string) bool { |
| 113 | + return false |
| 114 | + }, notify.All) |
| 115 | + if err != nil { |
| 116 | + return errors.Wrap(err, "start watching "+targetPath) |
| 117 | + } |
| 118 | + defer watchTree.Stop(eventChannel) |
| 119 | + |
| 120 | + go func(base string, eventChannel chan notify.EventInfo) { |
| 121 | + for { |
| 122 | + select { |
| 123 | + case <-ctx.Done(): |
| 124 | + return |
| 125 | + case e := <-eventChannel: |
| 126 | + // make relative |
| 127 | + relPath, err := filepath.Rel(base, e.Path()) |
| 128 | + if err != nil { |
| 129 | + log.Debugf("error converting path %s: %v", e.Path(), err) |
| 130 | + } else { |
| 131 | + globalChannel <- filepath.ToSlash(relPath) |
| 132 | + } |
| 133 | + } |
| 134 | + } |
| 135 | + }(targetPath, eventChannel) |
| 136 | + } |
| 137 | + |
| 138 | + // start command |
| 139 | + return w.handleCommand(ctx, patterns, failOnError, action, globalChannel, log) |
| 140 | +} |
| 141 | + |
| 142 | +func (w *watcher) handleCommand(ctx context.Context, patterns []string, failOnError bool, action func(ctx context.Context) error, events chan string, log log.Logger) error { |
| 143 | + t := w.startCommand(ctx, action) |
| 144 | + numEvents := 0 |
| 145 | + for { |
| 146 | + select { |
| 147 | + case <-ctx.Done(): |
| 148 | + t.Kill(nil) |
| 149 | + <-t.Dead() |
| 150 | + return nil |
| 151 | + case e := <-events: |
| 152 | + // check if match |
| 153 | + for _, p := range patterns { |
| 154 | + hasMatched, _ := doublestar.Match(p, e) |
| 155 | + if hasMatched { |
| 156 | + numEvents++ |
| 157 | + break |
| 158 | + } |
| 159 | + } |
| 160 | + case <-time.After(time.Second * 2): |
| 161 | + if numEvents > 0 { |
| 162 | + // kill application and wait for exit |
| 163 | + log.Infof("Restarting command...") |
| 164 | + t.Kill(nil) |
| 165 | + select { |
| 166 | + case <-ctx.Done(): |
| 167 | + return nil |
| 168 | + case <-t.Dead(): |
| 169 | + } |
| 170 | + |
| 171 | + // restart the command |
| 172 | + t = w.startCommand(ctx, action) |
| 173 | + numEvents = 0 |
| 174 | + } |
| 175 | + } |
| 176 | + |
| 177 | + // check if terminated |
| 178 | + if failOnError && t.Terminated() && t.Err() != nil { |
| 179 | + return t.Err() |
| 180 | + } |
| 181 | + } |
| 182 | +} |
| 183 | + |
| 184 | +func (w *watcher) startCommand(ctx context.Context, action func(ctx context.Context) error) *tomb.Tomb { |
| 185 | + t, tombCtx := tomb.WithContext(ctx) |
| 186 | + t.Go(func() error { |
| 187 | + return action(tombCtx) |
| 188 | + }) |
| 189 | + return t |
| 190 | +} |
0 commit comments