X-Git-Url: https://ruderich.org/simon/gitweb/?p=nsscash%2Fnsscash.git;a=blobdiff_plain;f=config.go;fp=config.go;h=8e9a6308124a4d74adb7f8e2dde1ad82f16b84bf;hp=0000000000000000000000000000000000000000;hb=92afde4e875a96e1ab865e29b9f0d11b08d7db1c;hpb=748846b9a65726fd19d43b45a4db68ef4c2e77f4 diff --git a/config.go b/config.go new file mode 100644 index 0000000..8e9a630 --- /dev/null +++ b/config.go @@ -0,0 +1,87 @@ +// Configuration file parsing and validation + +// Copyright (C) 2019 Simon Ruderich +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +package main + +import ( + "fmt" + + "github.com/BurntSushi/toml" +) + +type Config struct { + StatePath string + Files []File `toml:"file"` +} + +type File struct { + Type FileType + Url string + Path string + + body []byte // internally used by handleFiles() +} + +//go:generate stringer -type=FileType +type FileType int + +const ( + FileTypePlain FileType = iota + FileTypePasswd +) + +func (t *FileType) UnmarshalText(text []byte) error { + switch string(text) { + case "plain": + *t = FileTypePlain + case "passwd": + *t = FileTypePasswd + default: + return fmt.Errorf("invalid file type %q", text) + } + return nil +} + +func LoadConfig(path string) (*Config, error) { + var cfg Config + + md, err := toml.DecodeFile(path, &cfg) + if err != nil { + return nil, err + } + undecoded := md.Undecoded() + if len(undecoded) != 0 { + return nil, fmt.Errorf("invalid fields used: %q", undecoded) + } + + if cfg.StatePath == "" { + return nil, fmt.Errorf("statepath must not be empty") + } + + for i, f := range cfg.Files { + if f.Url == "" { + return nil, fmt.Errorf( + "file[%d].url must not be empty", i) + } + if f.Path == "" { + return nil, fmt.Errorf( + "file[%d].path must not be empty", i) + } + } + + return &cfg, nil +}