github.com/flyinox/gosm@v0.0.0-20171117061539-16768cb62077/src/cmd/go/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  	"strings"
    11  )
    12  
    13  func getwd() string {
    14  	wd, err := os.Getwd()
    15  	if err != nil {
    16  		Fatalf("cannot determine current directory: %v", err)
    17  	}
    18  	return wd
    19  }
    20  
    21  var Cwd = getwd()
    22  
    23  // ShortPath returns an absolute or relative name for path, whatever is shorter.
    24  func ShortPath(path string) string {
    25  	if rel, err := filepath.Rel(Cwd, path); err == nil && len(rel) < len(path) {
    26  		return rel
    27  	}
    28  	return path
    29  }
    30  
    31  // RelPaths returns a copy of paths with absolute paths
    32  // made relative to the current directory if they would be shorter.
    33  func RelPaths(paths []string) []string {
    34  	var out []string
    35  	// TODO(rsc): Can this use Cwd from above?
    36  	pwd, _ := os.Getwd()
    37  	for _, p := range paths {
    38  		rel, err := filepath.Rel(pwd, p)
    39  		if err == nil && len(rel) < len(p) {
    40  			p = rel
    41  		}
    42  		out = append(out, p)
    43  	}
    44  	return out
    45  }
    46  
    47  // FilterDotUnderscoreFiles returns a slice containing all elements
    48  // of path whose base name doesn't begin with "." or "_".
    49  func FilterDotUnderscoreFiles(path []string) []string {
    50  	var out []string // lazily initialized
    51  	for i, p := range path {
    52  		base := filepath.Base(p)
    53  		if strings.HasPrefix(base, ".") || strings.HasPrefix(base, "_") {
    54  			if out == nil {
    55  				out = append(make([]string, 0, len(path)), path[:i]...)
    56  			}
    57  			continue
    58  		}
    59  		if out != nil {
    60  			out = append(out, p)
    61  		}
    62  	}
    63  	if out == nil {
    64  		return path
    65  	}
    66  	return out
    67  }
    68  
    69  // IsTestFile reports whether the source file is a set of tests and should therefore
    70  // be excluded from coverage analysis.
    71  func IsTestFile(file string) bool {
    72  	// We don't cover tests, only the code they test.
    73  	return strings.HasSuffix(file, "_test.go")
    74  }