From f33c435383233cefd58b56fad5272f41d7a80f22 Mon Sep 17 00:00:00 2001 From: Or Elimelech Date: Tue, 15 Oct 2024 23:14:10 +0300 Subject: [PATCH] chore: support config --- .gitignore | 1 + config/config.go | 25 +++++++++++++++++++++++++ example.config.json | 5 +++++ main.go | 24 ++++++++++++++++++++++-- route/route.go | 2 +- 5 files changed, 54 insertions(+), 3 deletions(-) create mode 100644 .gitignore create mode 100644 config/config.go create mode 100644 example.config.json diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..361b2e8 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/bufile diff --git a/config/config.go b/config/config.go new file mode 100644 index 0000000..b452b1b --- /dev/null +++ b/config/config.go @@ -0,0 +1,25 @@ +package config + +import ( + "encoding/json" + "fmt" + "os" +) + +type Config struct { + Modules []string `json:"modules"` +} + +func Parse(path string) (Config, error) { + var cfg Config + f, err := os.ReadFile(path) + if err != nil { + return cfg, fmt.Errorf("reading config file: %w", err) + } + + err = json.Unmarshal(f, &cfg) + if err != nil { + return cfg, fmt.Errorf("parsing config file: %w", err) + } + return cfg, nil +} diff --git a/example.config.json b/example.config.json new file mode 100644 index 0000000..2be9ea4 --- /dev/null +++ b/example.config.json @@ -0,0 +1,5 @@ +{ + "modules": [ + "buf.build/vic3lord/bufile" + ] +} diff --git a/main.go b/main.go index a381036..475e088 100644 --- a/main.go +++ b/main.go @@ -2,15 +2,35 @@ package main import ( "context" + "flag" "log" + "log/slog" "os" + "github.com/vic3lord/bufile/config" "github.com/vic3lord/bufile/route" ) +var ( + configFile = flag.String("config", "bufile.json", "Path to config file") +) + func main() { - err := route.Generate(context.Background(), os.Stdout) + flag.Parse() + cfg, err := config.Parse(*configFile) if err != nil { - log.Fatalf("failed to generate routes: %v", err) + log.Fatalf("Failed to parse config: %v", err) + } + + ctx := context.Background() + for _, mod := range cfg.Modules { + err = route.Generate(ctx, mod, os.Stdout) + if err != nil { + l := slog.With( + slog.String("module", mod), + slog.String("err", err.Error()), + ) + l.Error("failed to generate routes") + } } } diff --git a/route/route.go b/route/route.go index 7d96ca1..cd9086d 100644 --- a/route/route.go +++ b/route/route.go @@ -35,7 +35,7 @@ type Rule struct { //go:embed template.yaml var routesTemplate string -func Generate(ctx context.Context, w io.Writer) error { +func Generate(ctx context.Context, mod string, w io.Writer) error { tmpl, err := template.New("routes-template").Parse(routesTemplate) if err != nil { return err