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
6 changes: 5 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@
All notable changes to this project will be documented in this file. See [conventional commits](https://www.conventionalcommits.org/) for commit guidelines.

---
## [Unreleased](https://github.com/ryancyq/github-signed-commit/tree/HEAD)
## [1.3.0](https://github.com/ryancyq/github-signed-commit/compare/v1.2.0..v1.3.0) - 2024-10-30

### Features

- Add support for remote GitHub repository + working directory ([#2](https://github.com/ryancyq/github-signed-commit/issues/2)) - ([2c19408](https://github.com/ryancyq/github-signed-commit/commit/2c19408618f096a6064093809288c28e3f4daaa1)) - Xavier Krantz

### Tests

Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ Note: The `GH_TOKEN` environment variable is **required** for GitHub API request
| `files` | **YES** | Multi-line string of file paths to be committed, relative to the current workspace.|
| `workspace` | **NO** | Directory containing files to be committed. **DEFAULT:** GitHub workspace directory (root of the repository). |
| `commit-message` | **YES** | Commit message for the file changes. |
| `branch-name` | **NO** | Branch to commit, it must already exist in the remote. **DEFAULT:** Workflow triggered branch |
| `branch-name` | **NO*** | Branch to commit, it must already exist in the remote. **DEFAULT:** Workflow triggered branch. **REQUIRED:** If triggered through `on tags`.|
| `branch-push-force` | **NO** | `--force` flag when running `git push <branch-name>`. |
| `tag` | **NO** | Push tag for the new/current commit. |
| `tag-only-if-file-changes` | **NO** | Push tag for new commit only when file changes present. **DEFAULT:** true |
Expand All @@ -79,4 +79,4 @@ Note: The `GH_TOKEN` environment variable is **required** for GitHub API request
[coverage_badge]: https://codecov.io/gh/ryancyq/github-signed-commit/graph/badge.svg?token=KZTD2F2MN2
[coverage]: https://codecov.io/gh/ryancyq/github-signed-commit
[maintainability_badge]: https://api.codeclimate.com/v1/badges/0de9dbec270ca85719c6/maintainability
[maintainability]: https://codeclimate.com/github/ryancyq/github-signed-commit/maintainability
[maintainability]: https://codeclimate.com/github/ryancyq/github-signed-commit/maintainability
4 changes: 2 additions & 2 deletions __tests__/git.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ describe('Git CLI', () => {

describe('git add', () => {
beforeEach(() => {
jest.spyOn(cwd, 'getWorkspace').mockReturnValue('/test-workspace')
jest.spyOn(cwd, 'getWorkspace').mockReturnValue('test-workspace/')
})

it('should ensure file paths are within curent working directory', async () => {
Expand All @@ -190,7 +190,7 @@ describe('Git CLI', () => {
await addFileChanges(['*.ts', '~/.bashrc'])
expect(execMock).toHaveBeenCalledWith(
'git',
['add', '--', '/test-workspace/*.ts', '/test-workspace/~/.bashrc'],
['add', '--', 'test-workspace/*.ts', 'test-workspace/~/.bashrc'],
expect.objectContaining({
listeners: { stdline: expect.anything(), errline: expect.anything() },
})
Expand Down
13 changes: 13 additions & 0 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,23 @@ inputs:
Directory containing files to be committed. Default: GitHub workspace directory (root of repository).
required: false
default: ''
workdir:
description: |
Directory where the action should run. Default: GitHub workspace directory (root of repository from where the GH Workflow is triggered).
required: false
default: ''
commit-message:
description: |
Commit message for the file changes.
required: false
owner:
description: |
GitHub repository owner (user or organization), defaults to the repo invoking the action.
required: false
repo:
description: |
GitHub repository name, defaults to the repo invoking the action.
required: false
branch-name:
description: |
Branch to commit to. Default: Workflow triggered branch.
Expand Down
232 changes: 172 additions & 60 deletions dist/index.js

Large diffs are not rendered by default.

23 changes: 13 additions & 10 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
"fetch-mock": "^11.1.5",
"jest": "^29.0.0",
"ts-jest": "^29.2.5",
"typescript": "^5.6.2",
"typescript": "^5.7.2",
"typescript-eslint": "^8.11.0"
},
"engines": {
Expand Down
21 changes: 18 additions & 3 deletions src/git.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
import * as core from '@actions/core'
import { exec } from '@actions/exec'
import { join } from 'node:path'
import { join, relative, resolve } from 'node:path'
import {
FileChanges,
FileAddition,
FileDeletion,
} from '@octokit/graphql-schema'

import { getWorkspace } from './utils/cwd'
import { getCwd, getWorkspace } from './utils/cwd'

async function execGit(args: string[]) {
const debugOutput: string[] = []
const warningOutput: string[] = []
const errorOutput: string[] = []

core.debug('execGit() - args: ' + JSON.stringify(args))
await exec('git', args, {
silent: true,
ignoreReturnCode: true,
Expand Down Expand Up @@ -53,8 +54,22 @@ export async function pushCurrentBranch() {
}

export async function addFileChanges(globPatterns: string[]) {
const cwd = getCwd()
const workspace = getWorkspace()
const workspacePaths = globPatterns.map((p) => join(workspace, p))
const resolvedWorkspace = resolve(workspace)
core.debug(
'addFileChanges() - resolvedWorkspace: ' + JSON.stringify(resolvedWorkspace)
)

let workspacePaths = globPatterns
if (resolvedWorkspace.includes(cwd)) {
core.notice(
'addFileChanges() - "workspace" is a subdirectory, updating globPatterns'
)
workspacePaths = globPatterns.map((p) =>
join(relative(cwd, resolvedWorkspace), p)
)
}

await execGit(['add', '--', ...workspacePaths])
}
Expand Down
1 change: 1 addition & 0 deletions src/github/graphql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ export async function createCommitOnBranch(
fileChanges.additions = await Promise.all(promises)
}


const commitInput: CreateCommitOnBranchInput = {
branch,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
Expand Down
2 changes: 2 additions & 0 deletions src/github/repo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ function resolveCurrentBranch(ref: string): string {
} else if (ref.startsWith('refs/pull/')) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access
return github.context.payload.pull_request?.head?.ref ?? ''
} else if (ref.startsWith('refs/tags/')) {
return ''
}

throw new Error(`Unsupported ref: ${ref}`)
Expand Down
57 changes: 47 additions & 10 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
pushCurrentBranch,
switchBranch,
} from './git'
import { getCwd, getWorkdir } from './utils/cwd'
import { getInput } from './utils/input'
import {
NoFileChanges,
Expand All @@ -23,32 +24,61 @@ import {

export async function run(): Promise<void> {
try {
core.info('Getting info from GH Worklfow context')
const { owner, repo, branch } = getContext()

core.info('Setting variables according to inputs and context')
core.debug('* branch')
const inputBranch = getInput('branch-name')
if (inputBranch && inputBranch !== branch) {
await switchBranch(inputBranch)
const selectedBranch = inputBranch ? inputBranch : branch

core.debug('* owner')
const inputOwner = getInput('owner')
const selectedOwner = inputOwner ? inputOwner : owner

core.debug('* repo')
const inputRepo = getInput('repo')
const selectedRepo = inputRepo ? inputRepo : repo

if (
selectedOwner == owner &&
selectedRepo == repo &&
selectedBranch !== branch
) {
core.warning(
'Pushing local and current branch to remote before proceeding'
)
// Git commands
await switchBranch(selectedBranch)
await pushCurrentBranch()
}
const currentBranch = inputBranch ? inputBranch : branch

const repository = await core.group(
`fetching repository info for owner: ${owner}, repo: ${repo}, branch: ${currentBranch}`,
`fetching repository info for owner: ${selectedOwner}, repo: ${selectedRepo}, branch: ${selectedBranch}`,
async () => {
const startTime = Date.now()
const repositoryData = await getRepository(owner, repo, currentBranch)
const repositoryData = await getRepository(
selectedOwner,
selectedRepo,
selectedBranch
)
const endTime = Date.now()
core.debug(`time taken: ${(endTime - startTime).toString()} ms`)
return repositoryData
}
)

core.info('Checking remote branches')
if (!repository.ref) {
if (inputBranch && currentBranch == inputBranch) {
if (inputBranch) {
throw new InputBranchNotFound(inputBranch)
} else {
throw new BranchNotFound(currentBranch)
throw new BranchNotFound(branch)
}
}

core.info('Processing to create signed commit')
core.debug('Get last (current?) commit')
const currentCommit = repository.ref.target.history?.nodes?.[0]
if (!currentCommit) {
throw new BranchCommitNotFound(repository.ref.name)
Expand All @@ -57,12 +87,19 @@ export async function run(): Promise<void> {
let createdCommit: Commit | undefined
const filePaths = core.getMultilineInput('files')
if (filePaths.length <= 0) {
core.debug('skip file commit, empty files input')
core.notice('skip file commit, empty files input')
} else {
core.debug(
`proceed with file commit, input: ${JSON.stringify(filePaths)}`
`Proceed with file commit, input: ${JSON.stringify(filePaths)}`
)

const workdir = getWorkdir()
const cwd = getCwd()
if (cwd !== workdir) {
core.notice('Changing working directory to Workdir: ' + workdir)
process.chdir(workdir)
}

await addFileChanges(filePaths)
const fileChanges = await getFileChanges()
const fileCount =
Expand All @@ -89,7 +126,7 @@ export async function run(): Promise<void> {
commitMessage,
{
repositoryNameWithOwner: repository.nameWithOwner,
branchName: currentBranch,
branchName: selectedBranch,
},
fileChanges
)
Expand Down
8 changes: 8 additions & 0 deletions src/utils/cwd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,11 @@ export function getWorkspace() {
core.debug(`workspace: ${workspace}`)
return workspace
}

export function getWorkdir() {
const workdir = getInput('workdir', {
default: process.env.GITHUB_WORKSPACE,
})
core.debug(`workdir: ${workdir}`)
return workdir
}
Loading