├── .gitignore ├── dist └── package.json ├── .editorconfig ├── .github ├── dependabot.yml └── workflows │ ├── build.yaml │ └── release.yaml ├── tsconfig.json ├── .eslintrc ├── action.yaml ├── package.json ├── LICENSE ├── local-run-sandbox.ts ├── README.md ├── lib ├── actions.ts ├── github.ts └── git.ts └── index.ts /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | node_modules 3 | -------------------------------------------------------------------------------- /dist/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "module" 3 | } 4 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | indent_style = space 6 | indent_size = 2 7 | insert_final_newline = true 8 | trim_trailing_whitespace = true 9 | 10 | ij_continuation_indent_size = 4 11 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "npm" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "weekly" 12 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/tsconfig", 3 | "compilerOptions": { 4 | "target": "ESNext", 5 | "module": "ESNext", 6 | "moduleResolution": "node", 7 | "esModuleInterop": true, 8 | "rootDir": "./", 9 | "baseUrl": "./", 10 | "sourceMap": true, 11 | "outDir": "./dist", 12 | "strict": true, 13 | "strictNullChecks": true, 14 | "forceConsistentCasingInFileNames": true, 15 | "noImplicitAny": true, 16 | "skipLibCheck": true 17 | }, 18 | "exclude": [ 19 | "./dist", 20 | "./node_modules", 21 | "./__tests__", 22 | "./coverage" 23 | ] 24 | } 25 | -------------------------------------------------------------------------------- /.github/workflows/build.yaml: -------------------------------------------------------------------------------- 1 | name: Build Action 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | 8 | jobs: 9 | build: 10 | runs-on: ubuntu-latest 11 | permissions: 12 | contents: write 13 | steps: 14 | - uses: actions/checkout@v4 15 | - uses: qoomon/actions--setup-git-user@v1 16 | 17 | # build the action 18 | - uses: actions/setup-node@v4 19 | with: 20 | node-version: '20' 21 | cache: 'npm' 22 | - run: npm ci 23 | - run: npm run build 24 | 25 | # commit and push build output 26 | - run: | 27 | git add -f dist/ 28 | git commit -m 'chore: build action' || true 29 | git push 30 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "parser": "@typescript-eslint/parser", 3 | "plugins": ["@typescript-eslint"], 4 | "extends": [ 5 | "eslint:recommended", 6 | "plugin:@typescript-eslint/recommended", 7 | "plugin:@typescript-eslint/eslint-recommended", 8 | "plugin:node/recommended", 9 | "google", 10 | "plugin:require-extensions/recommended" 11 | ], 12 | "root": true, 13 | "rules": { 14 | "semi": ["error", "never"], 15 | "max-len": ["error", {"code": 120, "ignoreComments": true}], 16 | "valid-jsdoc": ["error", {"requireParamType": false, "requireReturnType": false}], 17 | "node/no-missing-import": "off", 18 | "node/no-extraneous-import": "off" 19 | }, 20 | "ignorePatterns": ["dist/**"] 21 | } 22 | -------------------------------------------------------------------------------- /action.yaml: -------------------------------------------------------------------------------- 1 | name: 'Create GitHub Commit' 2 | description: 'Create Commit' 3 | author: 'qoomon' 4 | branding: 5 | icon: git-commit 6 | color: blue 7 | 8 | inputs: 9 | message: 10 | description: 'The commit message' 11 | required: true 12 | amend: 13 | description: 'Amend the last commit' 14 | default: 'false' 15 | allow-empty: 16 | description: 'Allow an empty commit' 17 | default: 'false' 18 | skip-empty: 19 | description: 'Skip action, if nothing to commit' 20 | default: 'false' 21 | 22 | token: 23 | description: 'A GitHub access token' 24 | required: true 25 | default: ${{ github.token }} 26 | working-directory: 27 | description: 'The working directory' 28 | required: true 29 | default: '.' 30 | remoteName: 31 | description: 'The remote name to create the commit at.' 32 | required: true 33 | default: 'origin' 34 | 35 | outputs: 36 | commit: 37 | description: 'The commit hash, if a commit was created' 38 | 39 | runs: 40 | using: 'node20' 41 | main: 'dist/index.js' 42 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "module", 3 | "main": "dist/index.js", 4 | "scripts": { 5 | "build": "ncc build index.ts", 6 | "lint": "eslint .", 7 | "test": "NODE_OPTIONS='--experimental-vm-modules --no-warnings' jest --forceExit --detectOpenHandles", 8 | "ts-node": "NODE_OPTIONS='--require ts-node/register --loader ts-node/esm' node" 9 | }, 10 | "dependencies": { 11 | "@actions/core": "^1.11.1", 12 | "@actions/exec": "^1.1.1", 13 | "@actions/github": "^6.0.0" 14 | }, 15 | "devDependencies": { 16 | "@eslint/js": "^8.56.0", 17 | "@types/node": "^20.11.7", 18 | "@typescript-eslint/eslint-plugin": "^8.39.1", 19 | "@typescript-eslint/parser": "^8.32.0", 20 | "@vercel/ncc": "^0.38.3", 21 | "eslint": "^8.56.0", 22 | "eslint-config-google": "^0.14.0", 23 | "eslint-config-standard": "^17.1.0", 24 | "eslint-plugin-node": "^11.1.0", 25 | "eslint-plugin-require-extensions": "^0.1.3", 26 | "typescript": "^5.8.3", 27 | "ts-node": "^10.9.2" 28 | }, 29 | "engines": { 30 | "node": ">=20.0.0" 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Bengt Brodersen 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.github/workflows/release.yaml: -------------------------------------------------------------------------------- 1 | name: Release Action 2 | 3 | on: 4 | workflow_dispatch: 5 | inputs: 6 | ref: 7 | description: 'Ref' 8 | required: true 9 | default: 'main' 10 | version: 11 | description: 'Version' 12 | required: true 13 | 14 | jobs: 15 | release: 16 | permissions: 17 | contents: write 18 | runs-on: ubuntu-latest 19 | steps: 20 | - uses: actions/checkout@v4 21 | with: 22 | ref: ${{ inputs.ref }} 23 | 24 | - name: Create Release 25 | uses: actions/github-script@v7 26 | env: 27 | INPUT_REF: ${{ inputs.ref }} 28 | INPUT_VERSION: ${{ inputs.version }} 29 | with: 30 | script: | 31 | await github.rest.repos.createRelease({ 32 | owner: context.repo.owner, 33 | repo: context.repo.repo, 34 | tag_name: 'v' + core.getInput('version'), 35 | target_commitish: core.getInput('ref'), 36 | }) 37 | 38 | - name: Move Major Version Tag 39 | env: 40 | INPUT_VERSION: ${{ inputs.version }} 41 | run: | 42 | # move the major version tag e.g. v1 43 | MAJOR_INPUT_VERSION="${INPUT_VERSION%%.*}" 44 | MAJOR_VERSION_TAG="v${MAJOR_INPUT_VERSION}" 45 | git tag --force "${MAJOR_VERSION_TAG}" 46 | git push --force origin "${MAJOR_VERSION_TAG}" 47 | -------------------------------------------------------------------------------- /local-run-sandbox.ts: -------------------------------------------------------------------------------- 1 | import * as process from 'process' 2 | import {exec} from './lib/actions.js' 3 | import {action} from './index.js' 4 | 5 | const actionDir = process.cwd() 6 | console.log('actionDir', actionDir) 7 | process.chdir('/tmp/uKbOisIc7J/sandbox') 8 | 9 | // Prepare the repository 10 | await exec('git reset --hard origin/master') 11 | for (let i = 0; i < 100; i++) { 12 | await exec(`sh -c "date > dummy${i}.txt"`) 13 | await exec(`git add dummy${i}.txt`) 14 | } 15 | 16 | // await exec('sh -c "curl https://raster.shields.io/badge/date-$(date | tr \' \' \'_\')-blue > dummy.png') 17 | // await exec('git add dummy.png') 18 | 19 | // --------------------------------------------------------------------------------------------------------------------- 20 | 21 | // Set action input environment variables 22 | setActionInputs({ 23 | // 'skip-empty': 'true', 24 | 'allow-empty': 'true', 25 | 'message': 'work work', 26 | 'token': process.env['GITHUB_TOKEN']!, 27 | }) 28 | 29 | // Run the action 30 | action() 31 | 32 | // --------------------------------------------------------------------------------------------------------------------- 33 | 34 | /** 35 | * Set action input environment variables 36 | * @param inputs - input values 37 | * @returns void 38 | */ 39 | function setActionInputs(inputs: Record) { 40 | Object.entries(inputs).forEach(([name, value]) => { 41 | process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] = value 42 | }) 43 | } 44 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Create Commit   [![starline](https://starlines.qoo.monster/assets/qoomon/actions--create-commit)](https://github.com/qoomon/starline) 2 | [![Actions](https://img.shields.io/badge/qoomon-GitHub%20Actions-blue)](https://github.com/qoomon/actions) 3 | 4 | This action will create a new commit via GitHub API, committer and author are related to given token identity. 5 | Commits getting signed, if a GitHub App token (`ghs_***`) is used and will be marked as `verified` in the GitHub web interface. 6 | 7 | ### Example 8 | 9 | ```yaml 10 | jobs: 11 | example: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v4 15 | with: 16 | ref: ${{ github.ref }} 17 | - run: | 18 | date > dummy.txt 19 | git add dummy.txt 20 | 21 | - uses: qoomon/actions--create-commit@v1 22 | id: commit 23 | with: 24 | message: work work 25 | skip-empty: true 26 | 27 | - run: git push 28 | ``` 29 | 30 | ### Inputs 31 | 32 | ```yaml 33 | inputs: 34 | message: 35 | description: 'The commit message' 36 | required: true 37 | amend: 38 | description: 'Amend the last commit' 39 | default: false 40 | allow-empty: 41 | description: 'Allow an empty commit' 42 | default: false 43 | skip-empty: 44 | description: 'Skip action, if nothing to commit' 45 | default: false 46 | 47 | token: 48 | description: 'A GitHub access token' 49 | required: true 50 | default: ${{ github.token }} 51 | working-directory: 52 | description: 'The working directory' 53 | required: true 54 | default: '.' 55 | remoteName: 56 | description: 'The remote name to create the commit at.' 57 | required: true 58 | default: 'origin' 59 | ``` 60 | 61 | ### Outputs 62 | 63 | ```yaml 64 | outputs: 65 | commit: 66 | description: 'The commit hash, if a commit was created' 67 | ``` 68 | 69 | ## Development 70 | 71 | ### Release New Action Version 72 | 73 | Trigger [Release Version workflow](/actions/workflows/action-release.yaml) 74 | -------------------------------------------------------------------------------- /lib/actions.ts: -------------------------------------------------------------------------------- 1 | import * as core from '@actions/core' 2 | import {InputOptions} from '@actions/core' 3 | import {HttpClientError} from '@actions/http-client' 4 | import * as _exec from '@actions/exec' 5 | import {ExecOptions} from '@actions/exec' 6 | 7 | export const bot = { 8 | name: 'github-actions[bot]', 9 | email: '41898282+github-actions[bot]@users.noreply.github.com', 10 | } as const 11 | 12 | /** 13 | * Run action and catch errors 14 | * @param action - action to run 15 | * @returns void 16 | */ 17 | export function run(action: () => Promise): void { 18 | action().catch(async (error: unknown) => { 19 | core.setFailed('Unhandled error, see job logs') 20 | console.error('Error:', error) 21 | if (error instanceof HttpClientError) { 22 | console.error('Http response:', error.result) 23 | } 24 | }) 25 | } 26 | 27 | /** 28 | * Gets string value of an input. 29 | * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed. 30 | * Returns null if the value is not defined. 31 | * 32 | * @param name name of the input to get 33 | * @param options optional. See InputOptions. 34 | * @returns parsed input as object 35 | */ 36 | export function getInput(name: string, options?: InputOptions): string | null { 37 | return core.getInput(name, options) || null 38 | } 39 | 40 | /** 41 | * Execute a command and get the output. 42 | * @param commandLine - command to execute (can include additional args). Must be correctly escaped. 43 | * @param args - optional command arguments. 44 | * @param options - optional exec options. See ExecOptions 45 | * @returns status, stdout and stderr 46 | */ 47 | export async function exec(commandLine: string, args?: string[], options?: ExecOptions): Promise { 48 | const stdoutChunks = [] as Uint8Array[] 49 | const stderrChunks = [] as Uint8Array[] 50 | const status = await _exec.exec(commandLine, args, { 51 | ...options, 52 | listeners: { 53 | stdout(data) { 54 | stdoutChunks.push(new Uint8Array(data.buffer, data.byteOffset, data.byteLength)) 55 | }, 56 | stderr(data) { 57 | stderrChunks.push(new Uint8Array(data.buffer, data.byteOffset, data.byteLength)) 58 | }, 59 | }, 60 | }) 61 | 62 | return { 63 | status, 64 | stdout: Buffer.concat(stdoutChunks), 65 | stderr: Buffer.concat(stderrChunks), 66 | } 67 | } 68 | 69 | export type ExecResult = { 70 | status: number 71 | stdout: Buffer 72 | stderr: Buffer 73 | } 74 | -------------------------------------------------------------------------------- /index.ts: -------------------------------------------------------------------------------- 1 | import * as core from '@actions/core' 2 | import * as github from '@actions/github' 3 | // see https://github.com/actions/toolkit for more github actions libraries 4 | import {bot, exec, getInput, run} from './lib/actions.js' 5 | import {getCacheDetails, getCommitDetails, getRemoteUrl, readFile} from './lib/git.js' 6 | import {createCommit, parseRepositoryFromUrl} from './lib/github.js' 7 | 8 | export const action = () => run(async () => { 9 | const input = { 10 | token: getInput('token', {required: true})!, 11 | workingDirectory: getInput('working-directory') ?? '.', 12 | remoteName: getInput('remoteName') ?? 'origin', 13 | message: getInput('message', {required: true})!, 14 | amend: getInput('amend') === 'true', 15 | allowEmpty: getInput('allow-empty') === 'true', 16 | skipEmpty: getInput('skip-empty') === 'true', 17 | } 18 | 19 | process.chdir(input.workingDirectory) 20 | 21 | core.setOutput('commit', null) 22 | 23 | const cacheDetails = await getCacheDetails() 24 | console.log('cacheDetails', cacheDetails) 25 | if (cacheDetails.files.length === 0) { 26 | if (input.skipEmpty) { 27 | core.info('nothing to commit, working tree clean') 28 | return 29 | } else if (!input.allowEmpty) { 30 | core.setFailed('nothing to commit, working tree clean') 31 | return 32 | } 33 | } 34 | 35 | const commitArgs = [ 36 | '--message', input.message, 37 | ] 38 | if (input.amend) commitArgs.push('--amend') 39 | if (input.allowEmpty) commitArgs.push('--allow-empty') 40 | await exec('git', [ 41 | '-c', `user.name=${bot.name}`, 42 | '-c', `user.email=${bot.email}`, 43 | 'commit', ...commitArgs, 44 | ]) 45 | 46 | const octokit = github.getOctokit(input.token) 47 | const headCommit = await getCommitDetails('HEAD') 48 | const repositoryRemoteUrl = await getRemoteUrl(input.remoteName) 49 | const repository = parseRepositoryFromUrl(repositoryRemoteUrl) 50 | const githubCommit = await createCommit(octokit, repository, { 51 | subject: headCommit.subject, 52 | body: headCommit.body, 53 | tree: headCommit.tree, 54 | parents: headCommit.parents, 55 | files: headCommit.files.map((file) => ({ 56 | path: file.path, 57 | mode: file.mode, 58 | status: file.status, 59 | loadContent: async () => readFile(file.path, headCommit.sha), 60 | })), 61 | }) 62 | 63 | core.info('Syncing local repository ...') 64 | await exec('git fetch', [input.remoteName, githubCommit.sha]) 65 | await exec('git reset', [githubCommit.sha]) 66 | 67 | core.setOutput('commit', githubCommit.sha) 68 | }) 69 | 70 | if (import.meta.url === `file://${process.argv[1]}`) { 71 | action() 72 | } 73 | -------------------------------------------------------------------------------- /lib/github.ts: -------------------------------------------------------------------------------- 1 | import * as github from '@actions/github' 2 | import pLimit from 'p-limit' 3 | 4 | const octokitLimit = pLimit(10) 5 | 6 | /** 7 | * Create a commit authored and committed by octokit token identity. 8 | * In case of octokit token identity is a GitHub App the commit will be signed as well. 9 | * @param octokit - GitHub client 10 | * @param repository - target repository 11 | * @param args - commit details and file content reader 12 | * @returns created commit 13 | */ 14 | export async function createCommit(octokit: ReturnType, repository: { 15 | owner: string, 16 | repo: string 17 | }, args: CreateCommitArgs) { 18 | console.debug('creating commit ...') 19 | 20 | let commitTreeSha = args.tree 21 | if (args.files.length > 0) { 22 | console.debug(' creating commit tree ...') 23 | 24 | console.debug(' creating file blobs ...') 25 | const commitTreeBlobs = await Promise.all(args.files.map(async ({path, mode, status, loadContent}) => { 26 | switch (status) { 27 | case 'A': 28 | case 'M': { 29 | console.debug(' ', path, '...') 30 | const content = await loadContent() 31 | const blob = await octokitLimit(() => octokit.rest.git.createBlob({ 32 | ...repository, 33 | content: content.toString('base64'), 34 | encoding: 'base64', 35 | })).then(({data}) => data) 36 | console.debug(' ', path, '->', blob.sha) 37 | return { 38 | path, 39 | mode, 40 | sha: blob.sha, 41 | type: 'blob', 42 | } 43 | } 44 | case 'D': 45 | return { 46 | path, 47 | mode: '100644', 48 | sha: null, 49 | type: 'blob', 50 | } satisfies TreeFile 51 | default: 52 | throw new Error(`Unexpected file status: ${status}`) 53 | } 54 | })) 55 | 56 | commitTreeSha = await octokit.rest.git.createTree({ 57 | ...repository, 58 | base_tree: args.parents[0], 59 | tree: commitTreeBlobs, 60 | }).then(({data}) => data.sha) 61 | console.debug(' commit tree', '->', commitTreeSha) 62 | } 63 | 64 | const commit = await octokit.rest.git.createCommit({ 65 | ...repository, 66 | parents: args.parents, 67 | tree: commitTreeSha, 68 | message: args.subject + '\n\n' + args.body, 69 | 70 | // DO NOT set author or committer otherwise commit will not be signed 71 | // author: { 72 | // name: localCommit.author.name, 73 | // email: localCommit.author.email, 74 | // date: localCommit.author.date.toISOString(), 75 | // }, 76 | 77 | // If used with GitHub Actions GITHUB_TOKEN following values are used 78 | // author.name: github-actions[bot] 79 | // author.email: 41898282+github-actions[bot]@users.noreply.github.com 80 | // committer.name: GitHub 81 | // committer.email: noreply@github.com 82 | 83 | }).then(({data}) => data) 84 | console.debug('commit', '->', commit.sha) 85 | 86 | return commit 87 | } 88 | 89 | /** 90 | * Get repository owner and name from url. 91 | * @param url - repository url 92 | * @returns repository owner and name 93 | */ 94 | export function parseRepositoryFromUrl(url: string) { 95 | // git@github.com:qoomon/sandbox.git 96 | // https://github.com/qoomon/sandbox.git 97 | const urlMatch = url.trim().match(/.*?(?[^/:]+)\/(?[^/]+?)(?:\.git)?$/) 98 | if (!urlMatch) throw new Error(`Invalid github repository url: ${url}`) 99 | return { 100 | owner: urlMatch.groups!.owner!, 101 | repo: urlMatch.groups!.repo!, 102 | } 103 | } 104 | 105 | export type CreateCommitArgs = { 106 | subject: string 107 | body: string 108 | parents: string[] 109 | tree: string, 110 | files: { 111 | path: string 112 | mode: '100644' | '100755' | '040000' | '160000' | '120000' | string 113 | status: 'A' | 'M' | 'D', 114 | loadContent: () => Promise 115 | }[], 116 | } 117 | 118 | export type TreeFile = { 119 | path: string 120 | mode: '100644' | '100755' | '040000' | '160000' | '120000' 121 | sha: string | null, 122 | type: 'blob' 123 | } 124 | -------------------------------------------------------------------------------- /lib/git.ts: -------------------------------------------------------------------------------- 1 | import {exec} from './actions.js' 2 | 3 | /** 4 | * Get the current branch name. 5 | * @returns branch name 6 | */ 7 | export async function getCurrentBranch(): Promise { 8 | return await exec('git branch --show-current') 9 | .then(({stdout}) => stdout.toString().trim()) 10 | } 11 | 12 | /** 13 | * Get the sha of the given ref. 14 | * @param ref - commit ref 15 | * @returns sha 16 | */ 17 | export async function getRev(ref: string = 'HEAD'): Promise { 18 | return await exec('git rev-parse', [ref]) 19 | .then(({stdout}) => stdout.toString().trim()) 20 | } 21 | 22 | /** 23 | * Get the remote url of the repository. 24 | * @param remoteName - remote name 25 | * @returns remote url 26 | */ 27 | export async function getRemoteUrl(remoteName: string = 'origin'): Promise { 28 | return await exec('git remote get-url --push', [remoteName]) 29 | .then(({stdout}) => stdout.toString().trim()) 30 | } 31 | 32 | /** 33 | * Get the list of unmerged files. 34 | * @returns unmerged files 35 | */ 36 | export async function getUnmergedFiles(): Promise { 37 | return await exec('git diff --name-only --diff-filter=U') 38 | .then(({stdout}) => stdout.toString().split('\n').filter(Boolean)) 39 | } 40 | 41 | /** 42 | * Get the commit details. 43 | * @param ref - ref to get the details for. 44 | * @returns commit details 45 | */ 46 | export async function getCommitDetails(ref: string = 'HEAD'): Promise { 47 | const result = {} 48 | 49 | const fieldsSeparator = '---' 50 | const showOutputLines = await exec('git show --raw --cc', [ 51 | '--format=' + [ 52 | 'commit:%H', 53 | 'tree:%T', 54 | 'parent:%P', 55 | 'author.name:%aN', 56 | 'author.email:%aE', 57 | 'author.date:%ai', 58 | 'committer.name:%cN', 59 | 'committer.email:%cE', 60 | 'committer.date:%ci', 61 | 'subject:%s', 62 | 'body:', 63 | '%b', 64 | fieldsSeparator, 65 | ].join('%n'), 66 | ref, 67 | ]) 68 | .then(({stdout}) => stdout.toString().split('\n')) 69 | const eofBodyIndicatorIndex = showOutputLines.lastIndexOf(fieldsSeparator) 70 | const showOutputFieldLines = showOutputLines.slice(0, eofBodyIndicatorIndex) 71 | const showOutputFileLines = showOutputLines.slice(eofBodyIndicatorIndex + 1 + 1, -1) 72 | 73 | const showFieldLinesIterator = showOutputFieldLines.values() 74 | for (const line of showFieldLinesIterator) { 75 | const lineMatch = line.match(/^(?[^:]+):(?.*)$/) 76 | if (!lineMatch) throw new Error(`Unexpected field line: ${line}`) 77 | const {lineValueName, lineValue} = lineMatch.groups as { lineValueName: string, lineValue: string } 78 | switch (lineValueName) { 79 | case 'commit': 80 | result.sha = lineValue 81 | break 82 | case 'tree': 83 | result.tree = lineValue 84 | break 85 | case 'parent': 86 | result.parents = lineValue.split(' ') 87 | break 88 | case 'author.name': 89 | result.author = result.author ?? {} 90 | result.author.name = lineValue 91 | break 92 | case 'author.email': 93 | result.author = result.author ?? {} 94 | result.author.email = lineValue 95 | break 96 | case 'author.date': 97 | result.author = result.author ?? {} 98 | result.author.date = new Date(lineValue) 99 | break 100 | case 'committer.name': 101 | result.committer = result.committer ?? {} 102 | result.committer.name = lineValue 103 | break 104 | case 'committer.email': 105 | result.committer = result.committer ?? {} 106 | result.committer.email = lineValue 107 | break 108 | case 'committer.date': 109 | result.committer = result.committer ?? {} 110 | result.committer.date = new Date(lineValue) 111 | break 112 | case 'subject': 113 | result.subject = lineValue 114 | break 115 | case 'body': 116 | // read all remaining lines 117 | result.body = [...showFieldLinesIterator].join('\n') 118 | break 119 | default: 120 | throw new Error(`Unexpected field: ${lineValueName}`) 121 | } 122 | } 123 | 124 | result.files = showOutputFileLines 125 | .map(parseRawFileDiffLine) 126 | .filter(({status}) => ['A', 'M', 'D'].includes(status)) as 127 | (ReturnType & { status: 'A' | 'M' | 'D' })[] 128 | 129 | return result 130 | } 131 | 132 | /** 133 | * Get the cached details. 134 | * @returns cached details 135 | */ 136 | export async function getCacheDetails(): Promise { 137 | const result = {} 138 | 139 | const diffOutputFileLines = await exec('git diff --cached --raw --cc') 140 | .then(({stdout}) => stdout.toString().split('\n').filter(Boolean)) 141 | 142 | result.files = diffOutputFileLines 143 | .map(parseRawFileDiffLine) 144 | .filter(({status}) => ['A', 'M', 'D'].includes(status)) as 145 | (ReturnType & { status: 'A' | 'M' | 'D' })[] 146 | 147 | return result 148 | } 149 | 150 | /** 151 | * Parse a line from the raw diff output. 152 | * @param line - line to parse 153 | * @returns parsed line 154 | */ 155 | function parseRawFileDiffLine(line: string): RawFileDiff { 156 | const fileMatch = line.match(/^:+(?:(?\d{6}) ){2,}(?:\w{7,} ){2,}(?[A-Z])\w*\s+(?.*)$/) 157 | if (!fileMatch) throw new Error(`Unexpected file line: ${line}`) 158 | 159 | return { 160 | status: fileMatch.groups!.status, 161 | mode: fileMatch.groups!.mode, 162 | path: fileMatch.groups!.path, 163 | } 164 | } 165 | 166 | /** 167 | * Read the content of the file at the given path. 168 | * @param path - path to the file 169 | * @param ref - ref to read the file from. If not set, the cached file is read. 170 | * @returns file content 171 | */ 172 | export async function readFile(path: string, ref?: string): Promise { 173 | const object = ref ? `${ref}:${path}` : await getCachedObjectSha(path) 174 | return await exec('git cat-file blob', [object], {silent: true}) 175 | .then(({stdout}) => stdout) 176 | } 177 | 178 | /** 179 | * Get the sha of the cached object for the given path. 180 | * @param path - path to the file 181 | * @returns sha of the cached object 182 | */ 183 | async function getCachedObjectSha(path: string) { 184 | return await exec('git ls-files --cached --stage', [path], {silent: false}) 185 | // example output: 100644 5492f6d1d15ac444387259da81d19b74b3f2d4d6 0 dummy.txt 186 | .then(({stdout}) => stdout.toString().split(/\s/)[1]) 187 | } 188 | 189 | export type CommitDetails = { 190 | sha: string 191 | tree: string 192 | parents: string[] 193 | author: { 194 | name: string 195 | email: string 196 | date: Date 197 | } 198 | committer: { 199 | name: string 200 | email: string 201 | date: Date 202 | } 203 | subject: string 204 | body: string 205 | files: { 206 | path: string, 207 | mode: string 208 | status: 'A' | 'M' | 'D' 209 | }[] 210 | } 211 | 212 | export type CacheDetails = { 213 | files: { 214 | path: string, 215 | mode: string 216 | status: 'A' | 'M' | 'D' 217 | }[] 218 | } 219 | 220 | type RawFileDiff = { 221 | mode: string 222 | path: string 223 | status: string 224 | } 225 | --------------------------------------------------------------------------------