aboutsummaryrefslogtreecommitdiffstats
path: root/pkg/datamaps/config.go
blob: e64f1fdaea2ceaa508975834a7e4ea06a2c411a8 (plain) (blame)
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
package datamaps

import (
	"log"
	"os"
	"path/filepath"
)

const (
	config_dir_name = "datamaps-go"
	db_name         = "datamaps.db"
)

func getUserConfigDir() (string, error) {
	dir, err := os.UserConfigDir()
	if err != nil {
		return "", err
	}
	config_path := filepath.Join(dir, config_dir_name)
	return config_path, nil
}

func defaultDMPath() (string, error) {
	dir, err := os.UserHomeDir()
	if err != nil {
		return "", err
	}
	return filepath.Join(dir, "Documents", "datamaps"), nil
}

// TODO - need a func to replace Options.Command with the one we pass
// Needs to use flag.NewFlagSet so we can Parse on it in main.

type Options struct {
	Command     string
	DBPath      string
	DMPath      string
	DMName      string
	DMOverwrite bool
	DMInitial   bool
	DMData      []DatamapLine
}

func defaultOptions() *Options {
	dbpath, err := getUserConfigDir()
	if err != nil {
		log.Fatalf("Unable to get user config directory %v", err)
	}
	dmpath, err := defaultDMPath()
	if err != nil {
		log.Fatalf("Unable to get default datamaps directory %v", err)
	}
	return &Options{
		Command:     "help",
		DBPath:      filepath.Join(dbpath, "datamaps.db"),
		DMPath:      dmpath,
		DMName:      "Unnamed Datamap",
		DMOverwrite: false,
		DMInitial:   false,
		DMData:      make([]DatamapLine, 0),
	}
}

// nextString get the next string in a slice
func nextString(args []string, i *int, message string) string {
	if len(args) > *i+1 {
		*i++
	} else {
		log.Fatal(message)
	}
	return args[*i]
}

func processOptions(opts *Options, allArgs []string) {
	switch allArgs[0] {
	case "server":
		opts.Command = "server"
	case "datamap":
		opts.Command = "datamap"
	case "setup":
		opts.Command = "setup"
	default:
		log.Fatal("No relevant command provided.")
	}
	restArgs := allArgs[1:]
	for i := 0; i < len(allArgs[1:]); i++ {
		arg := restArgs[i]
		switch arg {
		case "-i", "--import":
			opts.DMPath = nextString(restArgs, &i, "import path required")
		case "-n", "--name":
			opts.DMName = nextString(restArgs, &i, "datamap name required")
		case "--overwrite":
			opts.DMOverwrite = true
		case "--initial":
			opts.DMInitial = true
		}
	}
}

func ParseOptions() *Options {
	opts := defaultOptions()
	processOptions(opts, os.Args[1:])
	return opts
}