app/cli.go

187 lines · 5242 bytes · executable

  1package app
  2
  3import (
  4	"bufio"
  5	"bytes"
  6	"encoding/json"
  7	"html/template"
  8	"os"
  9	"time"
 10)
 11
 12// ExecuteCommandLineArguments parses argv, applying the flags that override
 13// config and running one-shot commands such as --help and --add-instance. Some
 14// of those commands exit the process rather than return.
 15func ExecuteCommandLineArguments() {
 16	var helpmsg = `SkunkyArt v{{.Version}} [{{.Description}}]
 17Usage:
 18	- [-c|--config] 	| path to config
 19	- [-a|--add-instance]	| generates 'instances.json' and 'INSTANCES.md' files with ur instance
 20	- [-h|--help]		| returns this message
 21Example:
 22	./skunkyart -c config.json
 23Copyright lost+skunk and zerolabs, X11. https://gitbay.org/krz/skunky-art/releases`
 24
 25	a := os.Args[1:]
 26	for n, x := range a {
 27		switch x {
 28		case "-c", "--config":
 29			if n+1 < len(a) {
 30				CFG.cfg = a[n+1]
 31				cfgExplicit = true
 32			} else {
 33				exit("Not enought arguments", 1)
 34			}
 35		case "-h", "--help":
 36			var buf bytes.Buffer
 37			t := template.New("help")
 38			tryWithExitStatus(func() error {
 39				if _, err := t.Parse(helpmsg); err != nil {
 40					return err
 41				}
 42				return t.Execute(&buf, &Release)
 43			}(), 1)
 44			exit(buf.String(), 0)
 45		case "-a", "--add-instance":
 46			addInstance()
 47		}
 48	}
 49}
 50
 51type settingsUrls struct {
 52	I2P      string `json:"i2p,omitempty"`
 53	Ygg      string `json:"ygg,omitempty"`
 54	Tor      string `json:"tor,omitempty"`
 55	Clearnet string `json:"clearnet,omitempty"`
 56}
 57
 58type settingsParams struct {
 59	Nsfw   bool   `json:"nsfw"`
 60	Proxy  bool   `json:"proxy"`
 61	HideAI bool   `json:"hide-ai"`
 62	Theme  string `json:"theme"`
 63}
 64
 65type settings struct {
 66	Title       string         `json:"title"`
 67	Country     string         `json:"country"`
 68	ModifiedSrc string         `json:"modified-src,omitempty"`
 69	Urls        settingsUrls   `json:"urls"`
 70	Settings    settingsParams `json:"settings"`
 71}
 72
 73// promptLine asks for a line on stdin, repeating the question until it gets
 74// an answer when necessary is set.
 75func promptLine(txt string, necessary bool) string {
 76	input := bufio.NewScanner(os.Stdin)
 77	for {
 78		print(txt)
 79		print(": ")
 80		input.Scan()
 81
 82		if i := input.Text(); necessary && i == "" {
 83			println("Please specify the", txt)
 84		} else {
 85			return i
 86		}
 87	}
 88}
 89
 90// promptInstance asks for this instance's listing details; its settings come
 91// from the running configuration.
 92func promptInstance() settings {
 93	return settings{
 94		Title:       promptLine("Title", true),
 95		Country:     promptLine("Country", true),
 96		ModifiedSrc: promptLine("Link to modified sources", false),
 97		Settings: settingsParams{
 98			Nsfw:   CFG.Nsfw,
 99			Proxy:  CFG.Proxy,
100			HideAI: CFG.HideAI,
101			Theme:  CFG.Theme,
102		},
103		Urls: settingsUrls{
104			Clearnet: promptLine("Clearnet link", false),
105			Ygg:      promptLine("Yggdrasil link", false),
106			Tor:      promptLine("Onion link", false),
107			I2P:      promptLine("I2P link", false),
108		},
109	}
110}
111
112// instanceMarkdownRow is the INSTANCES.md table row for an instance.
113func instanceMarkdownRow(inst *settings) []byte {
114	var mdstr bytes.Buffer
115
116	mdbuilder := func(yes bool, link string, title string) {
117		switch {
118		case yes && (title != "" && link != ""):
119			mdstr.WriteString("[")
120			mdstr.WriteString(title)
121			mdstr.WriteString("](")
122			mdstr.WriteString(link)
123			mdstr.WriteString(")")
124		case yes && link != "":
125			mdstr.WriteString("[Yes](")
126			mdstr.WriteString(link)
127			mdstr.WriteString(")")
128		case yes:
129			mdstr.WriteString("Yes")
130		default:
131			mdstr.WriteString("No")
132		}
133		mdstr.WriteString("|")
134	}
135
136	mdstr.WriteString("\n|")
137	mdbuilder(inst.Urls.Clearnet != "", inst.Urls.Clearnet, inst.Title)
138	for _, url := range []string{inst.Urls.Ygg, inst.Urls.I2P, inst.Urls.Tor} {
139		mdbuilder(url != "", url, "")
140	}
141	for _, on := range []bool{inst.Settings.Nsfw, inst.Settings.Proxy} {
142		mdbuilder(on, "", "")
143	}
144	mdbuilder(inst.ModifiedSrc != "", inst.ModifiedSrc, "")
145
146	mdstr.WriteString(inst.Country)
147	mdstr.WriteString("|")
148	return mdstr.Bytes()
149}
150
151func addInstance() {
152	var settingsVar struct {
153		Instances []settings `json:"instances"`
154	}
155	// 0644: both files are committed to the repository and are meant to be
156	// world-readable, so gosec's 0600 default does not apply.
157	instancesJSON, err := os.OpenFile("instances.json", os.O_CREATE|os.O_WRONLY, 0644) //nolint:gosec // G302
158	if err != nil {
159		exit(err.Error(), 1)
160	}
161	defer func() { try(instancesJSON.Close()) }()
162
163	instancesFile, err := os.OpenFile("INSTANCES.md", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) //nolint:gosec // G302
164	if err != nil {
165		exit(err.Error(), 1)
166	}
167	defer func() { try(instancesFile.Close()) }()
168
169	for string(instances) == "" {
170		print("\rDownloading instance list...")
171		time.Sleep(500 * time.Millisecond)
172	}
173	println("\r\033[2KDownloaded!")
174	try(json.Unmarshal(instances, &settingsVar))
175
176	settingsVar.Instances = append(settingsVar.Instances, promptInstance())
177
178	j, err := json.MarshalIndent(&settingsVar, "", "    ")
179	try(err)
180
181	try(func() error { _, err := instancesJSON.Write(j); return err }())
182
183	row := instanceMarkdownRow(&settingsVar.Instances[len(settingsVar.Instances)-1])
184	try(func() error { _, err := instancesFile.Write(row); return err }())
185
186	exit("Done! Now add the files 'instances.json' and 'INSTANCES.md' to the 'main' branch by merge request to https://gitbay.org/krz/skunky-art", 0)
187}