mlisting

Mailing list service

git clone git://git.lin.moe/go/mlisting.git

 1package cmd
 2
 3import (
 4	"fmt"
 5
 6	"git.lin.moe/go/mlisting/config"
 7	"git.lin.moe/go/mlisting/storage"
 8	"git.lin.moe/go/mlisting/storage/sqlite"
 9	"github.com/spf13/cobra"
10)
11
12var Cmd *cobra.Command
13var VERSION string = "unknown"
14
15func init() {
16	Cmd = &cobra.Command{
17		Use:               "mlisting",
18		Short:             "a tiny mailing list service",
19		PersistentPreRunE: prepareConfig,
20		PersistentPostRunE: func(cmd *cobra.Command, args []string) error {
21			st, ok := storage.FromContext(cmd.Context())
22			if ok {
23				return st.Shutdown(cmd.Context())
24			}
25
26			return nil
27		},
28		CompletionOptions: cobra.CompletionOptions{
29			HiddenDefaultCmd: true,
30		},
31	}
32
33	pf := Cmd.PersistentFlags()
34	pf.StringP("config", "c", "/etc/mlisting/config.toml", "configuration file")
35
36	Cmd.AddCommand(&cobra.Command{
37		Use:   "version",
38		Short: "Show version",
39		Run: func(cmd *cobra.Command, args []string) {
40			cmd.Printf("version: %s", VERSION)
41		},
42	})
43}
44
45func prepareConfig(cmd *cobra.Command, args []string) error {
46	if cmd.Name() == "help" {
47		return nil
48	}
49
50	ctx := cmd.Context()
51	fpath, err := cmd.Flags().GetString("config")
52	if err != nil {
53		return err
54	}
55	cfg, err := config.ParseToml(fpath)
56	if err != nil {
57		cfg = config.DefaultConfig
58	}
59	ctx = config.Context(ctx, cfg)
60
61	st, err := openStorage(cfg.Storage.Driver, cfg.Storage.DSN)
62	if err != nil {
63		return err
64	}
65	ctx = storage.Context(ctx, st)
66
67	cmd.SetContext(ctx)
68	return nil
69}
70
71func openStorage(driver, dsn string) (st storage.Storage, err error) {
72	switch driver {
73	case "sqlite3":
74		st, err = sqlite.NewStorage(dsn)
75		if err != nil {
76			return
77		}
78	default:
79		err = fmt.Errorf("unknown storage driver %s", driver)
80	}
81
82	return
83}