|
| 1 | +# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). |
| 2 | +# Licensed under the Apache License, Version 2.0 (see LICENSE). |
| 3 | +import logging |
| 4 | +import textwrap |
| 5 | +from dataclasses import dataclass |
| 6 | +from typing import List, Optional, Tuple |
| 7 | + |
| 8 | +import ijson |
| 9 | + |
| 10 | +from pants.backend.go.distribution import GoLangDistribution |
| 11 | +from pants.backend.go.target_types import GoModuleSources |
| 12 | +from pants.build_graph.address import Address |
| 13 | +from pants.core.util_rules.external_tool import DownloadedExternalTool, ExternalToolRequest |
| 14 | +from pants.core.util_rules.source_files import SourceFiles, SourceFilesRequest |
| 15 | +from pants.engine.addresses import Addresses |
| 16 | +from pants.engine.fs import ( |
| 17 | + CreateDigest, |
| 18 | + Digest, |
| 19 | + DigestContents, |
| 20 | + FileContent, |
| 21 | + MergeDigests, |
| 22 | + RemovePrefix, |
| 23 | + Snapshot, |
| 24 | + Workspace, |
| 25 | +) |
| 26 | +from pants.engine.goal import Goal, GoalSubsystem |
| 27 | +from pants.engine.internals.selectors import Get |
| 28 | +from pants.engine.platform import Platform |
| 29 | +from pants.engine.process import BashBinary, Process, ProcessResult |
| 30 | +from pants.engine.rules import collect_rules, goal_rule, rule |
| 31 | +from pants.engine.target import UnexpandedTargets |
| 32 | +from pants.util.logging import LogLevel |
| 33 | +from pants.util.ordered_set import FrozenOrderedSet |
| 34 | + |
| 35 | +_logger = logging.getLogger(__name__) |
| 36 | + |
| 37 | + |
| 38 | +@dataclass(frozen=True) |
| 39 | +class ModuleDescriptor: |
| 40 | + import_path: str |
| 41 | + module_path: str |
| 42 | + module_version: str |
| 43 | + |
| 44 | + |
| 45 | +@dataclass(frozen=True) |
| 46 | +class ResolvedGoModule: |
| 47 | + import_path: str |
| 48 | + minimum_go_version: Optional[str] |
| 49 | + modules: FrozenOrderedSet[ModuleDescriptor] |
| 50 | + digest: Digest |
| 51 | + |
| 52 | + |
| 53 | +@dataclass(frozen=True) |
| 54 | +class ResolveGoModuleRequest: |
| 55 | + address: Address |
| 56 | + |
| 57 | + |
| 58 | +# Perform a minimal parsing of go.mod for the `module` and `go` directives. Full resolution of go.mod is left to |
| 59 | +# the go toolchain. This could also probably be replaced by a go shim to make use of: |
| 60 | +# https://pkg.go.dev/golang.org/x/mod/modfile |
| 61 | +# TODO: Add full path to expections for applicable go.mod. |
| 62 | +def basic_parse_go_mod(raw_text: bytes) -> Tuple[Optional[str], Optional[str]]: |
| 63 | + module_path = None |
| 64 | + minimum_go_version = None |
| 65 | + for line in raw_text.decode("utf-8").splitlines(): |
| 66 | + parts = line.strip().split() |
| 67 | + if len(parts) >= 2: |
| 68 | + if parts[0] == "module": |
| 69 | + if module_path is not None: |
| 70 | + raise ValueError("Multiple `module` directives found in go.mod file.") |
| 71 | + module_path = parts[1] |
| 72 | + elif parts[0] == "go": |
| 73 | + if minimum_go_version is not None: |
| 74 | + raise ValueError("Multiple `go` directives found in go.mod file.") |
| 75 | + minimum_go_version = parts[1] |
| 76 | + return module_path, minimum_go_version |
| 77 | + |
| 78 | + |
| 79 | +# Parse the output of `go mod download` into a list of module descriptors. |
| 80 | +def parse_module_descriptors(raw_json: bytes) -> List[ModuleDescriptor]: |
| 81 | + module_descriptors = [] |
| 82 | + for raw_module_descriptor in ijson.items(raw_json, "", multiple_values=True): |
| 83 | + module_descriptor = ModuleDescriptor( |
| 84 | + import_path=raw_module_descriptor["Path"], |
| 85 | + module_path=raw_module_descriptor["Path"], |
| 86 | + module_version=raw_module_descriptor["Version"], |
| 87 | + ) |
| 88 | + module_descriptors.append(module_descriptor) |
| 89 | + return module_descriptors |
| 90 | + |
| 91 | + |
| 92 | +@rule |
| 93 | +async def resolve_go_module( |
| 94 | + request: ResolveGoModuleRequest, |
| 95 | + goroot: GoLangDistribution, |
| 96 | + platform: Platform, |
| 97 | + bash: BashBinary, |
| 98 | +) -> ResolvedGoModule: |
| 99 | + downloaded_goroot = await Get( |
| 100 | + DownloadedExternalTool, |
| 101 | + ExternalToolRequest, |
| 102 | + goroot.get_request(platform), |
| 103 | + ) |
| 104 | + |
| 105 | + targets = await Get(UnexpandedTargets, Addresses([request.address])) |
| 106 | + if not targets: |
| 107 | + raise AssertionError(f"Address `{request.address}` did not resolve to any targets.") |
| 108 | + elif len(targets) > 1: |
| 109 | + raise AssertionError(f"Address `{request.address}` resolved to multiple targets.") |
| 110 | + target = targets[0] |
| 111 | + |
| 112 | + sources = await Get(SourceFiles, SourceFilesRequest([target.get(GoModuleSources)])) |
| 113 | + flattened_sources_snapshot = await Get( |
| 114 | + Snapshot, RemovePrefix(sources.snapshot.digest, request.address.spec_path) |
| 115 | + ) |
| 116 | + |
| 117 | + # Note: The `go` tool requires GOPATH to be an absolute path which can only be resolved from within the |
| 118 | + # execution sandbox. Thus, this code uses a bash script to be able to resolve that path. |
| 119 | + analyze_script_digest = await Get( |
| 120 | + Digest, |
| 121 | + CreateDigest( |
| 122 | + [ |
| 123 | + FileContent( |
| 124 | + "analyze.sh", |
| 125 | + textwrap.dedent( |
| 126 | + """\ |
| 127 | + export GOROOT="./go" |
| 128 | + export GOPATH="$(/bin/pwd)/gopath" |
| 129 | + export GOCACHE="$(/bin/pwd)/cache" |
| 130 | + mkdir -p "$GOPATH" "$GOCACHE" |
| 131 | + exec ./go/bin/go mod download -json all |
| 132 | + """ |
| 133 | + ).encode("utf-8"), |
| 134 | + ) |
| 135 | + ] |
| 136 | + ), |
| 137 | + ) |
| 138 | + |
| 139 | + input_root_digest = await Get( |
| 140 | + Digest, |
| 141 | + MergeDigests( |
| 142 | + [flattened_sources_snapshot.digest, downloaded_goroot.digest, analyze_script_digest] |
| 143 | + ), |
| 144 | + ) |
| 145 | + |
| 146 | + process = Process( |
| 147 | + argv=[bash.path, "./analyze.sh"], |
| 148 | + input_digest=input_root_digest, |
| 149 | + description="Resolve go_module metadata.", |
| 150 | + output_files=["go.mod", "go.sum"], |
| 151 | + level=LogLevel.DEBUG, |
| 152 | + ) |
| 153 | + |
| 154 | + result = await Get(ProcessResult, Process, process) |
| 155 | + |
| 156 | + # Parse the go.mod for the module path and minimum Go version. |
| 157 | + module_path = None |
| 158 | + minimum_go_version = None |
| 159 | + digest_contents = await Get(DigestContents, Digest, flattened_sources_snapshot.digest) |
| 160 | + for entry in digest_contents: |
| 161 | + if entry.path == "go.mod": |
| 162 | + module_path, minimum_go_version = basic_parse_go_mod(entry.content) |
| 163 | + |
| 164 | + if module_path is None: |
| 165 | + raise ValueError("No `module` directive found in go.mod.") |
| 166 | + |
| 167 | + return ResolvedGoModule( |
| 168 | + import_path=module_path, |
| 169 | + minimum_go_version=minimum_go_version, |
| 170 | + modules=FrozenOrderedSet(parse_module_descriptors(result.stdout)), |
| 171 | + digest=result.output_digest, |
| 172 | + ) |
| 173 | + |
| 174 | + |
| 175 | +# TODO: Add integration tests for the `go-resolve` goal once we figure out its final form. For now, it is a debug |
| 176 | +# tool to help update go.sum while developing the Go plugin and will probably change. |
| 177 | +class GoResolveSubsystem(GoalSubsystem): |
| 178 | + name = "go-resolve" |
| 179 | + help = "Resolve a Go module's go.mod and update go.sum accordingly." |
| 180 | + |
| 181 | + |
| 182 | +class GoResolveGoal(Goal): |
| 183 | + subsystem_cls = GoResolveSubsystem |
| 184 | + |
| 185 | + |
| 186 | +@goal_rule |
| 187 | +async def run_go_resolve(targets: UnexpandedTargets, workspace: Workspace) -> GoResolveGoal: |
| 188 | + # TODO: Use MultiGet to resolve the go_module targets. |
| 189 | + # TODO: Combine all of the go.sum's into a single Digest to write. |
| 190 | + for target in targets: |
| 191 | + if target.has_field(GoModuleSources) and not target.address.is_file_target: |
| 192 | + resolved_go_module = await Get(ResolvedGoModule, ResolveGoModuleRequest(target.address)) |
| 193 | + # TODO: Only update the files if they actually changed. |
| 194 | + workspace.write_digest(resolved_go_module.digest, path_prefix=target.address.spec_path) |
| 195 | + _logger.info(f"{target.address}: Updated go.mod and go.sum.\n") |
| 196 | + else: |
| 197 | + _logger.info(f"{target.address}: Skipping because target is not a `go_module`.\n") |
| 198 | + return GoResolveGoal(exit_code=0) |
| 199 | + |
| 200 | + |
| 201 | +def rules(): |
| 202 | + return collect_rules() |
0 commit comments