|
| 1 | +package bootstrap |
| 2 | + |
| 3 | +import ( |
| 4 | + "github.com/alist-org/alist/v3/cmd/args" |
| 5 | + "github.com/alist-org/alist/v3/conf" |
| 6 | + "github.com/alist-org/alist/v3/pkg/utils" |
| 7 | + "github.com/caarlos0/env/v6" |
| 8 | + log "github.com/sirupsen/logrus" |
| 9 | + "io/ioutil" |
| 10 | + "os" |
| 11 | + "path/filepath" |
| 12 | +) |
| 13 | + |
| 14 | +func InitConfig() { |
| 15 | + log.Infof("reading config file: %s", args.Config) |
| 16 | + if !utils.Exists(args.Config) { |
| 17 | + log.Infof("config file not exists, creating default config file") |
| 18 | + _, err := utils.CreatNestedFile(args.Config) |
| 19 | + if err != nil { |
| 20 | + log.Fatalf("failed to create config file") |
| 21 | + } |
| 22 | + conf.Conf = conf.DefaultConfig() |
| 23 | + if !utils.WriteToJson(args.Config, conf.Conf) { |
| 24 | + log.Fatalf("failed to create default config file") |
| 25 | + } |
| 26 | + } else { |
| 27 | + configBytes, err := ioutil.ReadFile(args.Config) |
| 28 | + if err != nil { |
| 29 | + log.Fatalf("reading config file error:%s", err.Error()) |
| 30 | + } |
| 31 | + conf.Conf = conf.DefaultConfig() |
| 32 | + err = utils.Json.Unmarshal(configBytes, conf.Conf) |
| 33 | + if err != nil { |
| 34 | + log.Fatalf("load config error: %s", err.Error()) |
| 35 | + } |
| 36 | + log.Debugf("config:%+v", conf.Conf) |
| 37 | + // update config.json struct |
| 38 | + confBody, err := utils.Json.MarshalIndent(conf.Conf, "", " ") |
| 39 | + if err != nil { |
| 40 | + log.Fatalf("marshal config error:%s", err.Error()) |
| 41 | + } |
| 42 | + err = ioutil.WriteFile(args.Config, confBody, 0777) |
| 43 | + if err != nil { |
| 44 | + log.Fatalf("update config struct error: %s", err.Error()) |
| 45 | + } |
| 46 | + } |
| 47 | + if !conf.Conf.Force { |
| 48 | + confFromEnv() |
| 49 | + } |
| 50 | + err := os.RemoveAll(filepath.Join(conf.Conf.TempDir)) |
| 51 | + if err != nil { |
| 52 | + log.Errorln("failed delete temp file:", err) |
| 53 | + } |
| 54 | + err = os.MkdirAll(conf.Conf.TempDir, 0700) |
| 55 | + if err != nil { |
| 56 | + log.Fatalf("create temp dir error: %s", err.Error()) |
| 57 | + } |
| 58 | + log.Debugf("config: %+v", conf.Conf) |
| 59 | +} |
| 60 | + |
| 61 | +func confFromEnv() { |
| 62 | + prefix := "ALIST_" |
| 63 | + if args.NoPrefix { |
| 64 | + prefix = "" |
| 65 | + } |
| 66 | + log.Infof("load config from env with prefix: %s", prefix) |
| 67 | + if err := env.Parse(conf.Conf, env.Options{ |
| 68 | + Prefix: prefix, |
| 69 | + }); err != nil { |
| 70 | + log.Fatalf("load config from env error: %s", err.Error()) |
| 71 | + } |
| 72 | +} |
0 commit comments