| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "log" |
| 6 | "os" |
| 7 | "os/signal" |
| 8 | "strings" |
| 9 | "sync" |
| 10 | "syscall" |
| 11 | "time" |
| 12 | |
| 13 | "github.com/fsnotify/fsnotify" |
| 14 | flag "github.com/ogier/pflag" |
| 15 | ) |
| 16 | |
| 17 | const defaultSubSymbol = "{}" |
| 18 | |
| 19 | var ( |
| 20 | reflexes []*Reflex |
| 21 | |
| 22 | flagConf string |
| 23 | flagSequential bool |
| 24 | flagDecoration string |
| 25 | decoration Decoration |
| 26 | verbose bool |
| 27 | globalFlags = flag.NewFlagSet("", flag.ContinueOnError) |
| 28 | globalConfig = &Config{} |
| 29 | |
| 30 | reflexID = 0 |
| 31 | stdout = make(chan OutMsg, 1) |
| 32 | |
| 33 | cleanupMu = &sync.Mutex{} |
| 34 | ) |
| 35 | |
| 36 | func usage() { |
| 37 | fmt.Fprintf(os.Stderr, `Usage: %s [OPTIONS] [COMMAND] |
| 38 | |
| 39 | COMMAND is any command you'd like to run. Any instance of {} will be replaced |
| 40 | with the filename of the changed file. (The symbol may be changed with the |
| 41 | --substitute flag.) |
| 42 | |
| 43 | OPTIONS are given below: |
| 44 | `, os.Args[0]) |
| 45 | |
| 46 | globalFlags.PrintDefaults() |
| 47 | |
| 48 | fmt.Fprint(os.Stderr, ` |
| 49 | Examples: |
| 50 | |
| 51 | # Print each .txt file if it changes |
| 52 | $ reflex -r '\.txt$' echo {} |
| 53 | |
| 54 | # Run 'make' if any of the .c files in this directory change: |
| 55 | $ reflex -g '*.c' make |
| 56 | |
| 57 | # Build and run a server; rebuild and restart when .java files change: |
| 58 | $ reflex -r '\.java$' -s -- sh -c 'make && java bin/Server' |
| 59 | |
| 60 | `) |
| 61 | } |
| 62 | |
| 63 | func init() { |
| 64 | globalFlags.Usage = usage |
| 65 | globalFlags.StringVarP(&flagConf, "config", "c", "", ` |
| 66 | A configuration file that describes how to run reflex |
| 67 | (or '-' to read the configuration from stdin).`) |
| 68 | globalFlags.BoolVarP(&verbose, "verbose", "v", false, ` |
| 69 | Verbose mode: print out more information about what reflex is doing.`) |
| 70 | globalFlags.BoolVarP(&flagSequential, "sequential", "e", false, ` |
| 71 | Don't run multiple commands at the same time.`) |
| 72 | globalFlags.StringVarP(&flagDecoration, "decoration", "d", "plain", ` |
| 73 | How to decorate command output. Choices: none, plain, fancy.`) |
| 74 | globalConfig.registerFlags(globalFlags) |
| 75 | } |
| 76 | |
| 77 | func anyNonGlobalsRegistered() bool { |
| 78 | any := false |
| 79 | walkFn := func(f *flag.Flag) { |
| 80 | switch f.Name { |
| 81 | case "config", "verbose", "sequential", "decoration": |
| 82 | default: |
| 83 | any = true |
| 84 | } |
| 85 | } |
| 86 | globalFlags.Visit(walkFn) |
| 87 | return any |
| 88 | } |
| 89 | |
| 90 | func printGlobals() { |
| 91 | fmt.Println("Globals set at commandline") |
| 92 | walkFn := func(f *flag.Flag) { |
| 93 | fmt.Printf("| --%s (-%s) '%s' (default: '%s')\n", |
| 94 | f.Name, f.Shorthand, f.Value, f.DefValue) |
| 95 | } |
| 96 | globalFlags.Visit(walkFn) |
| 97 | fmt.Println("+---------") |
| 98 | } |
| 99 | |
| 100 | func cleanup(reason string) { |
| 101 | cleanupMu.Lock() |
| 102 | fmt.Println(reason) |
| 103 | wg := &sync.WaitGroup{} |
| 104 | for _, reflex := range reflexes { |
| 105 | if reflex.Running() { |
| 106 | wg.Add(1) |
| 107 | go func(reflex *Reflex) { |
| 108 | reflex.terminate() |
| 109 | wg.Done() |
| 110 | }(reflex) |
| 111 | } |
| 112 | } |
| 113 | wg.Wait() |
| 114 | // Give just a little time to finish printing output. |
| 115 | time.Sleep(10 * time.Millisecond) |
| 116 | os.Exit(0) |
| 117 | } |
| 118 | |
| 119 | func main() { |
| 120 | log.SetFlags(0) |
| 121 | if err := globalFlags.Parse(os.Args[1:]); err != nil { |
| 122 | log.Fatal(err) |
| 123 | } |
| 124 | globalConfig.command = globalFlags.Args() |
| 125 | globalConfig.source = "[commandline]" |
| 126 | if verbose { |
| 127 | printGlobals() |
| 128 | } |
| 129 | switch strings.ToLower(flagDecoration) { |
| 130 | case "none": |
| 131 | decoration = DecorationNone |
| 132 | case "plain": |
| 133 | decoration = DecorationPlain |
| 134 | case "fancy": |
| 135 | decoration = DecorationFancy |
| 136 | default: |
| 137 | log.Fatalf("Invalid decoration %s. Choices: none, plain, fancy.", flagDecoration) |
| 138 | } |
| 139 | |
| 140 | var configs []*Config |
| 141 | if flagConf == "" { |
| 142 | if flagSequential { |
| 143 | log.Fatal("Cannot set --sequential without --config (because you cannot specify multiple commands).") |
| 144 | } |
| 145 | configs = []*Config{globalConfig} |
| 146 | } else { |
| 147 | if anyNonGlobalsRegistered() { |
| 148 | log.Fatal("Cannot set other flags along with --config other than --sequential, --verbose, and --decoration.") |
| 149 | } |
| 150 | var err error |
| 151 | configs, err = ReadConfigs(flagConf) |
| 152 | if err != nil { |
| 153 | log.Fatalln("Could not parse configs:", err) |
| 154 | } |
| 155 | if len(configs) == 0 { |
| 156 | log.Fatal("No configurations found") |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | for _, config := range configs { |
| 161 | reflex, err := NewReflex(config) |
| 162 | if err != nil { |
| 163 | log.Fatalln("Could not make reflex for config:", err) |
| 164 | } |
| 165 | if verbose { |
| 166 | fmt.Println(reflex) |
| 167 | } |
| 168 | reflexes = append(reflexes, reflex) |
| 169 | } |
| 170 | |
| 171 | // Catch ctrl-c and make sure to kill off children. |
| 172 | signals := make(chan os.Signal, 1) |
| 173 | signal.Notify(signals, os.Interrupt) |
| 174 | signal.Notify(signals, os.Signal(syscall.SIGTERM)) |
| 175 | go func() { |
| 176 | s := <-signals |
| 177 | reason := fmt.Sprintf("Interrupted (%s). Cleaning up children...", s) |
| 178 | cleanup(reason) |
| 179 | }() |
| 180 | defer cleanup("Cleaning up.") |
| 181 | |
| 182 | watcher, err := fsnotify.NewWatcher() |
| 183 | if err != nil { |
| 184 | log.Fatal(err) |
| 185 | } |
| 186 | defer watcher.Close() |
| 187 | |
| 188 | changes := make(chan string) |
| 189 | broadcastChanges := make([]chan string, len(reflexes)) |
| 190 | done := make(chan error) |
| 191 | for i := range reflexes { |
| 192 | broadcastChanges[i] = make(chan string) |
| 193 | } |
| 194 | go watch(".", watcher, changes, done, reflexes) |
| 195 | go broadcast(broadcastChanges, changes) |
| 196 | go printOutput(stdout, os.Stdout) |
| 197 | |
| 198 | for i, reflex := range reflexes { |
| 199 | reflex.Start(broadcastChanges[i]) |
| 200 | } |
| 201 | |
| 202 | log.Fatal(<-done) |
| 203 | } |
| 204 | |
| 205 | func broadcast(outs []chan string, in <-chan string) { |
| 206 | for e := range in { |
| 207 | for _, out := range outs { |
| 208 | out <- e |
| 209 | } |
| 210 | } |
| 211 | } |