Last active
January 31, 2023 16:52
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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