Skip to content

Commit

Permalink
Merge pull request #577 from Homebrew/api-commit-and-push
Browse files Browse the repository at this point in the history
api-commit-and-push: add action
  • Loading branch information
Bo98 committed Sep 9, 2024
2 parents b436f63 + ced192b commit e7417aa
Show file tree
Hide file tree
Showing 5 changed files with 306 additions and 1 deletion.
23 changes: 23 additions & 0 deletions api-commit-and-push/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# API Commit and Push

An action that commits and pushes changes via the GitHub API rather than the git CLI.

Useful for GitHub Apps which need to use the API in order to sign commits.

## Usage

```yaml
- uses: actions/create-github-app-token@v1
id: app-token
with:
app-id: ${{ vars.APP_ID }}
private-key: ${{ secrets.PRIVATE_KEY }}

- run: git add some/file.txt

- uses: Homebrew/actions/api-commit-and-push@master
with:
message: Update generated files
branch: some-branch
token: ${{ steps.app-token.outputs.token }}
```
27 changes: 27 additions & 0 deletions api-commit-and-push/action.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
name: Commit and push via GitHub API
description: Commit and push changes to GitHub repository via GitHub API
author: Bo98
branding:
icon: git-commit
color: blue
inputs:
message:
description: Commit message
required: true
branch:
description: Branch to commit to
required: true
token:
description: GitHub token
required: true
directory:
description: Directory to the local repository clone. Changes to commit must have been staged (git add)
required: false
default: ${{ github.workspace }}
repository:
description: Repository to commit to
required: false
default: ${{ github.repository }}
runs:
using: node20
main: main.mjs
97 changes: 97 additions & 0 deletions api-commit-and-push/main.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import core from "@actions/core"
import exec from "@actions/exec"
import github from "@actions/github"
import fs from "node:fs/promises"
import path from "node:path"

async function main() {
const commitMessage = core.getInput("message")
const branch = core.getInput("branch")
const client = github.getOctokit(core.getInput("token"))
const directory = core.getInput("directory")
const [owner, repo] = core.getInput("repository").split("/")

const files = (
await exec.getExecOutput("git", ["-C", directory, "diff", "--no-ext-diff", "--cached", "--name-only", "-z"], { silent: true })
).stdout.split("\0").filter(file => file.length !== 0)
if (files.length === 0) {
core.setFailed("No files to commit")
return
}

const headCommitSha = (await exec.getExecOutput("git", ["-C", directory, "rev-parse", "HEAD"], { silent: true })).stdout.trim()
const headTreeSha = (await exec.getExecOutput("git", ["-C", directory, "rev-parse", "HEAD:"], { silent: true })).stdout.trim()

const tree = {}
for (const file of files) {
const absoluteFile = path.resolve(directory, file)

let content;
try {
content = await fs.readFile(absoluteFile, {encoding: "base64"})
} catch (error) {
if (error.code !== "ENOENT") throw error;

content = null;
}

if (content !== null) {
file.split("/").slice(0, -1).reduce((parentPath, component) => {
const treePath = path.posix.join(parentPath, component);

tree[treePath] ||= {
path: treePath,
mode: "040000",
type: "tree"
}

return treePath;
}, "")
}

tree[file] = {
path: file,
mode: "100644",
type: "blob",
}

if (content !== null) {
const blobResponse = await client.rest.git.createBlob({
owner: owner,
repo: repo,
content: await fs.readFile(absoluteFile, {encoding: "base64"}),
encoding: "base64"
})

tree[file].sha = blobResponse.data.sha
} else {
tree[file].sha = null
}
}

const treeResponse = await client.rest.git.createTree({
owner: owner,
repo: repo,
tree: Object.values(tree),
base_tree: headTreeSha
})

const commitResponse = await client.rest.git.createCommit({
owner: owner,
repo: repo,
message: commitMessage,
tree: treeResponse.data.sha,
parents: [headCommitSha]
})

await client.rest.git.updateRef({
owner: owner,
repo: repo,
ref: `heads/${branch}`,
sha: commitResponse.data.sha
})

core.info(`Pushed ${commitResponse.data.sha} to heads/${branch}`)
}

await main()
154 changes: 154 additions & 0 deletions api-commit-and-push/main.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
import exec from "@actions/exec"
import fs from "node:fs"
import os from "node:os"
import path from "node:path"
import util from "node:util"

describe("api-commit-and-push", async () => {
const token = "fake-token"
const branch = "a-branch"
const message = "Some message"
let directory
let baseCommitSha
let baseTreeSha

const blobSha = "abcdef1234567890abcdef1234567890abcdef12"
const treeSha = "abcdef1234567890abcdef1234567890abcdef13"
const commitSha = "abcdef1234567890abcdef1234567890abcdef14"
const addedFile = ".github/workflows/example.yml"
const removedFile = "someotherfile.rb"

before(async () => {
directory = await fs.promises.mkdtemp(path.join(os.tmpdir(), "api-commit-and-push-"))
console.log(directory)

// Setup test repository
await exec.exec("git", ["-C", directory, "init"])
await exec.exec("git", ["-C", directory, "config", "user.name", "github-actions[bot]"])
await exec.exec("git", ["-C", directory, "config", "user.email", "github-actions[bot]@users.noreply.github.com"])
await fs.promises.mkdir(path.join(directory, "somedir"))
await fs.promises.writeFile(path.join(directory, "somedir", "somefile.rb"), "test file 1")
await fs.promises.writeFile(path.join(directory, removedFile), "test file 2")
await exec.exec("git", ["-C", directory, "add", "-A"])
await exec.exec("git", ["-C", directory, "commit", "--no-gpg-sign", "-m", "Initial commit"])
await fs.promises.unlink(path.join(directory, removedFile))
await fs.promises.mkdir(path.join(directory, path.dirname(addedFile)), { recursive: true })
await fs.promises.writeFile(path.join(directory, addedFile), "test file 3")
await exec.exec("git", ["-C", directory, "add", "-A"])
baseCommitSha = (await exec.getExecOutput("git", ["-C", directory, "rev-parse", "HEAD"])).stdout.trim()
baseTreeSha = (await exec.getExecOutput("git", ["-C", directory, "rev-parse", "HEAD:"])).stdout.trim()
})

after(async () => {
await fs.promises.rm(directory, { recursive: true })
})

beforeEach(async () => {
mockInput("token", token)
mockInput("branch", branch)
mockInput("message", message)
mockInput("repository", GITHUB_REPOSITORY)
mockInput("directory", directory)
})

it("commits and pushes changes", async () => {
const mockPool = githubMockPool()

mockPool.intercept({
method: "POST",
path: `/repos/${GITHUB_REPOSITORY}/git/blobs`,
headers: {
Authorization: `token ${token}`,
},
body: (body) => util.isDeepStrictEqual(JSON.parse(body), {
content: fs.readFileSync(path.join(directory, addedFile), { encoding: "base64" }),
encoding: "base64",
}),
}).defaultReplyHeaders({
"Content-Type": "application/json",
}).reply(200, {
sha: blobSha,
})

const tree = []
addedFile.split("/").slice(0, -1).reduce((parentPath, component) => {
const treePath = path.posix.join(parentPath, component);

tree.push({
path: treePath,
mode: "040000",
type: "tree",
})

return treePath;
}, "")
tree.push(
{
path: addedFile,
mode: "100644",
type: "blob",
sha: blobSha,
},
{
path: removedFile,
mode: "100644",
type: "blob",
sha: null,
}
)

mockPool.intercept({
method: "POST",
path: `/repos/${GITHUB_REPOSITORY}/git/trees`,
headers: {
Authorization: `token ${token}`,
},
body: (body) => util.isDeepStrictEqual(JSON.parse(body), {
tree: tree,
base_tree: baseTreeSha,
}),
}).defaultReplyHeaders({
"Content-Type": "application/json",
}).reply(200, {
sha: treeSha,
})

mockPool.intercept({
method: "POST",
path: `/repos/${GITHUB_REPOSITORY}/git/commits`,
headers: {
Authorization: `token ${token}`,
},
body: (body) => util.isDeepStrictEqual(JSON.parse(body), {
message: message,
tree: treeSha,
parents: [baseCommitSha],
}),
}).defaultReplyHeaders({
"Content-Type": "application/json",
}).reply(200, {
sha: commitSha,
})

mockPool.intercept({
method: "PATCH",
path: `/repos/${GITHUB_REPOSITORY}/git/refs/heads%2F${branch}`,
headers: {
Authorization: `token ${token}`,
},
body: (body) => util.isDeepStrictEqual(JSON.parse(body), {
sha: commitSha
}),
}).defaultReplyHeaders({
"Content-Type": "application/json",
}).reply(200, {})

await loadMain()
})

it("aborts if no changes are found", async () => {
await exec.exec("git", ["-C", directory, "reset"])

await assert.rejects(loadMain, { message: "No files to commit" })
})
})
6 changes: 5 additions & 1 deletion spec-helper.mjs
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
/* node:coverage disable */
import assert from "node:assert/strict"
import { executionAsyncId } from "node:async_hooks"
import { createRequire } from "node:module"
import { test, beforeEach, afterEach, describe, it } from "node:test"
import { test, before, after, beforeEach, afterEach, describe, it } from "node:test"
import { MockAgent, setGlobalDispatcher } from "undici"
import core from "@actions/core"
import "esm-reload"

globalThis.test = test
globalThis.before = before
globalThis.after = after
globalThis.beforeEach = beforeEach
globalThis.afterEach = afterEach
globalThis.describe = describe
globalThis.it = it
globalThis.assert = assert
globalThis.mockInput = function(input, value) {
process.env[`INPUT_${input.replaceAll(" ", "_").toUpperCase()}`] = value
}
Expand Down

0 comments on commit e7417aa

Please sign in to comment.