Skip to content

fix: 使用go mod graph 替代 go.mod 解析#16

Merged
kooksee merged 1 commit intomainfrom
feat/go_mod_graph
Jul 11, 2025
Merged

fix: 使用go mod graph 替代 go.mod 解析#16
kooksee merged 1 commit intomainfrom
feat/go_mod_graph

Conversation

@kooksee
Copy link
Copy Markdown
Contributor

@kooksee kooksee commented Jul 11, 2025

This pull request focuses on improving dependency version management and cleaning up imports across multiple files. The changes introduce a new method for determining the maximum version of dependencies using go mod graph, replace deprecated functions, and add missing imports. Additionally, a test file has been added to validate the new functionality.

Dependency Version Management Enhancements:

  • internal/modutil/util.go: Added a new LoadVersionGraph function to calculate the maximum version of each dependency using go mod graph. This replaces the previous LoadVersions function in some parts of the code. Also introduced a helper function maxVersion for determining the highest version from a list of versions. [1] [2]
  • cmd/protobuild/cmd.go: Updated the logic in Main() to use the new LoadVersionGraph function instead of LoadVersions. This ensures more accurate dependency version resolution.

Code Cleanup:

  • cmd/protobuild/cmd.go: Removed unused imports (github.com/samber/lo and golang.org/x/mod/module).
  • docs/docs.go: Added missing imports (github.com/samber/lo and golang.org/x/mod/module) to the docs package.

Testing:

  • internal/modutil/util_test.go: Added a new test file to validate the functionality of LoadVersionGraph and helper methods like maxVersion and minVersion. This ensures the correctness of dependency version management logic.

Function Replacement:

  • cmd/protobuild/cmd.go: Replaced the deprecated generic.DePtr function with generic.FromPtr for better readability and consistency.

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary of Changes

Hello @kooksee, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request refactors the dependency version resolution mechanism to use go mod graph instead of direct go.mod file parsing. This change aims to improve the accuracy and reliability of dependency version identification by leveraging Go's built-in module graph capabilities. It introduces new utility functions and external dependencies to support this new approach, along with minor code cleanup and a new test file for verification.

Highlights

  • Dependency Resolution Strategy Change: The core mechanism for resolving Go module dependency versions has been updated. Instead of directly parsing the go.mod file, the system now leverages the output of the go mod graph command. This change aims to provide a more accurate and robust way to determine the effective versions of dependencies, especially in scenarios involving complex module graphs or transitive dependencies.
  • New Module Graph Utility: A new function, LoadVersionGraph(), has been introduced in internal/modutil/util.go. This function is responsible for executing go mod graph, parsing its output, and identifying the highest resolved version for each module, which is then used throughout the application.
  • External Dependency Additions: Several new external libraries have been added to support the enhanced module version parsing and comparison logic. These include github.com/deckarep/golang-set/v2 for set operations, github.com/hashicorp/go-version for robust version parsing, and github.com/samber/lo for utility functions.
  • Import Relocation and Cleanup: Some _ (blank) imports, specifically github.com/samber/lo and golang.org/x/mod/module, were moved from cmd/protobuild/cmd.go to docs/docs.go. This is a common Go practice to ensure these modules are included in the go.mod file and available for go mod tidy without being directly used in the main application logic.
  • Minor Pointer Helper Refactoring: An update was made in cmd/protobuild/cmd.go to change the pointer dereferencing helper from generic.DePtr to generic.FromPtr when handling optional dependency versions.
  • New Test/Analysis File: A new test file, internal/modutil/util_test.go, has been added. It includes a TestName function that demonstrates and verifies the parsing of go mod graph output and the logic for selecting maximum (and minimum) module versions.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist is currently in preview and may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request refactors the logic for determining dependency versions by switching from parsing go.mod directly to using the output of go mod graph. The core logic in internal/modutil/util.go is sound, but there are areas for improvement, particularly around robustness and testing. The test file, internal/modutil/util_test.go, currently doesn't function as a valid test and needs to be rewritten. There's also a potential panic in the new LoadVersionGraph function that should be addressed.

Comment on lines +14 to +43
func TestName(t *testing.T) {
pretty.Println(LoadVersions())

modList := strings.Split(result.Wrap(shutil.GoModGraph()).Must(), "\n")
modSet := mapset.NewSet[string]()
for _, m := range modList {
for _, v := range strings.Split(m, " ") {
modSet.Add(strings.TrimSpace(v))
}
}

var modMap = make(map[string][]*ver.Version)
modSet.Each(func(s string) bool {
ver2 := strings.Split(s, "@")
if len(ver2) != 2 {
return false
}

if !strings.HasPrefix(ver2[1], "v") {
return false
}

modMap[ver2[0]] = append(modMap[ver2[0]], ver.Must(ver.NewSemver(ver2[1])))
return false
})

for k, v := range modMap {
pretty.Println(k, maxVersion(v).String(), minVersion(v).String())
}
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

The test function TestName has critical issues:

  1. It does not contain any assertions (e.g., t.Errorf, require.Equal) to verify behavior. It only prints values, so it can't detect regressions.
  2. It duplicates the implementation of LoadVersionGraph instead of calling it. Tests should treat the function under test as a black box.

Please refactor this to be a proper unit test. It should call LoadVersionGraph and assert its results against expected values. To make the test deterministic, consider mocking shutil.GoModGraph to return a fixed go mod graph output.

Comment on lines +47 to +59
modSet.Each(func(s string) bool {
ver2 := strings.Split(s, "@")
if len(ver2) != 2 {
return false
}

if !strings.HasPrefix(ver2[1], "v") {
return false
}

modMap[ver2[0]] = append(modMap[ver2[0]], ver.Must(ver.NewSemver(ver2[1])))
return false
})
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The use of ver.Must(...) can cause a panic if go mod graph provides a version string that cannot be parsed as a semantic version. Consider handling the error from ver.NewSemver gracefully, for example, by logging the error and skipping the invalid entry.

modSet.Each(func(s string) bool {
		ver2 := strings.Split(s, "@")
		if len(ver2) != 2 {
			return false
		}

		if !strings.HasPrefix(ver2[1], "v") {
			return false
		}

		v, err := ver.NewSemver(ver2[1])
		if err != nil {
			// Consider logging this error, e.g., slog.Warn("failed to parse version, skipping", "entry", s, "error", err)
			return false
		}

		modMap[ver2[0]] = append(modMap[ver2[0]], v)
		return false
	})

Comment on lines +45 to +47
func minVersion(versions []*ver.Version) *ver.Version {
return lo.MaxBy(versions, func(a *ver.Version, b *ver.Version) bool { return !a.GreaterThan(b) })
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The minVersion function is implemented using lo.MaxBy. While technically correct that using a <= comparison with MaxBy finds the minimum, this is confusing and unidiomatic. The lo library provides lo.MinBy, which should be used here for better readability and maintainability.

Suggested change
func minVersion(versions []*ver.Version) *ver.Version {
return lo.MaxBy(versions, func(a *ver.Version, b *ver.Version) bool { return !a.GreaterThan(b) })
}
func minVersion(versions []*ver.Version) *ver.Version {
return lo.MinBy(versions, func(a *ver.Version, b *ver.Version) bool { return a.LessThan(b) })
}

@kooksee kooksee merged commit 31640cb into main Jul 11, 2025
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant