« Back to Index

Go: recursively search for a file until reaching user’s home directory

View original Gist on GitHub

Tags: #go #search #recursive

main.go

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
}