Black Lives Matter. Support the Equal Justice Initiative.

Source file src/cmd/go/internal/base/path.go

Documentation: cmd/go/internal/base

     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  	"sync"
    12  )
    13  
    14  var cwd string
    15  var cwdOnce sync.Once
    16  
    17  // Cwd returns the current working directory at the time of the first call.
    18  func Cwd() string {
    19  	cwdOnce.Do(func() {
    20  		var err error
    21  		cwd, err = os.Getwd()
    22  		if err != nil {
    23  			Fatalf("cannot determine current directory: %v", err)
    24  		}
    25  	})
    26  	return cwd
    27  }
    28  
    29  // ShortPath returns an absolute or relative name for path, whatever is shorter.
    30  func ShortPath(path string) string {
    31  	if rel, err := filepath.Rel(Cwd(), path); err == nil && len(rel) < len(path) {
    32  		return rel
    33  	}
    34  	return path
    35  }
    36  
    37  // RelPaths returns a copy of paths with absolute paths
    38  // made relative to the current directory if they would be shorter.
    39  func RelPaths(paths []string) []string {
    40  	var out []string
    41  	for _, p := range paths {
    42  		rel, err := filepath.Rel(Cwd(), p)
    43  		if err == nil && len(rel) < len(p) {
    44  			p = rel
    45  		}
    46  		out = append(out, p)
    47  	}
    48  	return out
    49  }
    50  
    51  // IsTestFile reports whether the source file is a set of tests and should therefore
    52  // be excluded from coverage analysis.
    53  func IsTestFile(file string) bool {
    54  	// We don't cover tests, only the code they test.
    55  	return strings.HasSuffix(file, "_test.go")
    56  }
    57  

View as plain text