Skip to content

Commit

Permalink
refactor(GoMod): Use option -json with go list to get module names
Browse files Browse the repository at this point in the history
The `-json` option allows specifying a comma separated list of
property names to include in the output. The `go list` command has a
mechanism for skipping certain processing steps which are not needed
for computing the values corresponding to those specified property
names, see [^1],[^2] and [^3]. Such a mechanism is not in place for the
`-f` option.

Migrate from `-f` to `-json` to benefit from above mechanism, removing
potential sources of issues. It could be that this allows to drop the
parameter `-buildvcs=false`, which is left for future investigation.

The primary reason for switching to `-json` is to extend the mentioned
mechanism [^4] in `go list` to conditionally skip computing embed
files in an analog way which would fix [^5].

[^1]: https://github.com/golang/go/blob/0cd309e12818f988693bf8e4d9f1453331dcf9f2/src/cmd/go/internal/load/pkg.go#L2768-L2776
[^2]: https://github.com/golang/go/blob/0cd309e12818f988693bf8e4d9f1453331dcf9f2/src/cmd/go/internal/list/list.go#L605-L606
[^3]: golang/go#29666
[^4]: golang/go#49534 (comment)
[^5]: #5560

Signed-off-by: Frank Viernau <frank_viernau@epam.com>
  • Loading branch information
fviernau committed Feb 15, 2023
1 parent 50e4c24 commit 43ad3a7
Showing 1 changed file with 10 additions and 11 deletions.
21 changes: 10 additions & 11 deletions analyzer/src/main/kotlin/managers/GoMod.kt
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,11 @@ class GoMod(
val main: Boolean = false
)

private data class DepInfo(
@JsonProperty("Module")
val module: ModuleInfo? = null
)

private fun ModuleInfo.toId(): Identifier =
Identifier(
type = managerName.takeIf { version.isBlank() } ?: "Go",
Expand Down Expand Up @@ -273,20 +278,14 @@ class GoMod(
* Return the module names of all transitive main module dependencies. This excludes test-only dependencies.
*/
private fun getTransitiveMainModuleDependencies(projectDir: File): Set<String> {
val result = mutableSetOf<String>()

// See https://pkg.go.dev/text/template for the format syntax.
val list = run(
"list", "-deps", "-f", "{{with .Module}}{{.Path}} {{.Version}}{{end}}", "-buildvcs=false", "./...",
workingDir = projectDir
)
val list = run("list", "-deps", "-json=Module", "-buildvcs=false", "./...", workingDir = projectDir)

list.stdout.lines().forEach { line ->
val columns = line.splitOnWhitespace()
if (columns.size in 1..2) result += columns.first()
return jsonMapper.createParser(list.stdout).use { parser ->
jsonMapper.readValues<DepInfo>(parser).readAll()
}.mapNotNullTo(mutableSetOf()) { depInfo ->
depInfo.module?.path
}

return result
}

private fun ModuleInfo.toPackage(): Package {
Expand Down

0 comments on commit 43ad3a7

Please sign in to comment.