cmd/shrt/main.go in go-shrt

at v0.4.1

1// See LICENSE file for copyright and license details
2
3//go:generate go test -v -run=TestDocsUpToDate -fixdocs
4
5package main
6
7import (
8 "context"
9 "flag"
10 "fmt"
11 "log"
12 "os"
13
14 "djmo.ch/go-shrt/cmd/shrt/internal/base"
15 "djmo.ch/go-shrt/cmd/shrt/internal/env"
16 "djmo.ch/go-shrt/cmd/shrt/internal/help"
17 "djmo.ch/go-shrt/cmd/shrt/internal/serve"
18 "djmo.ch/go-shrt/cmd/shrt/internal/version"
19)
20
21func init() {
22 base.Shrt.Subcommands = []*base.Command{
23 serve.Cmd,
24 env.Cmd,
25 version.Cmd,
26
27 help.EnvCmd,
28 }
29}
30
31func usagefunc(r int) func() {
32 return func() {
33 fmt.Fprintf(os.Stderr, "usage: %s [-hv] [-d dbpath] [-c cfgpath] [-l listenaddr] [init]\n",
34 os.Args[0])
35 os.Exit(r)
36 }
37}
38
39func main() {
40 log.SetFlags(0)
41 log.SetPrefix(os.Args[0] + ": ")
42 flag.Usage = usagefunc(0)
43 flag.Parse()
44
45 env.MergeEnv()
46 cfg := env.ConfigFromEnv()
47
48 args := flag.Args()
49 if len(args) < 1 {
50 usagefunc(1)()
51 }
52
53 ctx := context.Background()
54 ctx = context.WithValue(ctx, "args", args[1:])
55 ctx = context.WithValue(ctx, "w", os.Stdout)
56 ctx = context.WithValue(ctx, "cfg", cfg)
57
58 if args[0] == "help" {
59 help.Help(ctx)
60 return
61 }
62
63 cmd := base.FindCommand(args[0])
64 if cmd == nil {
65 fmt.Fprintf(os.Stderr, "%s %s: unknown command\n", os.Args[0], args[0])
66 fmt.Fprintf(os.Stderr, "Run '%s help' for usage\n", os.Args[0])
67 os.Exit(1)
68 }
69
70 cmd.Flags.Parse(os.Args[2:])
71 ctx = context.WithValue(ctx, "args", cmd.Flags.Args())
72
73 cmd.Run(ctx)
74}