github.com/bir3/gocompiler@v0.3.205/src/cmd/gocmd/internal/base/path.go (about) 1 // Copyright 2017 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package base 6 7 import ( 8 "os" 9 "path/filepath" 10 "runtime" 11 "strings" 12 "sync" 13 ) 14 15 var cwd string 16 var cwdOnce sync.Once 17 18 // Cwd returns the current working directory at the time of the first call. 19 func Cwd() string { 20 cwdOnce.Do(func() { 21 var err error 22 cwd, err = os.Getwd() 23 if err != nil { 24 Fatalf("cannot determine current directory: %v", err) 25 } 26 }) 27 return cwd 28 } 29 30 // ShortPath returns an absolute or relative name for path, whatever is shorter. 31 func ShortPath(path string) string { 32 if rel, err := filepath.Rel(Cwd(), path); err == nil && len(rel) < len(path) { 33 return rel 34 } 35 return path 36 } 37 38 // RelPaths returns a copy of paths with absolute paths 39 // made relative to the current directory if they would be shorter. 40 func RelPaths(paths []string) []string { 41 var out []string 42 for _, p := range paths { 43 rel, err := filepath.Rel(Cwd(), p) 44 if err == nil && len(rel) < len(p) { 45 p = rel 46 } 47 out = append(out, p) 48 } 49 return out 50 } 51 52 // IsTestFile reports whether the source file is a set of tests and should therefore 53 // be excluded from coverage analysis. 54 func IsTestFile(file string) bool { 55 // We don't cover tests, only the code they test. 56 return strings.HasSuffix(file, "_test.go") 57 } 58 59 // IsNull reports whether the path is a common name for the null device. 60 // It returns true for /dev/null on Unix, or NUL (case-insensitive) on Windows. 61 func IsNull(path string) bool { 62 if path == os.DevNull { 63 return true 64 } 65 if runtime.GOOS == "windows" { 66 if strings.EqualFold(path, "NUL") { 67 return true 68 } 69 } 70 return false 71 }