Skip to content

Instantly share code, notes, and snippets.

@Integralist
Last active January 31, 2023 16:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Integralist/1e9df4944e366e46471953864858ff7e to your computer and use it in GitHub Desktop.
Save Integralist/1e9df4944e366e46471953864858ff7e to your computer and use it in GitHub Desktop.
[Go recursively search for a file until reaching user's home directory] #go #golang #search #file #recursive
package main
import (
"errors"
"fmt"
"os"
"path/filepath"
)
func main() {
// NOTE: Changing to /tmp was to catch issue with user not running under HOME.
err := os.Chdir("/tmp")
if err != nil {
panic(err)
}
wd, err := os.Getwd()
if err != nil {
panic(err)
}
home, err := os.UserHomeDir()
if err != nil {
panic(err)
}
err = recurse(wd, home)
if err != nil {
panic(err)
}
}
func recurse(wd, home string) error {
parent := filepath.Dir(wd)
var noManifest bool
path := filepath.Join(wd, "package.json")
fmt.Println("checking", path)
if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) {
noManifest = true
}
if !noManifest {
fmt.Println("found a manifest!")
return nil
}
// NOTE: The first condition catches if we reach the user's 'root' directory.
if wd != parent && wd != home {
return recurse(parent, home)
}
fmt.Println("no manifest found")
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment