From 5023a2eae8801ac7db186816c1f0afac2196c3bd Mon Sep 17 00:00:00 2001 From: Asubtlecoderrr Date: Thu, 19 Nov 2026 11:07:40 +0530 Subject: [PATCH 1/2] feat(push_files): use createCommitOnBranch GraphQL mutation for signed commits Replace the five-step REST Git Data API flow (GetCommit + CreateTree + CreateCommit + UpdateRef) in PushFiles with a single GraphQL createCommitOnBranch mutation. The motivation is enterprise GitHub organisations that enforce "require signed commits" branch protection rules. The REST Git Data API creates unsigned commits, which are rejected by that policy, making push_files completely unusable in those environments. The createCommitOnBranch GraphQL mutation produces web-flow signed commits, satisfying the policy without any special key management on the caller side. The change is fully backwards-compatible: the mutation works on repos whether or not the signed-commit requirement is enabled. Updated test suite: - Replaced tree/commit/updateref REST mocks with a GQL mutation mock - Added a "fails to create signed commit" error path test - Fixed TypedRepositoryOutputs GQL handler to dispatch by query type --- pkg/github/repositories.go | 106 ++---- pkg/github/repositories_test.go | 375 ++++++++------------ pkg/github/typed_repository_outputs_test.go | 10 +- 3 files changed, 198 insertions(+), 293 deletions(-) diff --git a/pkg/github/repositories.go b/pkg/github/repositories.go index b884f4888d..85e5f127d5 100644 --- a/pkg/github/repositories.go +++ b/pkg/github/repositories.go @@ -1710,7 +1710,9 @@ func PushFiles(t translations.TranslationHelperFunc) inventory.ServerTool { if input.Files == nil { return utils.NewToolResultError("files parameter must be an array of objects with path and content"), nil, nil } - entries := make([]*github.TreeEntry, 0, len(input.Files)) + + // Build GraphQL file additions with base64-encoded content. + additions := make([]githubv4.FileAddition, 0, len(input.Files)) for _, file := range input.Files { if file.Path == "" { return utils.NewToolResultError("each file must have a path"), nil, nil @@ -1722,13 +1724,9 @@ func PushFiles(t translations.TranslationHelperFunc) inventory.ServerTool { if file.Content == nil { return utils.NewToolResultError("each file must have content"), nil, nil } - content := *file.Content - - entries = append(entries, &github.TreeEntry{ - Path: new(filePath), - Mode: new("100644"), - Type: new("blob"), - Content: new(content), + additions = append(additions, githubv4.FileAddition{ + Path: githubv4.String(filePath), + Contents: githubv4.Base64String(base64.StdEncoding.EncodeToString([]byte(*file.Content))), }) } @@ -1764,7 +1762,6 @@ func PushFiles(t translations.TranslationHelperFunc) inventory.ServerTool { defer func() { _ = resp.Body.Close() }() } - var baseCommit *github.Commit if !repositoryIsEmpty { if branchNotFound { ref, err = createReferenceFromDefaultBranch(ctx, client, owner, repo, branch) @@ -1772,27 +1769,15 @@ func PushFiles(t translations.TranslationHelperFunc) inventory.ServerTool { 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 { - var base *github.Commit // Repository is empty, need to initialize it first - ref, base, err = initializeRepository(ctx, client, owner, repo) + var initRef *github.Reference + initRef, _, err = initializeRepository(ctx, client, owner, repo) if err != nil { return utils.NewToolResultError(fmt.Sprintf("failed to initialize repository: %v", err)), nil, nil } + ref = initRef defaultBranch := strings.TrimPrefix(*ref.Ref, "refs/heads/") if branch != defaultBranch { // Create the requested branch from the default branch @@ -1801,62 +1786,49 @@ func PushFiles(t translations.TranslationHelperFunc) inventory.ServerTool { return utils.NewToolResultError(fmt.Sprintf("failed to create branch from default: %v", err)), nil, nil } } - - baseCommit = base } - // 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) + // Create a signed commit using the GraphQL createCommitOnBranch mutation. + // This produces web-flow signed commits that satisfy enterprise "require signed commits" + // branch protection rules, unlike the REST Git Data API which creates unsigned commits. + gqlClient, err := deps.GetGQLClient(ctx) if err != nil { - return ghErrors.NewGitHubAPIErrorResponse(ctx, - "failed to create tree", - resp, - err, - ), nil, nil - } - if resp != nil && resp.Body != nil { - defer func() { _ = resp.Body.Close() }() + return utils.NewToolResultErrorFromErr("failed to get GitHub GraphQL client", err), nil, nil } - // Create a new commit (baseCommit always has a value now) - commit := github.Commit{ - Message: new(message), - Tree: newTree, - Parents: []*github.Commit{{SHA: baseCommit.SHA}}, - } - newCommit, resp, err := client.Git.CreateCommit(ctx, owner, repo, commit, nil) - if err != nil { - return ghErrors.NewGitHubAPIErrorResponse(ctx, - "failed to create commit", - resp, - err, - ), nil, nil - } - if resp != nil && resp.Body != nil { - defer func() { _ = resp.Body.Close() }() + nameWithOwner := githubv4.String(owner + "/" + repo) + branchName := githubv4.String(branch) + headOID := githubv4.GitObjectID(*ref.Object.SHA) + + var commitMutation struct { + CreateCommitOnBranch struct { + Commit struct { + OID githubv4.GitObjectID + } + } `graphql:"createCommitOnBranch(input: $input)"` } - // 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 err := gqlClient.Mutate(ctx, &commitMutation, githubv4.CreateCommitOnBranchInput{ + Branch: githubv4.CommittableBranch{ + RepositoryNameWithOwner: &nameWithOwner, + BranchName: &branchName, + }, + Message: githubv4.CommitMessage{Headline: githubv4.String(message)}, + ExpectedHeadOid: headOID, + FileChanges: &githubv4.FileChanges{Additions: &additions}, + }, nil); err != nil { + return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "failed to create signed commit", err), nil, nil } - defer func() { _ = resp.Body.Close() }() - r, err := json.Marshal(updatedRef) + commitSHA := string(commitMutation.CreateCommitOnBranch.Commit.OID) + ref.Object.SHA = &commitSHA + + r, err := json.Marshal(ref) 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(ref), nil }, normalizePushFilesArguments, ) diff --git a/pkg/github/repositories_test.go b/pkg/github/repositories_test.go index 9b40c932ff..76948df4fe 100644 --- a/pkg/github/repositories_test.go +++ b/pkg/github/repositories_test.go @@ -3013,39 +3013,38 @@ func Test_PushFiles(t *testing.T) { }, } - mockCommit := &github.Commit{ - SHA: new("abc123"), - Tree: &github.Tree{ - SHA: new("def456"), - }, - } - - mockTree := &github.Tree{ - SHA: new("ghi789"), - } - - mockNewCommit := &github.Commit{ - SHA: new("jkl012"), - Message: new("Update multiple files"), - HTMLURL: new("https://github.com/owner/repo/commit/jkl012"), - } - mockUpdatedRef := &github.Reference{ Ref: new("refs/heads/main"), Object: &github.GitObject{ SHA: new("jkl012"), - URL: new("https://api.github.com/repos/owner/repo/git/trees/jkl012"), }, } + // createCommitOnBranch mutation shape used in matchers. + type createCommitMutation struct { + CreateCommitOnBranch struct { + Commit struct { + OID githubv4.GitObjectID + } + } `graphql:"createCommitOnBranch(input: $input)"` + } + + // gqlSuccessResponse returns a standard createCommitOnBranch success response. + gqlSuccessResponse := githubv4mock.DataResponse(map[string]any{ + "createCommitOnBranch": map[string]any{ + "commit": map[string]any{"oid": "jkl012"}, + }, + }) + // Define test cases tests := []struct { - name string - mockedClient *http.Client - requestArgs map[string]any - expectError bool - expectedRef *github.Reference - expectedErrMsg string + name string + mockedClient *http.Client + mockedGQLClient *http.Client + requestArgs map[string]any + expectError bool + expectedRef *github.Reference + expectedErrMsg string }{ { name: "successful push of multiple files", @@ -3055,54 +3054,32 @@ func Test_PushFiles(t *testing.T) { GetReposGitRefByOwnerByRepoByRef, mockRef, ), - // Get commit - WithRequestMatch( - GetReposGitCommitsByOwnerByRepoByCommitSHA, - mockCommit, - ), - // Create tree - WithRequestMatchHandler( - PostReposGitTreesByOwnerByRepo, - expectRequestBody(t, map[string]any{ - "base_tree": "def456", - "tree": []any{ - map[string]any{ - "path": "README.md", - "mode": "100644", - "type": "blob", - "content": "# Updated README\n\nThis is an updated README file.", - }, - map[string]any{ - "path": "docs/example.md", - "mode": "100644", - "type": "blob", - "content": "# Example\n\nThis is an example file.", + ), + mockedGQLClient: githubv4mock.NewMockedHTTPClient( + githubv4mock.NewMutationMatcher( + createCommitMutation{}, + githubv4.CreateCommitOnBranchInput{ + Branch: githubv4.CommittableBranch{ + RepositoryNameWithOwner: githubv4.NewString("owner/repo"), + BranchName: githubv4.NewString("main"), + }, + Message: githubv4.CommitMessage{Headline: githubv4.String("Update multiple files")}, + ExpectedHeadOid: githubv4.GitObjectID("abc123"), + FileChanges: &githubv4.FileChanges{ + Additions: &[]githubv4.FileAddition{ + { + Path: githubv4.String("README.md"), + Contents: githubv4.Base64String(base64.StdEncoding.EncodeToString([]byte("# Updated README\n\nThis is an updated README file."))), + }, + { + Path: githubv4.String("docs/example.md"), + Contents: githubv4.Base64String(base64.StdEncoding.EncodeToString([]byte("# Example\n\nThis is an example file."))), + }, }, }, - }).andThen( - mockResponse(t, http.StatusCreated, mockTree), - ), - ), - // Create commit - WithRequestMatchHandler( - PostReposGitCommitsByOwnerByRepo, - expectRequestBody(t, map[string]any{ - "message": "Update multiple files", - "tree": "ghi789", - "parents": []any{"abc123"}, - }).andThen( - mockResponse(t, http.StatusCreated, mockNewCommit), - ), - ), - // Update reference - WithRequestMatchHandler( - PatchReposGitRefsByOwnerByRepoByRef, - expectRequestBody(t, map[string]any{ - "sha": "jkl012", - "force": false, - }).andThen( - mockResponse(t, http.StatusOK, mockUpdatedRef), - ), + }, + nil, + gqlSuccessResponse, ), ), requestArgs: map[string]any{ @@ -3125,10 +3102,9 @@ func Test_PushFiles(t *testing.T) { expectedRef: mockUpdatedRef, }, { - name: "fails when files parameter is invalid", - mockedClient: NewMockedHTTPClient( - // No requests expected - ), + name: "fails when files parameter is invalid", + mockedClient: NewMockedHTTPClient(), + mockedGQLClient: githubv4mock.NewMockedHTTPClient(), requestArgs: map[string]any{ "owner": "owner", "repo": "repo", @@ -3140,19 +3116,9 @@ func Test_PushFiles(t *testing.T) { expectedErrMsg: "files parameter must be an array", }, { - name: "fails when files contains object without path", - mockedClient: NewMockedHTTPClient( - // Get branch reference - WithRequestMatch( - GetReposGitRefByOwnerByRepoByRef, - mockRef, - ), - // Get commit - WithRequestMatch( - GetReposGitCommitsByOwnerByRepoByCommitSHA, - mockCommit, - ), - ), + name: "fails when files contains object without path", + mockedClient: NewMockedHTTPClient(), + mockedGQLClient: githubv4mock.NewMockedHTTPClient(), requestArgs: map[string]any{ "owner": "owner", "repo": "repo", @@ -3168,19 +3134,9 @@ func Test_PushFiles(t *testing.T) { expectedErrMsg: "each file must have a path", }, { - name: "fails when files contains object without content", - mockedClient: NewMockedHTTPClient( - // Get branch reference - WithRequestMatch( - GetReposGitRefByOwnerByRepoByRef, - mockRef, - ), - // Get commit - WithRequestMatch( - GetReposGitCommitsByOwnerByRepoByCommitSHA, - mockCommit, - ), - ), + name: "fails when files contains object without content", + mockedClient: NewMockedHTTPClient(), + mockedGQLClient: githubv4mock.NewMockedHTTPClient(), requestArgs: map[string]any{ "owner": "owner", "repo": "repo", @@ -3209,6 +3165,7 @@ func Test_PushFiles(t *testing.T) { mockResponse(t, http.StatusNotFound, nil), ), ), + mockedGQLClient: githubv4mock.NewMockedHTTPClient(), requestArgs: map[string]any{ "owner": "owner", "repo": "repo", @@ -3225,51 +3182,34 @@ func Test_PushFiles(t *testing.T) { expectedErrMsg: "failed to create branch from default", }, { - name: "fails to get base commit", + name: "fails to create signed commit", mockedClient: NewMockedHTTPClient( - // Get branch reference WithRequestMatch( GetReposGitRefByOwnerByRepoByRef, mockRef, ), - // Fail to get commit - WithRequestMatchHandler( - GetReposGitCommitsByOwnerByRepoByCommitSHA, - mockResponse(t, http.StatusNotFound, nil), - ), ), - requestArgs: map[string]any{ - "owner": "owner", - "repo": "repo", - "branch": "main", - "files": []any{ - map[string]any{ - "path": "README.md", - "content": "# README", + mockedGQLClient: githubv4mock.NewMockedHTTPClient( + githubv4mock.NewMutationMatcher( + createCommitMutation{}, + githubv4.CreateCommitOnBranchInput{ + Branch: githubv4.CommittableBranch{ + RepositoryNameWithOwner: githubv4.NewString("owner/repo"), + BranchName: githubv4.NewString("main"), + }, + Message: githubv4.CommitMessage{Headline: githubv4.String("Update file")}, + ExpectedHeadOid: githubv4.GitObjectID("abc123"), + FileChanges: &githubv4.FileChanges{ + Additions: &[]githubv4.FileAddition{ + { + Path: githubv4.String("README.md"), + Contents: githubv4.Base64String(base64.StdEncoding.EncodeToString([]byte("# README"))), + }, + }, + }, }, - }, - "message": "Update file", - }, - expectError: true, - expectedErrMsg: "failed to get base commit", - }, - { - name: "fails to create tree", - mockedClient: NewMockedHTTPClient( - // Get branch reference - WithRequestMatch( - GetReposGitRefByOwnerByRepoByRef, - mockRef, - ), - // Get commit - WithRequestMatch( - GetReposGitCommitsByOwnerByRepoByCommitSHA, - mockCommit, - ), - // Fail to create tree - WithRequestMatchHandler( - PostReposGitTreesByOwnerByRepo, - mockResponse(t, http.StatusInternalServerError, nil), + nil, + githubv4mock.ErrorResponse("push blocked: branch protection rule requires signed commits"), ), ), requestArgs: map[string]any{ @@ -3284,8 +3224,8 @@ func Test_PushFiles(t *testing.T) { }, "message": "Update file", }, - expectError: true, - expectedErrMsg: "failed to create tree", + expectError: false, + expectedErrMsg: "failed to create signed commit", }, { name: "successful push to empty repository", @@ -3337,25 +3277,36 @@ func Test_PushFiles(t *testing.T) { _, _ = w.Write(b) }), ), - // Get the commit after initialization + // initializeRepository calls GetCommit internally WithRequestMatch( GetReposGitCommitsByOwnerByRepoByCommitSHA, - mockCommit, - ), - // Create tree - WithRequestMatch( - PostReposGitTreesByOwnerByRepo, - mockTree, - ), - // Create commit - WithRequestMatch( - PostReposGitCommitsByOwnerByRepo, - mockNewCommit, + &github.Commit{ + SHA: new("abc123"), + Tree: &github.Tree{SHA: new("tree123")}, + }, ), - // Update reference - WithRequestMatch( - PatchReposGitRefsByOwnerByRepoByRef, - mockUpdatedRef, + ), + mockedGQLClient: githubv4mock.NewMockedHTTPClient( + githubv4mock.NewMutationMatcher( + createCommitMutation{}, + githubv4.CreateCommitOnBranchInput{ + Branch: githubv4.CommittableBranch{ + RepositoryNameWithOwner: githubv4.NewString("owner/repo"), + BranchName: githubv4.NewString("main"), + }, + Message: githubv4.CommitMessage{Headline: githubv4.String("Initial commit")}, + ExpectedHeadOid: githubv4.GitObjectID("abc123"), + FileChanges: &githubv4.FileChanges{ + Additions: &[]githubv4.FileAddition{ + { + Path: githubv4.String("README.md"), + Contents: githubv4.Base64String(base64.StdEncoding.EncodeToString([]byte("# Initial README\n\nFirst commit to empty repository."))), + }, + }, + }, + }, + nil, + gqlSuccessResponse, ), ), requestArgs: map[string]any{ @@ -3376,7 +3327,7 @@ func Test_PushFiles(t *testing.T) { { name: "successful push multiple files to empty repository", mockedClient: NewMockedHTTPClient( - // Get branch reference - called twice: first for empty check, second after file creation + // Get branch reference - called twice: first for empty check, second inside initializeRepository WithRequestMatchHandler( GetReposGitRefByOwnerByRepoByRef, func() http.HandlerFunc { @@ -3392,7 +3343,7 @@ func Test_PushFiles(t *testing.T) { } _ = json.NewEncoder(w).Encode(response) } else { - // Second call: returns the updated reference after first file creation + // Second call: returns the reference after initialization w.WriteHeader(http.StatusOK) b, _ := json.Marshal(&github.Reference{ Ref: new("refs/heads/main"), @@ -3419,87 +3370,59 @@ func Test_PushFiles(t *testing.T) { require.NoError(t, err) require.Equal(t, "Initial commit", body["message"]) require.Equal(t, "main", body["branch"]) - // Verify it's an empty file expectedContent := base64.StdEncoding.EncodeToString([]byte("")) require.Equal(t, expectedContent, body["content"]) w.WriteHeader(http.StatusCreated) response := &github.RepositoryContentResponse{ - Content: &github.RepositoryContent{ - SHA: new("readme123"), - }, SHA: new("init456"), - Tree: &github.Tree{ - SHA: new("tree456"), - }, } b, _ := json.Marshal(response) _, _ = w.Write(b) }), ), - // Get the commit to retrieve parent SHA + // initializeRepository calls GetCommit internally WithRequestMatchHandler( GetReposGitCommitsByOwnerByRepoByCommitSHA, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) response := &github.Commit{ - SHA: new("init456"), - Tree: &github.Tree{ - SHA: new("tree456"), - }, + SHA: new("init456"), + Tree: &github.Tree{SHA: new("tree456")}, } b, _ := json.Marshal(response) _, _ = w.Write(b) }), ), - // Create tree with all user files - WithRequestMatchHandler( - PostReposGitTreesByOwnerByRepo, - expectRequestBody(t, map[string]any{ - "base_tree": "tree456", - "tree": []any{ - map[string]any{ - "path": "README.md", - "mode": "100644", - "type": "blob", - "content": "# Project\n\nProject README", - }, - map[string]any{ - "path": ".gitignore", - "mode": "100644", - "type": "blob", - "content": "node_modules/\n*.log\n", - }, - map[string]any{ - "path": "src/main.js", - "mode": "100644", - "type": "blob", - "content": "console.log('Hello World');\n", + ), + mockedGQLClient: githubv4mock.NewMockedHTTPClient( + githubv4mock.NewMutationMatcher( + createCommitMutation{}, + githubv4.CreateCommitOnBranchInput{ + Branch: githubv4.CommittableBranch{ + RepositoryNameWithOwner: githubv4.NewString("owner/repo"), + BranchName: githubv4.NewString("main"), + }, + Message: githubv4.CommitMessage{Headline: githubv4.String("Initial project setup")}, + ExpectedHeadOid: githubv4.GitObjectID("init456"), + FileChanges: &githubv4.FileChanges{ + Additions: &[]githubv4.FileAddition{ + { + Path: githubv4.String("README.md"), + Contents: githubv4.Base64String(base64.StdEncoding.EncodeToString([]byte("# Project\n\nProject README"))), + }, + { + Path: githubv4.String(".gitignore"), + Contents: githubv4.Base64String(base64.StdEncoding.EncodeToString([]byte("node_modules/\n*.log\n"))), + }, + { + Path: githubv4.String("src/main.js"), + Contents: githubv4.Base64String(base64.StdEncoding.EncodeToString([]byte("console.log('Hello World');\n"))), + }, }, }, - }).andThen( - mockResponse(t, http.StatusCreated, mockTree), - ), - ), - // Create commit with all user files - WithRequestMatchHandler( - PostReposGitCommitsByOwnerByRepo, - expectRequestBody(t, map[string]any{ - "message": "Initial project setup", - "tree": "ghi789", - "parents": []any{"init456"}, - }).andThen( - mockResponse(t, http.StatusCreated, mockNewCommit), - ), - ), - // Update reference - WithRequestMatchHandler( - PatchReposGitRefsByOwnerByRepoByRef, - expectRequestBody(t, map[string]any{ - "sha": "jkl012", - "force": false, - }).andThen( - mockResponse(t, http.StatusOK, mockUpdatedRef), - ), + }, + nil, + gqlSuccessResponse, ), ), requestArgs: map[string]any{ @@ -3553,6 +3476,7 @@ func Test_PushFiles(t *testing.T) { mockResponse(t, http.StatusInternalServerError, nil), ), ), + mockedGQLClient: githubv4mock.NewMockedHTTPClient(), requestArgs: map[string]any{ "owner": "owner", "repo": "repo", @@ -3604,11 +3528,11 @@ func Test_PushFiles(t *testing.T) { WithRequestMatch( PutReposContentsByOwnerByRepoByPath, &github.RepositoryContentResponse{ - Content: &github.RepositoryContent{SHA: new("readme123")}, - SHA: new("init456"), + SHA: new("init456"), }, ), ), + mockedGQLClient: githubv4mock.NewMockedHTTPClient(), requestArgs: map[string]any{ "owner": "owner", "repo": "repo", @@ -3650,16 +3574,16 @@ func Test_PushFiles(t *testing.T) { WithRequestMatch( PutReposContentsByOwnerByRepoByPath, &github.RepositoryContentResponse{ - Content: &github.RepositoryContent{SHA: new("readme123")}, - SHA: new("init456"), + SHA: new("init456"), }, ), - // Fail to get commit + // Fail to get commit (inside initializeRepository) WithRequestMatchHandler( GetReposGitCommitsByOwnerByRepoByCommitSHA, mockResponse(t, http.StatusInternalServerError, nil), ), ), + mockedGQLClient: githubv4mock.NewMockedHTTPClient(), requestArgs: map[string]any{ "owner": "owner", "repo": "repo", @@ -3683,10 +3607,11 @@ func Test_PushFiles(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - // Setup client with mock - client := mustNewGHClient(t, tc.mockedClient) + restClient := mustNewGHClient(t, tc.mockedClient) + gqlClient := githubv4.NewClient(tc.mockedGQLClient) deps := BaseDeps{ - Client: client, + Client: restClient, + GQLClient: gqlClient, } handler := serverTool.Handler(deps) diff --git a/pkg/github/typed_repository_outputs_test.go b/pkg/github/typed_repository_outputs_test.go index 672837c711..890e6653a1 100644 --- a/pkg/github/typed_repository_outputs_test.go +++ b/pkg/github/typed_repository_outputs_test.go @@ -204,7 +204,15 @@ func typedRepositoryDeps(t *testing.T) BaseDeps { mockResponse(t, http.StatusOK, []*github.User{{Login: new("octo"), ID: new(int64(1)), RoleName: new("write")}})(w, r) }, } - gql := &http.Client{Transport: recorderTransport{handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + gql := &http.Client{Transport: recorderTransport{handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var req struct { + Query string `json:"query"` + } + _ = json.NewDecoder(r.Body).Decode(&req) + if strings.Contains(req.Query, "createCommitOnBranch") { + _, _ = w.Write([]byte(`{"data":{"createCommitOnBranch":{"commit":{"oid":"base"}}}}`)) + return + } _, _ = w.Write([]byte(`{"data":{"repository":{"defaultBranchRef":{"name":"main"},"object":{"__typename":"Commit","blame":{"ranges":[{"startingLine":1,"endingLine":3,"age":0,"commit":{"oid":"abc","message":"Message","committedDate":"2026-01-02T00:00:00Z","author":{"name":"Author","email":"author@example.com","user":null}}}]}}}}}`)) })}} return BaseDeps{ From 94afc48a3551a2b3d9fd0d5471cd8636c6d1cbb2 Mon Sep 17 00:00:00 2001 From: Asubtlecoderrr Date: Thu, 19 Nov 2026 11:42:25 +0530 Subject: [PATCH 2/2] fix: also update ref.Object.URL after createCommitOnBranch mutation The URL was still pointing at the previous commit after updating the SHA. Update it in-place so legacy clients following object.url get the new commit. --- pkg/github/repositories.go | 4 ++++ pkg/github/repositories_test.go | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/pkg/github/repositories.go b/pkg/github/repositories.go index 85e5f127d5..a698965e6e 100644 --- a/pkg/github/repositories.go +++ b/pkg/github/repositories.go @@ -1822,6 +1822,10 @@ func PushFiles(t translations.TranslationHelperFunc) inventory.ServerTool { commitSHA := string(commitMutation.CreateCommitOnBranch.Commit.OID) ref.Object.SHA = &commitSHA + if oldURL := ref.Object.GetURL(); strings.HasSuffix(oldURL, "/"+string(headOID)) { + updatedURL := strings.TrimSuffix(oldURL, string(headOID)) + commitSHA + ref.Object.URL = &updatedURL + } r, err := json.Marshal(ref) if err != nil { diff --git a/pkg/github/repositories_test.go b/pkg/github/repositories_test.go index 76948df4fe..07146e56ec 100644 --- a/pkg/github/repositories_test.go +++ b/pkg/github/repositories_test.go @@ -3017,6 +3017,7 @@ func Test_PushFiles(t *testing.T) { Ref: new("refs/heads/main"), Object: &github.GitObject{ SHA: new("jkl012"), + URL: new("https://api.github.com/repos/owner/repo/git/trees/jkl012"), }, } @@ -3651,6 +3652,9 @@ func Test_PushFiles(t *testing.T) { assert.Equal(t, *tc.expectedRef.Ref, *returnedRef.Ref) assert.Equal(t, *tc.expectedRef.Object.SHA, *returnedRef.Object.SHA) + if tc.expectedRef.Object.URL != nil && returnedRef.Object.URL != nil { + assert.Equal(t, *tc.expectedRef.Object.URL, *returnedRef.Object.URL) + } }) } }