Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 41 additions & 21 deletions pkg/github/repositories.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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,
)
Expand Down
24 changes: 0 additions & 24 deletions pkg/github/repositories_helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
195 changes: 195 additions & 0 deletions pkg/github/repositories_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down