/
packages.go
55 lines (50 loc) · 1.54 KB
/
packages.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
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
package base
import (
"fmt"
"os"
"path"
"path/filepath"
"golang.org/x/tools/go/packages"
)
// DefaultConfig for loading Go base.
var DefaultConfig = &packages.Config{Mode: packages.NeedName}
// PkgPath returns the Go package name for given target path.
// Even if the existing path is not exist yet in the filesystem.
//
// If base.Config is nil, DefaultConfig will be used to load base.
func PkgPath(config *packages.Config, target string) (string, error) {
if config == nil {
config = DefaultConfig
}
pathCheck, err := filepath.Abs(target)
if err != nil {
return "", err
}
var parts []string
if _, err := os.Stat(pathCheck); os.IsNotExist(err) {
parts = append(parts, filepath.Base(pathCheck))
pathCheck = filepath.Dir(pathCheck)
}
// Try maximum 2 directories above the given
// target to find the root package or module.
for i := 0; i < 2; i++ {
pkgs, err := packages.Load(config, pathCheck)
if err != nil {
return "", fmt.Errorf("load package info: %v", err)
}
if len(pkgs) == 0 || len(pkgs[0].Errors) != 0 {
parts = append(parts, filepath.Base(pathCheck))
pathCheck = filepath.Dir(pathCheck)
continue
}
pkgPath := pkgs[0].PkgPath
for j := len(parts) - 1; j >= 0; j-- {
pkgPath = path.Join(pkgPath, parts[j])
}
return pkgPath, nil
}
return "", fmt.Errorf("root package or module was not found for: %s", target)
}