- Notifications
You must be signed in to change notification settings - Fork3.3k
Improvements to push_files tool#1676
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
Open
almaleksia wants to merge4 commits intomainChoose a base branch fromalmaleksia/push_files-improvements
base:main
Could not load branches
Branch not found:{{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline, and old review comments may become outdated.
+689 −43
Open
Changes fromall commits
Commits
Show all changes
4 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
Some comments aren't visible on the classic Files Changed page.
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 | ||
| @@ -1271,28 +1279,75 @@ func PushFiles(t translations.TranslationHelperFunc) inventory.ServerTool { | ||
| } | ||
| // Get the reference for the branch | ||
| var repositoryIsEmpty bool | ||
| var branchNotFound bool | ||
| ref, resp, err := client.Git.GetRef(ctx, owner, repo, "refs/heads/"+branch) | ||
| if err != nil { | ||
| ghErr, isGhErr := err.(*github.ErrorResponse) | ||
| if isGhErr { | ||
| if ghErr.Response.StatusCode == http.StatusConflict && ghErr.Message == "Git Repository is empty." { | ||
| repositoryIsEmpty = true | ||
| } else if ghErr.Response.StatusCode == http.StatusNotFound { | ||
| branchNotFound = true | ||
| } | ||
| } | ||
| if !repositoryIsEmpty && !branchNotFound { | ||
| return ghErrors.NewGitHubAPIErrorResponse(ctx, | ||
| "failed to get branch reference", | ||
| resp, | ||
| err, | ||
| ), nil, nil | ||
| } | ||
| } | ||
| // Only close resp if it's not nil and not an error case where resp might be nil | ||
| if resp != nil && resp.Body != nil { | ||
| defer func() { _ = resp.Body.Close() }() | ||
| } | ||
| var baseCommit *github.Commit | ||
| if !repositoryIsEmpty { | ||
| if branchNotFound { | ||
| ref, err = createReferenceFromDefaultBranch(ctx, client, owner, repo, branch) | ||
| if err != nil { | ||
| return utils.NewToolResultError(fmt.Sprintf("failed to create branch from default: %v", err)), nil, nil | ||
| } | ||
| } | ||
| // Get the commit object that the branch points to | ||
| baseCommit, resp, err = client.Git.GetCommit(ctx, owner, repo, *ref.Object.SHA) | ||
| if err != nil { | ||
| return ghErrors.NewGitHubAPIErrorResponse(ctx, | ||
| "failed to get base commit", | ||
| resp, | ||
| err, | ||
| ), nil, nil | ||
| } | ||
| if resp != nil && resp.Body != nil { | ||
| defer func() { _ = resp.Body.Close() }() | ||
| } | ||
| } else { | ||
| // Repository is empty, need to initialize it first | ||
| defaultRef, base, err := initializeRepository(ctx, client, owner, repo) | ||
| if err != nil { | ||
| return utils.NewToolResultError(fmt.Sprintf("failed to initialize repository: %v", err)), nil, nil | ||
| } | ||
| defaultBranch := strings.TrimPrefix(*defaultRef.Ref, "refs/heads/") | ||
| if branch != defaultBranch { | ||
| // Create the requested branch from the default branch | ||
| ref, err = createReferenceFromDefaultBranch(ctx, client, owner, repo, branch) | ||
| if err != nil { | ||
| return utils.NewToolResultError(fmt.Sprintf("failed to create branch from default: %v", err)), nil, nil | ||
| } | ||
| } else { | ||
| ref = defaultRef | ||
| } | ||
| baseCommit = base | ||
| } | ||
| // Create tree entries for all files (or remaining files if empty repo) | ||
| var entries []*github.TreeEntry | ||
| for _, file := range filesObj { | ||
| @@ -1320,7 +1375,7 @@ func PushFiles(t translations.TranslationHelperFunc) inventory.ServerTool { | ||
| }) | ||
| } | ||
| // Create a new tree with the file entries (baseCommit is now guaranteed to exist) | ||
| newTree, resp, err := client.Git.CreateTree(ctx, owner, repo, *baseCommit.Tree.SHA, entries) | ||
| if err != nil { | ||
| return ghErrors.NewGitHubAPIErrorResponse(ctx, | ||
| @@ -1329,9 +1384,11 @@ func PushFiles(t translations.TranslationHelperFunc) inventory.ServerTool { | ||
| err, | ||
| ), nil, nil | ||
| } | ||
| if resp != nil && resp.Body != nil { | ||
| defer func() { _ = resp.Body.Close() }() | ||
| } | ||
| // Create a new commit (baseCommit always has a value now) | ||
| commit := github.Commit{ | ||
| Message: github.Ptr(message), | ||
| Tree: newTree, | ||
| @@ -1345,7 +1402,9 @@ func PushFiles(t translations.TranslationHelperFunc) inventory.ServerTool { | ||
| err, | ||
| ), nil, nil | ||
| } | ||
| if resp != nil && resp.Body != nil { | ||
| defer func() { _ = resp.Body.Close() }() | ||
| } | ||
| // Update the reference to point to the new commit | ||
| ref.Object.SHA = newCommit.SHA | ||
| @@ -1372,6 +1431,80 @@ func PushFiles(t translations.TranslationHelperFunc) inventory.ServerTool { | ||
| ) | ||
| } | ||
| func initializeRepository(ctx context.Context, client *github.Client, owner, repo string) (ref *github.Reference, baseCommit *github.Commit, err error) { | ||
| // First, we need to check what's the default branch in this empty repo should be: | ||
| repository, resp, err := client.Repositories.Get(ctx, owner, repo) | ||
| if err != nil { | ||
| _, _ = ghErrors.NewGitHubAPIErrorToCtx(ctx, "failed to get repository", resp, err) | ||
| return nil, nil, fmt.Errorf("failed to get repository: %w", err) | ||
| } | ||
| if resp != nil && resp.Body != nil { | ||
| defer func() { _ = resp.Body.Close() }() | ||
| } | ||
| defaultBranch := repository.GetDefaultBranch() | ||
| fileOpts := &github.RepositoryContentFileOptions{ | ||
| Message: github.Ptr("Initial commit"), | ||
| Content: []byte(""), | ||
| Branch: github.Ptr(defaultBranch), | ||
| } | ||
| // Create an initial empty commit to create the default branch | ||
| createResp, resp, err := client.Repositories.CreateFile(ctx, owner, repo, "README.md", fileOpts) | ||
almaleksia marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
| if err != nil { | ||
| _, _ = ghErrors.NewGitHubAPIErrorToCtx(ctx, "failed to create initial file", resp, err) | ||
| return nil, nil, fmt.Errorf("failed to create initial file: %w", err) | ||
| } | ||
| if resp != nil && resp.Body != nil { | ||
| defer func() { _ = resp.Body.Close() }() | ||
| } | ||
| // Get the commit that was just created to use as base for remaining files | ||
| baseCommit, resp, err = client.Git.GetCommit(ctx, owner, repo, *createResp.Commit.SHA) | ||
| if err != nil { | ||
| _, _ = ghErrors.NewGitHubAPIErrorToCtx(ctx, "failed to get initial commit", resp, err) | ||
| return nil, nil, fmt.Errorf("failed to get initial commit: %w", err) | ||
| } | ||
| if resp != nil && resp.Body != nil { | ||
| defer func() { _ = resp.Body.Close() }() | ||
| } | ||
| ref, resp, err = client.Git.GetRef(ctx, owner, repo, "refs/heads/"+defaultBranch) | ||
| if err != nil { | ||
| _, _ = ghErrors.NewGitHubAPIErrorToCtx(ctx, "failed to get final reference", resp, err) | ||
| return nil, nil, fmt.Errorf("failed to get branch reference after initial commit: %w", err) | ||
| } | ||
| if resp != nil && resp.Body != nil { | ||
| defer func() { _ = resp.Body.Close() }() | ||
| } | ||
| return ref, baseCommit, nil | ||
| } | ||
| func createReferenceFromDefaultBranch(ctx context.Context, client *github.Client, owner, repo, branch string) (*github.Reference, error) { | ||
| defaultRef, err := resolveDefaultBranch(ctx, client, owner, repo) | ||
| if err != nil { | ||
| _, _ = ghErrors.NewGitHubAPIErrorToCtx(ctx, "failed to resolve default branch", nil, err) | ||
| return nil, fmt.Errorf("failed to resolve default branch: %w", err) | ||
| } | ||
| // Create the new branch reference | ||
| createdRef, resp, err := client.Git.CreateRef(ctx, owner, repo, github.CreateRef{ | ||
| Ref: "refs/heads/" + branch, | ||
| SHA: *defaultRef.Object.SHA, | ||
| }) | ||
| if err != nil { | ||
| _, _ = ghErrors.NewGitHubAPIErrorToCtx(ctx, "failed to create new branch reference", resp, err) | ||
| return nil, fmt.Errorf("failed to create new branch reference: %w", err) | ||
| } | ||
| if resp != nil && resp.Body != nil { | ||
| defer func() { _ = resp.Body.Close() }() | ||
| } | ||
| return createdRef, nil | ||
| } | ||
| // ListTags creates a tool to list tags in a GitHub repository. | ||
| func ListTags(t translations.TranslationHelperFunc) inventory.ServerTool { | ||
| return NewTool( | ||
| @@ -1876,15 +2009,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 +2026,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 +2061,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 +2089,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) | ||
| } | ||
| 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. | ||
Oops, something went wrong.
Uh oh!
There was an error while loading.Please reload this page.
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.