- Notifications
You must be signed in to change notification settings - Fork3.3k
Fallback to default branch in get_file_contents when main doesn't exist#1669
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Merged
+142 −21
Merged
Changes fromall commits
Commits
Show all changes
3 commits Select commitHold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -671,6 +671,8 @@ func GetFileContents(t translations.TranslationHelperFunc) inventory.ServerTool | ||
| if err != nil { | ||
| return utils.NewToolResultError(err.Error()), nil, nil | ||
| } | ||
| originalRef := ref | ||
| sha, err := OptionalParam[string](args, "sha") | ||
| if err != nil { | ||
| return utils.NewToolResultError(err.Error()), nil, nil | ||
| @@ -681,7 +683,7 @@ func GetFileContents(t translations.TranslationHelperFunc) inventory.ServerTool | ||
| return utils.NewToolResultError("failed to get GitHub client"), nil, nil | ||
| } | ||
| rawOpts,fallbackUsed,err := resolveGitReference(ctx, client, owner, repo, ref, sha) | ||
| if err != nil { | ||
| return utils.NewToolResultError(fmt.Sprintf("failed to resolve git reference: %s", err)), nil, nil | ||
| } | ||
| @@ -747,6 +749,12 @@ func GetFileContents(t translations.TranslationHelperFunc) inventory.ServerTool | ||
| } | ||
| } | ||
| // main branch ref passed in ref parameter but it doesn't exist - default branch was used | ||
| var successNote string | ||
| if fallbackUsed { | ||
| successNote = fmt.Sprintf(" Note: the provided ref '%s' does not exist, default branch '%s' was used instead.", originalRef, rawOpts.Ref) | ||
| } | ||
| // Determine if content is text or binary | ||
| isTextContent := strings.HasPrefix(contentType, "text/") || | ||
| contentType == "application/json" || | ||
| @@ -762,9 +770,9 @@ func GetFileContents(t translations.TranslationHelperFunc) inventory.ServerTool | ||
| } | ||
| // Include SHA in the result metadata | ||
| if fileSHA != "" { | ||
| return utils.NewToolResultResource(fmt.Sprintf("successfully downloaded text file (SHA: %s)", fileSHA)+successNote, result), nil, nil | ||
| } | ||
| return utils.NewToolResultResource("successfully downloaded text file"+successNote, result), nil, nil | ||
| } | ||
| result := &mcp.ResourceContents{ | ||
| @@ -774,9 +782,9 @@ func GetFileContents(t translations.TranslationHelperFunc) inventory.ServerTool | ||
| } | ||
| // Include SHA in the result metadata | ||
| if fileSHA != "" { | ||
| return utils.NewToolResultResource(fmt.Sprintf("successfully downloaded binary file (SHA: %s)", fileSHA)+successNote, result), nil, nil | ||
| } | ||
| return utils.NewToolResultResource("successfully downloaded binary file"+successNote, result), nil, nil | ||
| } | ||
| // Raw API call failed | ||
| @@ -1876,15 +1884,15 @@ func looksLikeSHA(s string) bool { | ||
| // | ||
| // Any unexpected (non-404) errors during the resolution process are returned | ||
| // immediately. All API errors are logged with rich context to aid diagnostics. | ||
| func resolveGitReference(ctx context.Context, githubClient *github.Client, owner, repo, ref, sha string) (*raw.ContentOpts,bool,error) { | ||
| // 1) If SHA explicitly provided, it's the highest priority. | ||
| if sha != "" { | ||
| return &raw.ContentOpts{Ref: "", SHA: sha},false,nil | ||
| } | ||
| // 1a) If sha is empty but ref looks like a SHA, return it without changes | ||
| if looksLikeSHA(ref) { | ||
| return &raw.ContentOpts{Ref: "", SHA: ref},false,nil | ||
| } | ||
| originalRef := ref // Keep original ref for clearer error messages down the line. | ||
| @@ -1893,16 +1901,16 @@ func resolveGitReference(ctx context.Context, githubClient *github.Client, owner | ||
| var reference *github.Reference | ||
| var resp *github.Response | ||
| var err error | ||
| var fallbackUsed bool | ||
| switch { | ||
| case originalRef == "": | ||
| // 2a) If ref is empty, determine the default branch. | ||
| reference,err= resolveDefaultBranch(ctx, githubClient, owner, repo) | ||
| if err != nil { | ||
| return nil, false, err // Error is already wrapped in resolveDefaultBranch. | ||
| } | ||
| ref =reference.GetRef() | ||
| case strings.HasPrefix(originalRef, "refs/"): | ||
| // 2b) Already fully qualified. The reference will be fetched at the end. | ||
| case strings.HasPrefix(originalRef, "heads/") || strings.HasPrefix(originalRef, "tags/"): | ||
| @@ -1928,19 +1936,26 @@ func resolveGitReference(ctx context.Context, githubClient *github.Client, owner | ||
| ghErr2, isGhErr2 := err.(*github.ErrorResponse) | ||
| if isGhErr2 && ghErr2.Response.StatusCode == http.StatusNotFound { | ||
| if originalRef == "main" { | ||
| reference, err = resolveDefaultBranch(ctx, githubClient, owner, repo) | ||
| if err != nil { | ||
| return nil, false, err // Error is already wrapped in resolveDefaultBranch. | ||
| } | ||
| // Update ref to the actual default branch ref so the note can be generated | ||
| ref = reference.GetRef() | ||
| fallbackUsed = true | ||
| break | ||
| } | ||
| return nil,false,fmt.Errorf("could not resolve ref %q as a branch or a tag", originalRef) | ||
| } | ||
| // The tag lookup failed for a different reason. | ||
| _, _ = ghErrors.NewGitHubAPIErrorToCtx(ctx, "failed to get reference (tag)", resp, err) | ||
| return nil,false,fmt.Errorf("failed to get reference for tag '%s': %w", originalRef, err) | ||
| } | ||
| } else { | ||
| // The branch lookup failed for a different reason. | ||
| _, _ = ghErrors.NewGitHubAPIErrorToCtx(ctx, "failed to get reference (branch)", resp, err) | ||
| return nil,false,fmt.Errorf("failed to get reference for branch '%s': %w", originalRef, err) | ||
| } | ||
| } | ||
| } | ||
| @@ -1949,15 +1964,48 @@ func resolveGitReference(ctx context.Context, githubClient *github.Client, owner | ||
| reference, resp, err = githubClient.Git.GetRef(ctx, owner, repo, ref) | ||
| if err != nil { | ||
| if ref == "refs/heads/main" { | ||
| reference, err = resolveDefaultBranch(ctx, githubClient, owner, repo) | ||
| if err != nil { | ||
| return nil, false, err // Error is already wrapped in resolveDefaultBranch. | ||
| } | ||
| // Update ref to the actual default branch ref so the note can be generated | ||
| ref = reference.GetRef() | ||
| fallbackUsed = true | ||
| } else { | ||
| _, _ = ghErrors.NewGitHubAPIErrorToCtx(ctx, "failed to get final reference", resp, err) | ||
| return nil, false, fmt.Errorf("failed to get final reference for %q: %w", ref, err) | ||
| } | ||
| } | ||
| } | ||
| sha = reference.GetObject().GetSHA() | ||
| return &raw.ContentOpts{Ref: ref, SHA: sha}, fallbackUsed, nil | ||
| } | ||
| func resolveDefaultBranch(ctx context.Context, githubClient *github.Client, owner, repo string) (*github.Reference, error) { | ||
| repoInfo, resp, err := githubClient.Repositories.Get(ctx, owner, repo) | ||
| if err != nil { | ||
| _, _ = ghErrors.NewGitHubAPIErrorToCtx(ctx, "failed to get repository info", resp, err) | ||
| return nil, fmt.Errorf("failed to get repository info: %w", err) | ||
| } | ||
almaleksia marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
| if resp != nil && resp.Body != nil { | ||
| _ = resp.Body.Close() | ||
| } | ||
| defaultBranch := repoInfo.GetDefaultBranch() | ||
| defaultRef, resp, err := githubClient.Git.GetRef(ctx, owner, repo, "heads/"+defaultBranch) | ||
| if err != nil { | ||
| _, _ = ghErrors.NewGitHubAPIErrorToCtx(ctx, "failed to get default branch reference", resp, err) | ||
| return nil, fmt.Errorf("failed to get default branch reference: %w", err) | ||
| } | ||
| if resp != nil && resp.Body != nil { | ||
| defer func() { _ = resp.Body.Close() }() | ||
| } | ||
| return defaultRef, nil | ||
| } | ||
| // ListStarredRepositories creates a tool to list starred repositories for the authenticated user or a specified user. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.