1package main
2
3import (
4	"context"
5	"flag"
6	"fmt"
7	"os"
8	"strings"
9	"text/tabwriter"
10)
11
12// DatabasesCommand is a command for listing managed databases.
13type DatabasesCommand struct{}
14
15// Run executes the command.
16func (c *DatabasesCommand) Run(ctx context.Context, args []string) (err error) {
17	fs := flag.NewFlagSet("litestream-databases", flag.ContinueOnError)
18	configPath, noExpandEnv := registerConfigFlag(fs)
19	fs.Usage = c.Usage
20	if err := fs.Parse(args); err != nil {
21		return err
22	} else if fs.NArg() != 0 {
23		return fmt.Errorf("too many arguments")
24	}
25
26	// Load configuration.
27	if *configPath == "" {
28		*configPath = DefaultConfigPath()
29	}
30	config, err := ReadConfigFile(*configPath, !*noExpandEnv)
31	if err != nil {
32		return err
33	}
34
35	// List all databases.
36	w := tabwriter.NewWriter(os.Stdout, 0, 8, 2, ' ', 0)
37	defer w.Flush()
38
39	fmt.Fprintln(w, "path\treplicas")
40	for _, dbConfig := range config.DBs {
41		db, err := NewDBFromConfig(dbConfig)
42		if err != nil {
43			return err
44		}
45
46		var replicaNames []string
47		for _, r := range db.Replicas {
48			replicaNames = append(replicaNames, r.Name())
49		}
50
51		fmt.Fprintf(w, "%s\t%s\n",
52			db.Path(),
53			strings.Join(replicaNames, ","),
54		)
55	}
56
57	return nil
58}
59
60// Usage prints the help screen to STDOUT.
61func (c *DatabasesCommand) Usage() {
62	fmt.Printf(`
63The databases command lists all databases in the configuration file.
64
65Usage:
66
67	litestream databases [arguments]
68
69Arguments:
70
71	-config PATH
72	    Specifies the configuration file.
73	    Defaults to %s
74
75	-no-expand-env
76	    Disables environment variable expansion in configuration file.
77
78`[1:],
79		DefaultConfigPath(),
80	)
81}
82