This repository has been archived by the owner on Sep 25, 2023. It is now read-only.
/
init.go
75 lines (63 loc) · 1.43 KB
/
init.go
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
package main
import (
"bytes"
"fmt"
"os"
"path/filepath"
"github.com/urfave/cli/v2"
"golang.org/x/xerrors"
"gopkg.in/yaml.v3"
)
func initFlags() []cli.Flag {
return []cli.Flag{
&cli.IntFlag{
Name: "app-id",
Required: true,
Usage: "telegram app ID",
EnvVars: []string{"APP_ID"},
},
&cli.StringFlag{
Name: "app-hash",
Required: true,
Usage: "telegram app hash",
EnvVars: []string{"APP_HASH"},
},
&cli.StringFlag{
Name: "token",
Required: true,
Usage: "telegram bot token",
EnvVars: []string{"BOT_TOKEN"},
},
}
}
func writeConfig(cfgPath string, cfg Config) error {
buf := new(bytes.Buffer)
e := yaml.NewEncoder(buf)
e.SetIndent(2)
if err := e.Encode(cfg); err != nil {
return xerrors.Errorf("encode: %w", err)
}
if _, err := os.Stat(cfgPath); err == nil {
return xerrors.Errorf("file %s exist", cfgPath)
}
if err := os.MkdirAll(filepath.Dir(cfgPath), 0o700); err != nil {
return err
}
if err := os.WriteFile(cfgPath, buf.Bytes(), 0o600); err != nil {
return xerrors.Errorf("write: %w", err)
}
return nil
}
func initCmd(c *cli.Context) error {
sampleCfg := Config{
AppID: c.Int("app-id"),
AppHash: c.String("app-hash"),
BotToken: c.String("token"),
}
cfgPath := c.String("config")
if cfgPath == "" {
return xerrors.Errorf("no config path provided")
}
defer fmt.Println("Wrote config to", cfgPath)
return writeConfig(cfgPath, sampleCfg)
}