dev.go

285 lines
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
package commands

import (
	"cmp"
	"flag"
	"fmt"
	"log"
	"net"
	"os"
	"os/exec"
	"os/signal"
	"path/filepath"
	"strings"
	"sync"
	"syscall"
	"time"

	"github.com/fsnotify/fsnotify"
)

const devUsage = `Start a development server with hot reload

Usage:
  congo dev [flags]

Flags:
  --port <port>      Override server port (default: 5000)
  --no-watch         Disable file watching (just run once)

The server runs with ENV=development. Go and template files are watched
for changes — the server rebuilds and restarts automatically.
Press Ctrl+C to stop.
`

func Dev() {
	fs := flag.NewFlagSet("dev", flag.ExitOnError)
	fs.Usage = func() { fmt.Print(devUsage) }

	port := fs.String("port", "", "Override server port")
	noWatch := fs.Bool("no-watch", false, "Disable file watching")

	fs.Parse(os.Args[2:])

	dir := findAppDir()

	env := append(os.Environ(), "ENV=development")
	if *port != "" {
		env = append(env, "PORT="+*port)
	}

	listenPort := cmp.Or(*port, os.Getenv("PORT"), "5000")

	// Check for port conflicts before starting.
	if conn, err := net.Dial("tcp", "localhost:"+listenPort); err == nil {
		conn.Close()
		log.Fatalf("Port %s is already in use. Try:\n  congo dev --port <other-port>", listenPort)
	}

	if *noWatch {
		fmt.Printf("Starting development server from ./%s\n", dir)
		fmt.Printf("  http://localhost:%s\n\n", listenPort)
		cmd := exec.Command("go", "run", "./"+dir)
		cmd.Env = env
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
		cmd.Stdin = os.Stdin
		if err := cmd.Run(); err != nil {
			if exitErr, ok := err.(*exec.ExitError); ok && exitErr.ExitCode() == 2 {
				fmt.Fprintf(os.Stderr, "\nBuild failed. Check the errors above.\n")
			}
			os.Exit(1)
		}
		return
	}

	d := &devServer{
		dir:  dir,
		env:  env,
		port: listenPort,
	}
	d.run()
}

// devServer manages the build-watch-restart loop.
type devServer struct {
	dir  string
	env  []string
	port string

	mu  sync.Mutex
	cmd *exec.Cmd
}

func (d *devServer) run() {
	fmt.Printf("Starting development server from ./%s\n", d.dir)
	fmt.Printf("  http://localhost:%s\n\n", d.port)

	// Initial build + start
	d.buildAndStart()

	// Set up file watcher
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatalf("Could not start file watcher: %v", err)
	}
	defer watcher.Close()

	d.watchDirs(watcher)

	// Handle Ctrl+C
	sigCh := make(chan os.Signal, 1)
	signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM)

	// Debounce timer for file changes
	var timer *time.Timer
	debounce := 500 * time.Millisecond

	for {
		select {
		case event, ok := <-watcher.Events:
			if !ok {
				return
			}
			if !isRelevantChange(event) {
				continue
			}

			// Watch newly created directories
			if event.Has(fsnotify.Create) {
				if info, err := os.Stat(event.Name); err == nil && info.IsDir() {
					d.addWatchDir(watcher, event.Name)
				}
			}

			if timer != nil {
				timer.Stop()
			}
			timer = time.AfterFunc(debounce, func() {
				fmt.Printf("\n[dev] Change detected: %s\n", event.Name)
				d.buildAndStart()
			})

		case err, ok := <-watcher.Errors:
			if !ok {
				return
			}
			log.Printf("[dev] Watcher error: %v", err)

		case <-sigCh:
			fmt.Println("\nShutting down...")
			d.stop()
			return
		}
	}
}

// buildAndStart compiles the app and starts the new process.
// If the build fails, the old process keeps running.
func (d *devServer) buildAndStart() {
	d.mu.Lock()
	defer d.mu.Unlock()

	binPath := filepath.Join(os.TempDir(), "congo-dev-"+filepath.Base(d.dir))

	// Build
	build := exec.Command("go", "build", "-o", binPath, "./"+d.dir)
	build.Env = d.env
	build.Stdout = os.Stdout
	build.Stderr = os.Stderr
	if err := build.Run(); err != nil {
		fmt.Fprintf(os.Stderr, "\n[dev] Build failed. Fix the errors above — will retry on next change.\n\n")
		return
	}

	// Stop old process
	d.stopProcess()

	// Start new process
	cmd := exec.Command(binPath)
	cmd.Env = d.env
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	cmd.SysProcAttr = processGroupAttr()

	if err := cmd.Start(); err != nil {
		log.Printf("[dev] Failed to start: %v", err)
		return
	}

	d.cmd = cmd
	fmt.Printf("[dev] Server running (pid %d)\n\n", cmd.Process.Pid)

	// Wait in background to reap the process
	go cmd.Wait()
}

// stopProcess terminates the running server process and its children.
func (d *devServer) stopProcess() {
	if d.cmd == nil || d.cmd.Process == nil {
		return
	}
	// Kill the process group (server + any children)
	killProcessGroup(d.cmd.Process.Pid, syscall.SIGTERM)
	done := make(chan struct{})
	go func() {
		d.cmd.Wait()
		close(done)
	}()
	select {
	case <-done:
	case <-time.After(3 * time.Second):
		killProcessGroup(d.cmd.Process.Pid, syscall.SIGKILL)
		<-done
	}
	d.cmd = nil
}

func (d *devServer) stop() {
	d.mu.Lock()
	defer d.mu.Unlock()
	d.stopProcess()
}

// watchDirs adds all directories containing Go/template files to the watcher.
func (d *devServer) watchDirs(watcher *fsnotify.Watcher) {
	filepath.Walk(".", func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return nil
		}
		// Skip hidden dirs, build dirs, node_modules
		name := info.Name()
		if info.IsDir() && (strings.HasPrefix(name, ".") || name == "node_modules" || name == "build" || name == "vendor") {
			return filepath.SkipDir
		}
		if info.IsDir() {
			watcher.Add(path)
		}
		return nil
	})
}

// addWatchDir adds a new directory and its children to the watcher.
func (d *devServer) addWatchDir(watcher *fsnotify.Watcher, dir string) {
	filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return nil
		}
		name := info.Name()
		if info.IsDir() && (strings.HasPrefix(name, ".") || name == "node_modules" || name == "build" || name == "vendor") {
			return filepath.SkipDir
		}
		if info.IsDir() {
			watcher.Add(path)
		}
		return nil
	})
}

// isRelevantChange returns true if the file event should trigger a rebuild.
func isRelevantChange(event fsnotify.Event) bool {
	if !event.Has(fsnotify.Write) && !event.Has(fsnotify.Create) && !event.Has(fsnotify.Remove) {
		return false
	}
	ext := filepath.Ext(event.Name)
	switch ext {
	case ".go", ".html", ".tmpl":
		return true
	}
	return false
}

// findAppDir locates the app directory containing main.go.
// Checks common names, then falls back to root.
func findAppDir() string {
	for _, dir := range []string{"web", "app", "api", "cmd"} {
		if _, err := os.Stat(filepath.Join(dir, "main.go")); err == nil {
			return dir
		}
	}
	if _, err := os.Stat("main.go"); err == nil {
		return "."
	}
	log.Fatal("No main.go found in web/, app/, api/, cmd/, or root.\nRun 'congo init <name>' to create a project.")
	return ""
}