From f2c4ba662ff117297bc5f5bcd52e2dd0ef9107b4 Mon Sep 17 00:00:00 2001 From: "Dr. Stefan Schimanski" Date: Fri, 2 Jun 2023 09:14:18 +0200 Subject: [PATCH] Recursively search goio.yaml --- README.md | 7 +++---- main.go | 29 ++++++++++++++++++++++++++++- 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 32480d2..3182298 100644 --- a/README.md +++ b/README.md @@ -10,11 +10,10 @@ A customizable imports organizer for the Go programming language # Summary `goio` is a fully customizable Go imports organizer. The configuration -is project based and is stored in a `goio.yaml` file in the root of your +is project based and is stored in a `goio.yaml` file, e.g. in the root of your module's project folder alongside the `go.mod` file. For consistency -the `goio.yaml` file should be committed to your projects vcs. - - +the `goio.yaml` file should be committed to your projects vcs. If no `goio.yaml` +file is found, `goio` will try to find one walking up the directory tree. # Command Line Tool diff --git a/main.go b/main.go index a449dac..0059729 100644 --- a/main.go +++ b/main.go @@ -76,8 +76,19 @@ func main() { os.Exit(1) } + // Find a goio.yaml file in the current directory or any parent directory + path, found, err := findFile(currentDir, "goio.yaml") + if err != nil { + fmt.Fprintf(os.Stderr, "error occurred finding configuration file goio.yaml: %v\n", err) + os.Exit(1) + } + if !found { + fmt.Fprint(os.Stderr, "error occurred finding configuration file goio.yaml\n") + os.Exit(1) + } + // Load the configuration from the goio.yaml file - conf, err := config.Load("goio.yaml") + conf, err := config.Load(path) if err != nil { fmt.Fprintf(os.Stderr, "error occurred loading configuration file: %s\n", err.Error()) os.Exit(1) @@ -184,3 +195,19 @@ func main() { } } } + +func findFile(path, fileName string) (string, bool, error) { + for { + _, err := os.Stat(filepath.Join(path, fileName)) + if err == nil { + return filepath.Join(path, fileName), true, nil + } + if !os.IsNotExist(err) { + return "", false, err + } + if path == "/" { + return "", false, nil + } + path = filepath.Dir(path) + } +}