DevelopOther
@holtkeeper/go-source
Everything Holtkeeper knows about Go source, in TypeScript: no Go toolchain, no network, no parser dependency. Module discovery and go.mod parsing, the public API of a module, import paths resolved to modules, package-level uses in a file, and which module a git tag releases. The one exception is the optional typed usage pass (goTypedUsages), which runs a small Go helper shipped as source with the job’s own go. libraries, depgraph-go, api-surface, usages and quality-tests build on it.
import { discoverGoModules, goModuleApi, resolveGoImport, scanGoUsages,} from '@holtkeeper/go-source'
const { modules } = await discoverGoModules(checkout)const api = goModuleApi(filesOfModule, { includeInternal: true })const { imports, sites } = scanGoUsages(source)const where = resolveGoImport(sites[0].importPath, owningModule, modules)Modules and go.mod
Section titled “Modules and go.mod”parseGoMod(content): GoMod—module,go,require({ path, version, indirect? },indirectonly for a// indirectmarker),replace({ path, version?, to, toVersion?, local };localwhen the target is a directory:./,../or absolute) andexclude({ path, version }), from both the single-line and the block forms.parseGoSum(content): GoSumEntry[]— the lines of ago.sumas{ path, version, kind },kindgo.modforv1.2.3/go.modlines (hash of thego.modonly) andmodulefor the tree hash; malformed lines are skipped.parseGoWork(content)— theusedirectories of ago.work, normalized.findGoModules(dir, depth = 4)— directories holding ago.mod,.first, skippingnode_modules,vendor,testdataand hidden directories.readGoModules(dir, dirs): GoWorkspaceModule[]—{ module, dir, mod }per directory with ago.modthat names a module.discoverGoModules(dir, depth = 4)— thego.workmembers when the root has ago.work(workspace: true), otherwise everygo.modfound.- Module helpers:
libraryOfModule(drops the/vNsuffix),modulePathOf(name, version),isPseudoVersion,compareGoVersions,isStableGoVersion,escapeModulePath.
Public API
Section titled “Public API”goModuleApi(files, { module?, version?, maxSymbols?, includeInternal? }): GoModuleApi reads one module’s files (paths relative to the module root) and returns { module, packages, mainPackages, internalPackages }:
- One
ApiPackageper library package directory:nameis the full import path,diris relative to the module root,ecosystem: 'Go',moduleis the module path, and a single entry.lists exported functions, methods (Type.Method), types (typeorinterface), constants and variables (variable; the signature starts withconstorvar), with doc comments,Deprecated:paragraphs asdeprecatedand the package doc’s first sentence asdescription. Unexported struct fields show as// contains filtered or unexported fields. - Packages under
internal/are counted ininternalPackages, and listed withprivate: trueonly withincludeInternal(default false). package maindirectories are counted inmainPackagesand never listed. A service made ofcmd/andinternal/haspackages: []and non-zero counts.- Skipped:
vendor/,testdata/,_and.directories, directories of nested modules (anothergo.modbelow the root),_test.gofiles,*_testpackages and files with//go:build ignore. Other build constraints are not applied; a symbol declared per platform appears once, the generic file winning.
goApi(files, options) is the importable-only list (includeInternal: false) without counts, as the third-party library index uses it. parseGoDoc(lines) splits a doc comment into doc and deprecated.
The scan reads gofmt-formatted source line by line and by brackets (mask blanks comments and strings first); unformatted code with several declarations on one line may be read incompletely.
Imports and modules
Section titled “Imports and modules”resolveGoImport(importPath, owning, modules): GoImportResolution says where an import of a file in module owning leads. It takes the longest module path that is a prefix at a / boundary:
- Modules of the repository (
owningandmodules: own, nested andgo.workmembers) give{ kind: 'local', module, subpath, dir }. - Otherwise the owning
go.mod’srequireandreplacepaths. Areplacewith a directory target giveslocal(withdirwhen it stays inside the repository); one with a module target gives{ kind: 'external', module, subpath, version: <target version>, required, replacedBy }; a plainrequiregives{ kind: 'external', module, subpath, version, indirect? }. A versionedreplaceapplies only when it names the required version. - An import whose first element has no dot is
{ kind: 'stdlib' }(isStdlibImport), checked after the repository’s modules so an own module path without a dot stays local. - Anything else is
{ kind: 'unresolved' }.
subpath is . for the module’s root package, else ./sub/pkg, so module path plus subpath rebuilds the import path. module keeps its /vN suffix. Since Go 1.17 the main module’s go.mod lists every module that provides an imported package, so the require version is the version built with.
Usages
Section titled “Usages”scanGoUsages(source, packageNames?): GoUsageScan returns the file’s packageName, its imports (parseGoImports: { path, alias?, name?, line, column, offset }) and its sites: { importPath, export, member?, kind, props?, line, column, offset }, positions 1-based and UTF-16, pointing at the start of pkg.Name (at the path for import sites).
| Code | Kind |
|---|---|
pkg.F(…), pkg.F[T](…), conversions pkg.T(x) |
call |
pkg.T{A: 1}, &pkg.T{…}, pkg.T[int]{…} (keys in props) |
new |
declarations, parameters, results, fields, *, [], map, chan, ... |
type |
type assertions x.(pkg.T), type switch cases, constraints [T pkg.C] |
type |
pkg.T alone on a struct or interface line |
extends |
type X = pkg.Y |
reexport |
pkg.V.X, pkg.T.M (member is X, M, or a .-joined chain) |
member |
anything else (if err == pkg.ErrX, arguments, <-pkg.Done) |
reference |
blank _ and dot . imports, named imports never referred to |
import |
The name a package is referred to by is its alias, else packageNames.get(path), else defaultPackageName(path) (last element, skipping /vN, without .vN, go- and -go). Names a dot import brings in are not resolved. Local names that shadow a package, methods called on values a package returned and type arguments of instantiations (List[pkg.T], read as reference) need type information and are out of reach. Standard library imports are scanned like any other; drop them with isStdlibImport.
Typed usages
Section titled “Typed usages”goTypedUsages({ dir, runner, runs, timeoutMs?, maxSites?, signal?, log? }): Promise<GoTypedOutcome> asks the Go type checker what the syntactic scan cannot see: fields and methods reached through values. c := canvas.New(); c.Draw(s) gives { file, line, column, importPath: '…/canvas', export: 'Canvas', member: 'Draw', kind: 'call' }; a field read or a method value is member. The export is the exported type declaring the member, or the innermost exported type on the selection path when an unexported embedded type declares it. Chains rooted at a package name (pkg.V.X, pkg.T.M) are left to scanGoUsages; types of the standard library and of the run’s own modules are left out. Positions are 1-based with UTF-16 columns, pointing at the member name, so they line up with scanGoUsages.
runs: GoTypedRun[]—{ dir, gowork?, patterns? }, paths relative to the checkout: a single module (GOWORK=off, patterns./...), or ago.workwith the member patterns (./api/...).- The helper lives in
helper/typedusages(main.goand ago.modwith no requirements, standard library only). It is not built ahead of time: each call copies it into a hidden.holtkeeper-typedusages-*folder of the checkout (so a container runner sees it too), runs it withgo run .throughrunner(GOTOOLCHAIN=local,GOWORK=off; the job’sGOFLAGSpass through) and deletes the folder. - The helper runs
go list -e -export -deps -test(CGO_ENABLED=0;-mod=modfor a single module whenGOFLAGSsets no-mod), so missing modules download through the job’s proxy andGOPRIVATEsettings and the build cache holds export data. It then parses every package of the run’s main modules,_test.gofiles and external test packages included, and type-checks it withgo/typesagainst that export data. Type errors are collected, not fatal. GoTypedOutcome { status, reason?, sites, packages, errors, truncated? }:skippedwhengo versionfails or there are no runs,failedwhen no run succeeded (reason: the first error), elseusedwith the sites of the runs that succeeded and up to 50errors(type errors, package errors and failed runs, prefixed by the run’sdir). Never throws except on abort.- Bounds (
goTypedDefaults):timeoutMs5 minutes over all runs (the helper stops itself; the runner’s timeout adds a minute for compiling),maxSites100 000, helper output 64 MiB.
goModuleTags(tags, modules): GoModuleTag[] maps git tags to the modules they release, following Go’s rules: vX.Y.Z releases the root module, dir/vX.Y.Z the module at dir; a module in a major-version directory (v2, dir/v3) takes tags without that directory. The tag’s major must match the module path (/vN paths only vN, other paths only v0 and v1). Tags that are not semantic versions or match no module are left out.