summaryrefslogtreecommitdiffstats
path: root/src/cmd/go/internal/toolchain/path_windows.go
blob: 086c591e0589dfef2f8a60d59fc7e03691302331 (plain)
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package toolchain

import (
	"io/fs"
	"os"
	"path/filepath"
	"strings"
	"sync"

	"cmd/go/internal/gover"
)

// pathExts is a cached PATHEXT list.
var pathExts struct {
	once sync.Once
	list []string
}

func initPathExts() {
	var exts []string
	x := os.Getenv(`PATHEXT`)
	if x != "" {
		for _, e := range strings.Split(strings.ToLower(x), `;`) {
			if e == "" {
				continue
			}
			if e[0] != '.' {
				e = "." + e
			}
			exts = append(exts, e)
		}
	} else {
		exts = []string{".com", ".exe", ".bat", ".cmd"}
	}
	pathExts.list = exts
}

// pathDirs returns the directories in the system search path.
func pathDirs() []string {
	return filepath.SplitList(os.Getenv("PATH"))
}

// pathVersion returns the Go version implemented by the file
// described by de and info in directory dir.
// The analysis only uses the name itself; it does not run the program.
func pathVersion(dir string, de fs.DirEntry, info fs.FileInfo) (string, bool) {
	pathExts.once.Do(initPathExts)
	name, _, ok := cutExt(de.Name(), pathExts.list)
	if !ok {
		return "", false
	}
	v := gover.FromToolchain(name)
	if v == "" {
		return "", false
	}
	return v, true
}

// cutExt looks for any of the known extensions at the end of file.
// If one is found, cutExt returns the file name with the extension trimmed,
// the extension itself, and true to signal that an extension was found.
// Otherwise cutExt returns file, "", false.
func cutExt(file string, exts []string) (name, ext string, found bool) {
	i := strings.LastIndex(file, ".")
	if i < 0 {
		return file, "", false
	}
	for _, x := range exts {
		if strings.EqualFold(file[i:], x) {
			return file[:i], file[i:], true
		}
	}
	return file, "", false
}