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

### Documentation

Expand Down
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,9 @@ 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. |
| `repository` | **NO** | Repository name including owner (e.g. owner/repo). **DEFAULT:** Workflow triggered repository |
| `branch-name` | **NO** | Branch to commit, it must already exist in the remote. **DEFAULT:** Workflow triggered branch |
| `owner` | **NO** | GitHub repository owner (user or organization), defaults to the repo invoking the action. |
| `repo` | **NO** | GitHub repository name, defaults to the repo invoking the action. |
| `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 @@ -80,4 +81,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 @@ -182,7 +182,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 @@ -191,7 +191,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
14 changes: 11 additions & 3 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +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
repository:
owner:
description: |
Repository name including owner (e.g. owner/repo). Default: Workflow triggered repository.
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
default: ''
branch-name:
description: |
Branch to commit to. Default: Workflow triggered branch.
Expand Down
71 changes: 53 additions & 18 deletions dist/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -30023,6 +30023,7 @@ function execGit(args) {
const debugOutput = [];
const warningOutput = [];
const errorOutput = [];
core.debug('execGit() - args: ' + JSON.stringify(args));
yield (0, exec_1.exec)('git', args, {
silent: true,
ignoreReturnCode: true,
Expand Down Expand Up @@ -30067,8 +30068,15 @@ function pushCurrentBranch() {
}
function addFileChanges(globPatterns) {
return __awaiter(this, void 0, void 0, function* () {
const cwd = (0, cwd_1.getCwd)();
const workspace = (0, cwd_1.getWorkspace)();
const workspacePaths = globPatterns.map((p) => (0, node_path_1.join)(workspace, p));
const resolvedWorkspace = (0, node_path_1.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) => (0, node_path_1.join)((0, node_path_1.relative)(cwd, resolvedWorkspace), p));
}
yield execGit(['add', '--', ...workspacePaths]);
});
}
Expand Down Expand Up @@ -30379,6 +30387,9 @@ function resolveCurrentBranch(ref) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access
return (_c = (_b = (_a = github.context.payload.pull_request) === null || _a === void 0 ? void 0 : _a.head) === null || _b === void 0 ? void 0 : _b.ref) !== null && _c !== void 0 ? _c : '';
}
else if (ref.startsWith('refs/tags/')) {
return '';
}
throw new Error(`Unsupported ref: ${ref}`);
}
function getContext() {
Expand Down Expand Up @@ -30445,52 +30456,68 @@ const core = __importStar(__nccwpck_require__(7484));
const graphql_1 = __nccwpck_require__(1422);
const repo_1 = __nccwpck_require__(1839);
const git_1 = __nccwpck_require__(1243);
const cwd_1 = __nccwpck_require__(9827);
const input_1 = __nccwpck_require__(7797);
const errors_1 = __nccwpck_require__(3916);
function run() {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b, _c, _d, _e, _f;
try {
core.info('Getting info from GH Worklfow context');
const { owner, repo, branch } = (0, repo_1.getContext)();
const inputRepository = (0, input_1.getInput)('repository');
core.info('Setting variables according to inputs and context');
core.debug('* branch');
const inputBranch = (0, input_1.getInput)('branch-name');
if (inputBranch && inputBranch !== branch) {
yield (0, git_1.switchBranch)(inputBranch);
const selectedBranch = inputBranch ? inputBranch : branch;
core.debug('* owner');
const inputOwner = (0, input_1.getInput)('owner');
const selectedOwner = inputOwner ? inputOwner : owner;
core.debug('* repo');
const inputRepo = (0, input_1.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
yield (0, git_1.switchBranch)(selectedBranch);
yield (0, git_1.pushCurrentBranch)();
}
const repositoryParts = inputRepository ? inputRepository.split('/') : [];
if (repositoryParts.length && repositoryParts.length != 2) {
throw new errors_1.InputRepositoryInvalid(inputRepository);
}
const currentOwner = repositoryParts.length ? repositoryParts[0] : owner;
const currentRepository = repositoryParts.length ? repositoryParts[1] : repo;
const currentBranch = inputBranch ? inputBranch : branch;
const repository = yield core.group(`fetching repository info for owner: ${currentOwner}, repo: ${currentRepository}, branch: ${currentBranch}`, () => __awaiter(this, void 0, void 0, function* () {
const repository = yield core.group(`fetching repository info for owner: ${selectedOwner}, repo: ${selectedRepo}, branch: ${selectedBranch}`, () => __awaiter(this, void 0, void 0, function* () {
const startTime = Date.now();
const repositoryData = yield (0, graphql_1.getRepository)(currentOwner, currentRepository, currentBranch);
const repositoryData = yield (0, graphql_1.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 errors_1.InputBranchNotFound(inputBranch);
}
else {
throw new errors_1.BranchNotFound(currentBranch);
throw new errors_1.BranchNotFound(branch);
}
}
core.info('Processing to create signed commit');
core.debug('Get last (current?) commit');
const currentCommit = (_b = (_a = repository.ref.target.history) === null || _a === void 0 ? void 0 : _a.nodes) === null || _b === void 0 ? void 0 : _b[0];
if (!currentCommit) {
throw new errors_1.BranchCommitNotFound(repository.ref.name);
}
let createdCommit;
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)}`);
core.debug(`Proceed with file commit, input: ${JSON.stringify(filePaths)}`);
const workdir = (0, cwd_1.getWorkdir)();
const cwd = (0, cwd_1.getCwd)();
if (cwd !== workdir) {
core.notice('Changing working directory to Workdir: ' + workdir);
process.chdir(workdir);
}
yield (0, git_1.addFileChanges)(filePaths);
const fileChanges = yield (0, git_1.getFileChanges)();
const fileCount = ((_d = (_c = fileChanges.additions) === null || _c === void 0 ? void 0 : _c.length) !== null && _d !== void 0 ? _d : 0) +
Expand All @@ -30512,7 +30539,7 @@ function run() {
const startTime = Date.now();
const commitData = yield (0, graphql_1.createCommitOnBranch)(currentCommit, commitMessage, {
repositoryNameWithOwner: repository.nameWithOwner,
branchName: currentBranch,
branchName: selectedBranch,
}, fileChanges);
const endTime = Date.now();
core.debug(`time taken: ${(endTime - startTime).toString()} ms`);
Expand Down Expand Up @@ -30646,6 +30673,7 @@ var __importStar = (this && this.__importStar) || (function () {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getCwd = getCwd;
exports.getWorkspace = getWorkspace;
exports.getWorkdir = getWorkdir;
const core = __importStar(__nccwpck_require__(7484));
const input_1 = __nccwpck_require__(7797);
function getCwd() {
Expand All @@ -30660,6 +30688,13 @@ function getWorkspace() {
core.debug(`workspace: ${workspace}`);
return workspace;
}
function getWorkdir() {
const workdir = (0, input_1.getInput)('workdir', {
default: process.env.GITHUB_WORKSPACE,
});
core.debug(`workdir: ${workdir}`);
return workdir;
}


/***/ }),
Expand Down
19 changes: 19 additions & 0 deletions package-lock.json

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

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
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
Loading