diff --git a/pkg/github/repositories.go b/pkg/github/repositories.go index b884f4888d..102b84c076 100644 --- a/pkg/github/repositories.go +++ b/pkg/github/repositories.go @@ -1767,10 +1767,11 @@ func PushFiles(t translations.TranslationHelperFunc) inventory.ServerTool { var baseCommit *github.Commit if !repositoryIsEmpty { if branchNotFound { - ref, err = createReferenceFromDefaultBranch(ctx, client, owner, repo, branch) + defaultRef, err := resolveDefaultBranch(ctx, client, owner, repo) if err != nil { return utils.NewToolResultError(fmt.Sprintf("failed to create branch from default: %v", err)), nil, nil } + ref = defaultRef } // Get the commit object that the branch points to @@ -1795,11 +1796,7 @@ func PushFiles(t translations.TranslationHelperFunc) inventory.ServerTool { defaultBranch := strings.TrimPrefix(*ref.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 - } + branchNotFound = true } baseCommit = base @@ -1836,27 +1833,50 @@ func PushFiles(t translations.TranslationHelperFunc) inventory.ServerTool { defer func() { _ = resp.Body.Close() }() } - // Update the reference to point to the new commit - ref.Object.SHA = newCommit.SHA - updatedRef, resp, err := client.Git.UpdateRef(ctx, owner, repo, *ref.Ref, github.UpdateRef{ - SHA: *newCommit.SHA, - Force: new(false), - }) - if err != nil { - return ghErrors.NewGitHubAPIErrorResponse(ctx, - "failed to update reference", - resp, - err, - ), nil, nil + var targetRef *github.Reference + if branchNotFound { + // Create the new branch reference directly at the new commit + createdRef, resp, err := client.Git.CreateRef(ctx, owner, repo, github.CreateRef{ + Ref: "refs/heads/" + branch, + SHA: *newCommit.SHA, + }) + if err != nil { + return ghErrors.NewGitHubAPIErrorResponse(ctx, + "failed to create new branch reference", + resp, + err, + ), nil, nil + } + if resp != nil && resp.Body != nil { + defer func() { _ = resp.Body.Close() }() + } + targetRef = createdRef + } else { + // Update the reference to point to the new commit + ref.Object.SHA = newCommit.SHA + updatedRef, resp, err := client.Git.UpdateRef(ctx, owner, repo, *ref.Ref, github.UpdateRef{ + SHA: *newCommit.SHA, + Force: new(false), + }) + if err != nil { + return ghErrors.NewGitHubAPIErrorResponse(ctx, + "failed to update reference", + resp, + err, + ), nil, nil + } + if resp != nil && resp.Body != nil { + defer func() { _ = resp.Body.Close() }() + } + targetRef = updatedRef } - defer func() { _ = resp.Body.Close() }() - r, err := json.Marshal(updatedRef) + r, err := json.Marshal(targetRef) if err != nil { return nil, nil, fmt.Errorf("failed to marshal response: %w", err) } - return utils.NewToolResultText(string(r)), repositoryReferenceOutput(updatedRef), nil + return utils.NewToolResultText(string(r)), repositoryReferenceOutput(targetRef), nil }, normalizePushFilesArguments, ) diff --git a/pkg/github/repositories_helper.go b/pkg/github/repositories_helper.go index fe1983252c..e326434e01 100644 --- a/pkg/github/repositories_helper.go +++ b/pkg/github/repositories_helper.go @@ -71,30 +71,6 @@ func initializeRepository(ctx context.Context, client *github.Client, owner, rep return ref, baseCommit, nil } -// createReferenceFromDefaultBranch creates a new branch reference from the repository's default branch -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 -} - const ( gitSymlinkMode = "120000" gitSubmoduleMode = "160000" diff --git a/pkg/github/repositories_test.go b/pkg/github/repositories_test.go index 9b40c932ff..949509a3ea 100644 --- a/pkg/github/repositories_test.go +++ b/pkg/github/repositories_test.go @@ -3038,6 +3038,14 @@ func Test_PushFiles(t *testing.T) { }, } + mockCreatedBranchRef := &github.Reference{ + Ref: new("refs/heads/new-branch"), + Object: &github.GitObject{ + SHA: new("jkl012"), + URL: new("https://api.github.com/repos/owner/repo/git/trees/jkl012"), + }, + } + // Define test cases tests := []struct { name string @@ -3679,6 +3687,193 @@ func Test_PushFiles(t *testing.T) { expectError: false, expectedErrMsg: "failed to initialize repository", }, + { + name: "successful push to new branch creates reference directly at new commit", + mockedClient: NewMockedHTTPClient( + // Get branch reference: 404 for new-branch, 200 for default branch main + WithRequestMatchHandler( + GetReposGitRefByOwnerByRepoByRef, + func(w http.ResponseWriter, r *http.Request) { + path := strings.ReplaceAll(r.URL.Path, "%2F", "/") + w.Header().Set("Content-Type", "application/json") + switch { + case strings.Contains(path, "heads/new-branch"): + w.WriteHeader(http.StatusNotFound) + _ = json.NewEncoder(w).Encode(map[string]any{"message": "Not Found"}) + case strings.Contains(path, "heads/main"): + w.WriteHeader(http.StatusOK) + _ = json.NewEncoder(w).Encode(mockRef) + default: + w.WriteHeader(http.StatusNotFound) + _ = json.NewEncoder(w).Encode(map[string]any{"message": "Not Found"}) + } + }, + ), + // Resolve default branch + WithRequestMatch( + GetReposByOwnerByRepo, + &github.Repository{ + DefaultBranch: new("main"), + }, + ), + // Get base commit from default branch + WithRequestMatch( + GetReposGitCommitsByOwnerByRepoByCommitSHA, + mockCommit, + ), + // Create tree + WithRequestMatch( + PostReposGitTreesByOwnerByRepo, + mockTree, + ), + // Create commit + WithRequestMatch( + PostReposGitCommitsByOwnerByRepo, + mockNewCommit, + ), + // Create reference directly at new commit + WithRequestMatchHandler( + PostReposGitRefsByOwnerByRepo, + expectRequestBody(t, map[string]any{ + "ref": "refs/heads/new-branch", + "sha": "jkl012", + }).andThen( + mockResponse(t, http.StatusCreated, mockCreatedBranchRef), + ), + ), + ), + requestArgs: map[string]any{ + "owner": "owner", + "repo": "repo", + "branch": "new-branch", + "files": []any{ + map[string]any{ + "path": "README.md", + "content": "# New branch README", + }, + }, + "message": "Push to new branch", + }, + expectError: false, + expectedRef: mockCreatedBranchRef, + }, + { + name: "fails to create tree on new branch does not create branch reference", + mockedClient: NewMockedHTTPClient( + // Get branch reference: 404 for new-branch, 200 for default branch main + WithRequestMatchHandler( + GetReposGitRefByOwnerByRepoByRef, + func(w http.ResponseWriter, r *http.Request) { + path := strings.ReplaceAll(r.URL.Path, "%2F", "/") + w.Header().Set("Content-Type", "application/json") + switch { + case strings.Contains(path, "heads/new-branch"): + w.WriteHeader(http.StatusNotFound) + _ = json.NewEncoder(w).Encode(map[string]any{"message": "Not Found"}) + case strings.Contains(path, "heads/main"): + w.WriteHeader(http.StatusOK) + _ = json.NewEncoder(w).Encode(mockRef) + default: + w.WriteHeader(http.StatusNotFound) + _ = json.NewEncoder(w).Encode(map[string]any{"message": "Not Found"}) + } + }, + ), + // Resolve default branch + WithRequestMatch( + GetReposByOwnerByRepo, + &github.Repository{ + DefaultBranch: new("main"), + }, + ), + // Get base commit from default branch + WithRequestMatch( + GetReposGitCommitsByOwnerByRepoByCommitSHA, + mockCommit, + ), + // Fail to create tree (e.g. malformed path component) + WithRequestMatchHandler( + PostReposGitTreesByOwnerByRepo, + mockResponse(t, http.StatusUnprocessableEntity, map[string]any{ + "message": "tree.path contains a malformed path component", + }), + ), + ), + requestArgs: map[string]any{ + "owner": "owner", + "repo": "repo", + "branch": "new-branch", + "files": []any{ + map[string]any{ + "path": ".git/config", + "content": "x", + }, + }, + "message": "Push with invalid path", + }, + expectError: true, + expectedErrMsg: "failed to create tree", + }, + { + name: "fails to create commit on new branch does not create branch reference", + mockedClient: NewMockedHTTPClient( + // Get branch reference: 404 for new-branch, 200 for default branch main + WithRequestMatchHandler( + GetReposGitRefByOwnerByRepoByRef, + func(w http.ResponseWriter, r *http.Request) { + path := strings.ReplaceAll(r.URL.Path, "%2F", "/") + w.Header().Set("Content-Type", "application/json") + switch { + case strings.Contains(path, "heads/new-branch"): + w.WriteHeader(http.StatusNotFound) + _ = json.NewEncoder(w).Encode(map[string]any{"message": "Not Found"}) + case strings.Contains(path, "heads/main"): + w.WriteHeader(http.StatusOK) + _ = json.NewEncoder(w).Encode(mockRef) + default: + w.WriteHeader(http.StatusNotFound) + _ = json.NewEncoder(w).Encode(map[string]any{"message": "Not Found"}) + } + }, + ), + // Resolve default branch + WithRequestMatch( + GetReposByOwnerByRepo, + &github.Repository{ + DefaultBranch: new("main"), + }, + ), + // Get base commit from default branch + WithRequestMatch( + GetReposGitCommitsByOwnerByRepoByCommitSHA, + mockCommit, + ), + // Create tree succeeds + WithRequestMatch( + PostReposGitTreesByOwnerByRepo, + mockTree, + ), + // Fail to create commit + WithRequestMatchHandler( + PostReposGitCommitsByOwnerByRepo, + mockResponse(t, http.StatusInternalServerError, nil), + ), + ), + requestArgs: map[string]any{ + "owner": "owner", + "repo": "repo", + "branch": "new-branch", + "files": []any{ + map[string]any{ + "path": "README.md", + "content": "# Test", + }, + }, + "message": "Push commit fail", + }, + expectError: true, + expectedErrMsg: "failed to create commit", + }, } for _, tc := range tests {