Pārlūkot izejas kodu

qst: run things quickly.

Lucas Stadler 11 gadi atpakaļ
vecāks
revīzija
5641ce6f2f
1 mainītis faili ar 80 papildinājumiem un 0 dzēšanām
  1. 80 0
      go/qst.go

+ 80 - 0
go/qst.go

@ -0,0 +1,80 @@
1
package main
2
3
import "flag"
4
import "fmt"
5
import "log"
6
import "os"
7
import "os/exec"
8
import "path"
9
import "strings"
10
import "time"
11
12
/*
13
14
# the plan
15
16
qst: run things quickly
17
18
qst - detects the current project type and runs it
19
qst hello.rb - runs `ruby hello.rb`
20
qst hello.go - compiles & runs hello.go
21
22
qst -watch hello.go - watches changes to hello.go and recompiles and runs it on changes
23
24
*/
25
26
var mappings = map[string]func(string) string{
27
	".go": func(name string) string {
28
		return fmt.Sprintf("go build %s && ./%s", name, strings.TrimSuffix(name, path.Ext(name)))
29
	},
30
}
31
32
func main() {
33
	flag.Usage = func() {
34
		fmt.Fprintf(os.Stderr, "Usage: %s <file>\n", os.Args[0])
35
		flag.PrintDefaults()
36
	}
37
38
	flag.Parse()
39
	args := flag.Args()
40
41
	if len(args) < 1 {
42
		flag.Usage()
43
		os.Exit(1)
44
	}
45
46
	file := os.Args[1]
47
	if !isFile(file) {
48
		fmt.Fprintf(os.Stderr, "Error: %s is not a file.\n", file)
49
		os.Exit(1)
50
	}
51
52
	ext := path.Ext(file)
53
	fn, found := mappings[ext]
54
	if found {
55
		runAndWatch(file, fn(file))
56
	} else {
57
		fmt.Fprintf(os.Stderr, "Error: No command defined for %s files", ext)
58
		os.Exit(1)
59
	}
60
}
61
62
func runAndWatch(file string, cmd string) {
63
	// run command, if file changes (mtime) restart command
64
	// for now: run command until it exits, wait a bit, run again
65
	runShellCmd(cmd)
66
	time.Sleep(1 * time.Second)
67
	runAndWatch(file, cmd)
68
}
69
70
func runShellCmd(cmd string) {
71
	log.Printf("Running: `%s'", cmd)
72
	output, err := exec.Command("sh", "-c", cmd).CombinedOutput()
73
	os.Stderr.Write(output)
74
	log.Printf("Error running command: %s\n", err.Error())
75
}
76
77
func isFile(file string) bool {
78
	info, err := os.Stat(file)
79
	return err == nil && !info.IsDir()
80
}