package cli import ( "errors" "fmt" "io" "os" "path/filepath" "gopkg.in/yaml.v3" ) // initProfile is the intentionally small profile written by init. It avoids // marshaling every optional config field and keeps the starter file readable. type initProfile struct { DSN string `yaml:"dsn"` Baseline string `yaml:"baseline"` Output string `yaml:"output"` Schemas []string `yaml:"schema"` FailOn string `yaml:"fail_on"` } // initConfig is the YAML document produced by init. type initConfig struct { Default string `yaml:"default"` Profiles map[string]initProfile `yaml:"profiles"` } // runInit writes a starter .pgics.yaml. It never connects to PostgreSQL and // refuses to overwrite an existing config unless --force is set. func runInit(args []string, stdout, stderr io.Writer) int { fs := newFlagSet("init", stderr) configPath := fs.String("output", ".pgics.yaml", "config file to create, or - for stdout") profile := fs.String("profile", "default", "profile name") dsn := fs.String("dsn", "env:DATABASE_URL", "connection string or env:NAME") baseline := fs.String("baseline", "", "baseline path, default baselines/.json") force := fs.Bool("force", false, "overwrite an existing config") quiet := fs.Bool("quiet", false, "suppress the created-file message") var schemas stringList fs.Var(&schemas, "schema", "schema to include; repeatable") if code := parseFlags(fs, args, stderr); code >= 0 { return code } if *profile == "" { return commandError(stderr, errors.New("--profile must not be empty")) } if len(schemas) == 0 { schemas = stringList{"public"} } baselinePath := *baseline if baselinePath == "" { baselinePath = filepath.Join("baselines", *profile+".json") } cfg := initConfig{ Default: *profile, Profiles: map[string]initProfile{ *profile: { DSN: *dsn, Baseline: baselinePath, Output: baselinePath, Schemas: []string(schemas), FailOn: "any", }, }, } body, err := yaml.Marshal(cfg) if err != nil { return commandError(stderr, err) } if *configPath == "-" { fmt.Fprint(stdout, "# Generated by pg_integrity_checksums init\n") _, _ = stdout.Write(body) return 0 } if !*force { if _, err := os.Stat(*configPath); err == nil { return commandError(stderr, fmt.Errorf("%s already exists (use --force to overwrite)", *configPath)) } } configDir := filepath.Dir(*configPath) if configDir != "." { if err := os.MkdirAll(configDir, 0o755); err != nil { return commandError(stderr, err) } } if dir := filepath.Dir(baselinePath); dir != "." { if !filepath.IsAbs(dir) { dir = filepath.Join(configDir, dir) } if err := os.MkdirAll(dir, 0o755); err != nil { return commandError(stderr, err) } } if err := os.WriteFile(*configPath, append([]byte("# Generated by pg_integrity_checksums init\n"), body...), 0o644); err != nil { return commandError(stderr, err) } if !*quiet { fmt.Fprintf(stderr, "wrote %s\n", *configPath) } return 0 }