-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
62 lines (54 loc) · 1.04 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package main
import (
"flag"
"fmt"
"os"
"path/filepath"
"strings"
)
func findClosest(filename string, searchAll bool) ([]string, error) {
pwd, err := os.Getwd()
if err != nil {
return nil, nil
}
var paths []string
for true {
path := filepath.Join(pwd, filename)
if _, err := os.Stat(path); err == nil {
paths = append(paths, path)
if !searchAll {
break
}
}
if pwd == "/" {
if len(paths) == 0 {
return nil, fmt.Errorf("File not found: %s", filename)
}
break
}
pwd = filepath.Dir(pwd)
}
return paths, nil
}
func printUsage() {
fmt.Println("Usage: closest [options] [pattern]")
fmt.Println("Options:")
flag.PrintDefaults()
}
func main() {
flag.Usage = printUsage
searchAll := flag.Bool("a", false, "Search all files[default: false]")
flag.Parse()
args := flag.Args()
if len(args) < 1 {
flag.Usage()
os.Exit(1)
}
filename := args[0]
paths, err := findClosest(filename, *searchAll)
if err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
os.Exit(1)
}
fmt.Println(strings.Join(paths, "\n"))
}