File: package.go

package info (click to toggle)
golang-github-azure-azure-sdk-for-go 68.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 556,256 kB
  • sloc: javascript: 196; sh: 96; makefile: 7
file content (188 lines) | stat: -rw-r--r-- 4,746 bytes parent folder | download
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

package exports

import (
	"fmt"
	"go/ast"
	"go/parser"
	"go/token"
	"io/ioutil"
	"os"
	"strings"
)

// Package represents a Go package.
type Package struct {
	f     *token.FileSet
	p     *ast.Package
	files map[string][]byte
}

// LoadPackageErrorInfo provides extended information about certain LoadPackage() failures.
type LoadPackageErrorInfo interface {
	Packages() []string
}

type errorInfo struct {
	m string
	p []string
}

func (ei errorInfo) Error() string {
	return ei.m
}

func (ei errorInfo) Packages() []string {
	return ei.p
}

var _ LoadPackageErrorInfo = (*errorInfo)(nil)

// LoadPackage loads the package in the specified directory.
// It's required there is only one package in the directory.
func LoadPackage(dir string) (pkg Package, err error) {
	pkg.files = map[string][]byte{}
	pkg.f = token.NewFileSet()
	packages, err := parser.ParseDir(pkg.f, dir, func(f os.FileInfo) bool {
		// exclude test files
		return !strings.HasSuffix(f.Name(), "_test.go")
	}, 0)
	if err != nil {
		return
	}
	if len(packages) < 1 {
		err = errorInfo{
			m: fmt.Sprintf("didn't find any packages in '%s'", dir),
		}
		return
	}
	if len(packages) > 1 {
		pkgs := []string{}
		for p := range packages {
			pkgs = append(pkgs, p)
		}
		err = errorInfo{
			m: fmt.Sprintf("found multiple packages in '%s': %s", dir, strings.Join(pkgs, ", ")),
			p: pkgs,
		}
		return
	}
	for pn := range packages {
		p := packages[pn]
		// trim any non-exported nodes
		if exp := ast.PackageExports(p); !exp {
			err = fmt.Errorf("package '%s' doesn't contain any exports", pn)
			return
		}
		pkg.p = p
		return
	}
	// shouldn't ever get here...
	panic("failed to return package")
}

// GetExports returns the exported content of the package.
func (pkg Package) GetExports() (c Content) {
	c = NewContent()
	ast.Inspect(pkg.p, func(n ast.Node) bool {
		switch x := n.(type) {
		case *ast.TypeSpec:
			if t, ok := x.Type.(*ast.StructType); ok {
				c.addStruct(pkg, x.Name.Name, t)
			} else if t, ok := x.Type.(*ast.InterfaceType); ok {
				c.addInterface(pkg, x.Name.Name, t)
			}
		case *ast.FuncDecl:
			c.addFunc(pkg, x)
			// return false as we don't care about the function body.
			// this is super important as it filters out the majority of
			// the package's AST making it WAY easier to find the bits
			// of interest (not doing this will break a lot of code).
			return false
		case *ast.GenDecl:
			if x.Tok == token.CONST {
				c.addConst(pkg, x)
			}
		}
		return true
	})
	return
}

// Name returns the package name.
func (pkg Package) Name() string {
	return pkg.p.Name
}

// Get loads the package in the specified directory and returns the exported
// content.  It's a convenience wrapper around LoadPackage() and GetExports().
func Get(pkgDir string) (Content, error) {
	pkg, err := LoadPackage(pkgDir)
	if err != nil {
		return Content{}, err
	}
	return pkg.GetExports(), nil
}

// returns the text between [start, end]
func (pkg Package) getText(start token.Pos, end token.Pos) string {
	// convert to absolute position within the containing file
	p := pkg.f.Position(start)
	// check if the file has been loaded, if not then load it
	if _, ok := pkg.files[p.Filename]; !ok {
		b, err := ioutil.ReadFile(p.Filename)
		if err != nil {
			panic(err)
		}
		pkg.files[p.Filename] = b
	}
	return string(pkg.files[p.Filename][p.Offset : p.Offset+int(end-start)])
}

// iterates over the specified field list, for each field the specified
// callback is invoked with the name of the field and the type name.  the field
// name can be nil, e.g. anonymous fields in structs, unnamed return types etc.
func (pkg Package) translateFieldList(fl []*ast.Field, cb func(*string, string, *ast.Field)) {
	for _, f := range fl {
		var name *string
		if f.Names != nil {
			n := pkg.getText(f.Names[0].Pos(), f.Names[0].End())
			name = &n
		}
		t := pkg.getText(f.Type.Pos(), f.Type.End())
		cb(name, t, f)
	}
}

// creates a Func object from the specified ast.FuncType
func (pkg Package) buildFunc(ft *ast.FuncType) (f Func) {
	// appends a to s, comma-delimited style, and returns s
	appendString := func(s, a string) string {
		if s != "" {
			s += ", "
		}
		s += a
		return s
	}

	// build the params type list
	if ft.Params.List != nil {
		p := ""
		pkg.translateFieldList(ft.Params.List, func(n *string, t string, f *ast.Field) {
			p = appendString(p, t)
		})
		f.Params = &p
	}

	// build the return types list
	if ft.Results != nil {
		r := ""
		pkg.translateFieldList(ft.Results.List, func(n *string, t string, f *ast.Field) {
			r = appendString(r, t)
		})
		f.Returns = &r
	}
	return
}