X-Git-Url: https://ruderich.org/simon/gitweb/?a=blobdiff_plain;f=main.go;h=0dd00294634b1759fa9bc8a59bfeeea79cffd39e;hb=22695332931698776b4075451435025377bdb3d1;hp=cef6c61d41bfe9dfef0c8995ab25cf8b4762d7c9;hpb=01d938ad14224aa2c84f8814ab955bb99f6f5b34;p=nsscash%2Fnsscash.git diff --git a/main.go b/main.go index cef6c61..0dd0029 100644 --- a/main.go +++ b/main.go @@ -49,19 +49,7 @@ func main() { break } - cfg, err := LoadConfig(args[1]) - if err != nil { - log.Fatal(err) - } - state, err := LoadState(cfg.StatePath) - if err != nil { - log.Fatal(err) - } - err = handleFiles(cfg, state) - if err != nil { - log.Fatal(err) - } - err = WriteStateIfChanged(cfg.StatePath, state) + err := mainFetch(args[1]) if err != nil { log.Fatal(err) } @@ -72,45 +60,90 @@ func main() { break } - var t FileType - err := t.UnmarshalText([]byte(args[1])) + err := mainConvert(args[1], args[2], args[3]) if err != nil { log.Fatal(err) } + return + } - src, err := ioutil.ReadFile(args[2]) + flag.Usage() + os.Exit(1) +} + +func mainFetch(cfgPath string) error { + cfg, err := LoadConfig(cfgPath) if err != nil { - log.Fatal(err) + return err } - pws, err := ParsePasswds(bytes.NewReader(src)) + state, err := LoadState(cfg.StatePath) if err != nil { - log.Fatal(err) + return err } - var x bytes.Buffer - err = SerializePasswds(&x, pws) + err = handleFiles(cfg, state) if err != nil { - log.Fatal(err) + return err + } + // NOTE: Make sure to call WriteState() only if there were no + // errors (see WriteState() and README) + err = WriteState(cfg.StatePath, state) + if err != nil { + return err + } + return nil +} + +func mainConvert(typ, srcPath, dstPath string) error { + var t FileType + err := t.UnmarshalText([]byte(typ)) + if err != nil { + return err + } + + src, err := ioutil.ReadFile(srcPath) + if err != nil { + return err + } + var x bytes.Buffer + if t == FileTypePlain { + x.Write(src) + } else if t == FileTypePasswd { + pws, err := ParsePasswds(bytes.NewReader(src)) + if err != nil { + return err + } + err = SerializePasswds(&x, pws) + if err != nil { + return err + } + } else if t == FileTypeGroup { + grs, err := ParseGroups(bytes.NewReader(src)) + if err != nil { + return err + } + err = SerializeGroups(&x, grs) + if err != nil { + return err + } + } else { + return fmt.Errorf("unsupported file type %v", t) } // We must create the file first or deployFile() will abort - f, err := os.Create(args[3]) + f, err := os.Create(dstPath) if err != nil { - log.Fatal(err) + return err } f.Close() err = deployFile(&File{ Type: t, - Url: args[2], - Path: args[3], + Url: srcPath, + Path: dstPath, body: x.Bytes(), }) if err != nil { - log.Fatal(err) + return err } - return - } - - flag.Usage() - os.Exit(1) + return nil }