import * as core from '@actions/core'; import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; import {simpleGit, Response, SimpleGit} from 'simple-git'; import { checkInputs, getInput, logOutputs, parseBoolOrGitArgs, parsePushAttempts, setOutput, } from './io'; import { assertNoUnexpectedGitlinks, assertWorkingDirectory, findUnexpectedGitlinks, log, matchGitArgs, neutralizeLogString, parseInputArray, pickGitIdentityConfig, resolveBaseDir, safeInfo, usesImplicitPullTarget, } from './util'; const cwdInput = getInput('cwd') || ''; const baseDir = resolveBaseDir(cwdInput); let git!: SimpleGit; /** Env for git child processes; restricts transports unless opt-out is set. */ function gitChildEnv( extra: Partial> = {}, ): NodeJS.ProcessEnv { const env: NodeJS.ProcessEnv = {...process.env}; for (const key of Object.keys(env)) { if (key.startsWith('GIT_')) delete env[key]; } if (!getInput('allow_unsafe_git_protocols', true)) { env.GIT_ALLOW_PROTOCOL = 'https:http:ssh:file:git'; env.GIT_PROTOCOL_FROM_USER = '0'; } if (extra.GIT_INDEX_FILE) env.GIT_INDEX_FILE = extra.GIT_INDEX_FILE; return env; } function createGit() { return simpleGit({ baseDir, allowEnvironment: [ 'GIT_ALLOW_PROTOCOL', 'GIT_PROTOCOL_FROM_USER', 'GIT_INDEX_FILE', ], }); } function parseGitArgs(string: string) { return matchGitArgs(string, { allowUnsafeGitProtocols: getInput('allow_unsafe_git_protocols', true), }); } const exitErrors: Error[] = []; safeInfo(`Running in ${baseDir}`); (async () => { assertWorkingDirectory(baseDir, cwdInput); git = createGit(); await checkInputs(); git.env(gitChildEnv()); const dryRun = getInput('dry_run', true); core.startGroup('Internal logs'); safeInfo(dryRun ? '> Staging files (dry run)...' : '> Staging files...'); const ignoreErrors = getInput('pathspec_error_handling') === 'ignore' ? 'pathspec' : 'none'; let wouldStageChanges = false; if (getInput('add')) { safeInfo(dryRun ? '> Adding files (dry run)...' : '> Adding files...'); const addResults = await add(ignoreErrors, dryRun); if (dryRun) wouldStageChanges = wouldStageChanges || addResults.some(r => typeof r === 'string' && r.trim().length > 0); } else safeInfo('> No files to add.'); if (getInput('remove')) { safeInfo(dryRun ? '> Removing files (dry run)...' : '> Removing files...'); const removeResults = await remove(ignoreErrors, dryRun); if (dryRun) wouldStageChanges = wouldStageChanges || removeResults.some(r => { if (r === null || r === undefined) return false; const text = typeof r === 'string' ? r : String(r); return text.trim().length > 0; }); } else safeInfo('> No files to remove.'); safeInfo('> Checking for uncommitted changes in the git working tree...'); const changedFiles = (await git.diffSummary(['--cached'])).files.length; const allowEmpty = parseGitArgs(getInput('commit') || '').includes( '--allow-empty', ); // continue if there are any changes or if the allow-empty commit argument is included if (changedFiles > 0 || wouldStageChanges || allowEmpty) { safeInfo( dryRun ? `> Dry run: would proceed (${changedFiles} already staged` + `${wouldStageChanges ? ', staging probes reported changes' : ''}` + `${allowEmpty ? ', --allow-empty' : ''}).` : `> Found ${changedFiles} changed files.`, ); core.debug(`--allow-empty argument detected: ${allowEmpty}`); if (dryRun) { await logDryRunRemainingSteps(); core.endGroup(); safeInfo('> Dry run completed. No changes were made.'); return; } await git .addConfig('user.email', getInput('author_email'), undefined, log) .addConfig('user.name', getInput('author_name'), undefined, log) .addConfig('author.email', getInput('author_email'), undefined, log) .addConfig('author.name', getInput('author_name'), undefined, log) .addConfig('committer.email', getInput('committer_email'), undefined, log) .addConfig('committer.name', getInput('committer_name'), undefined, log); if (core.isDebug()) { const identity = pickGitIdentityConfig((await git.listConfig()).all); core.debug( Object.keys(identity).length ? '> Current git identity config\n' + JSON.stringify(identity, null, 2) : '> Git identity config set (no identity keys present in listConfig)', ); } let fetchOption: string | boolean; try { fetchOption = getInput('fetch', true); } catch { fetchOption = getInput('fetch'); } if (fetchOption) { safeInfo('> Fetching repo...'); await git.fetch( parseGitArgs(fetchOption === true ? '' : fetchOption), log, ); } else safeInfo('> Not fetching repo.'); const targetBranch = getInput('new_branch'); let branchCreated = false; if (targetBranch) { safeInfo('> Checking-out branch...'); if (!fetchOption) core.warning( 'Creating a new branch without fetching the repo first could result in an error when pushing to GitHub. Refer to the action README for more info about this topic.', ); branchCreated = await git .checkout([targetBranch]) .then(() => { log(undefined, `'${targetBranch}' branch already existed.`); return false; }) .catch(async () => { log(undefined, `Creating '${targetBranch}' branch.`); await git.checkout(['-b', targetBranch], log); return true; }); } const pullOption = parseBoolOrGitArgs('pull'); const pullArgs = parseGitArgs(pullOption === true ? '' : pullOption || ''); if (pullOption) { await pullFromRemote(pullArgs, { restage: true, ignoreErrors, createdBranch: branchCreated ? targetBranch : undefined, }); } else safeInfo('> Not pulling from repo.'); safeInfo('> Creating commit...'); const data = await git.commit( getInput('message'), parseGitArgs(getInput('commit') || ''), ); log(undefined, data); // simple-git can resolve with an empty SHA when no commit was created // (e.g. nothing left to commit). Do not report a false success. if (!data.commit) { throw new Error( 'Commit did not produce a SHA; refusing to report committed=true.', ); } setOutput('committed', 'true'); setOutput('commit_long_sha', data.commit); setOutput('commit_sha', data.commit.substring(0, 7)); let pushOption: string | boolean; try { pushOption = getInput('push', true); } catch { pushOption = getInput('push'); } const pushAttempts = pushOption ? parsePushAttempts(getInput('push_attempts') || '1') : 0; const tagArgs = parseGitArgs(getInput('tag') || ''); const mayRetag = tagArgs.length > 0 && Boolean(pullOption) && pushAttempts > 1; let head = data.commit; let retryTag: string | undefined; if (getInput('tag')) { safeInfo('> Tagging commit...'); if (!fetchOption) core.warning( 'Creating a tag without fetching the repo first could result in an error when pushing to GitHub. Refer to the action README for more info about this topic.', ); // Identify only the tag this invocation created or replaced at HEAD. // Keep tagging before the push so custom atomic branch/tag pushes work. const previousTags = mayRetag ? await tagsAtCommit(head) : undefined; try { log(null, await git.tag(tagArgs)); setOutput('tagged', 'true'); if (previousTags) retryTag = (await tagsAtCommit(head)).find( tag => !previousTags.includes(tag), ); } catch (err) { core.setFailed(err instanceof Error ? err : String(err)); } } else safeInfo('> No tag info provided.'); if (pushOption) { for (let attempt = 1; attempt <= pushAttempts; attempt++) { try { safeInfo( pushAttempts > 1 ? `> Pushing commit to repo (attempt ${attempt}/${pushAttempts})...` : '> Pushing commit to repo...', ); await pushCommit(pushOption, mayRetag); break; } catch (err) { if (attempt === pushAttempts) throw err; const message = err instanceof Error ? err.message : String(err); core.warning( `Push failed (attempt ${attempt}/${pushAttempts}): ${neutralizeLogString(message)}`, ); if (pullOption) { await pullFromRemote(pullArgs, { restage: false, ignoreErrors, createdBranch: branchCreated ? targetBranch : undefined, retryFromOrigin: pushOption === true, }); // Rebase rewrites the commit; refresh outputs from HEAD. const previousHead = head; head = (await git.revparse(['HEAD'])).trim(); setOutput('commit_long_sha', head); setOutput('commit_sha', head.substring(0, 7)); if (retryTag && head !== previousHead) { if (!(await tagsAtCommit(previousHead)).includes(retryTag)) throw new Error('The local tag changed during the push retry.'); // Reapply the original target, annotation and signing options. // An explicitly pinned target stays pinned. await git.tag(['--force', ...tagArgs]); const [ref] = retryTag.split(' '); retryTag = (await tagsAtCommit(head)).find(tag => tag.startsWith(ref + ' '), ); } } } } if (getInput('tag')) { safeInfo('> Pushing tags to repo...'); await git .pushTags('origin', parseGitArgs(getInput('tag_push') || '')) .then(data => { setOutput('tag_pushed', 'true'); return log(null, data); }) .catch(err => core.setFailed(err)); } else safeInfo('> No tags to push.'); } else safeInfo('> Not pushing anything.'); core.endGroup(); safeInfo('> Task completed.'); } else { core.endGroup(); safeInfo( dryRun ? '> Dry run: working tree clean. Nothing would be committed.' : '> Working tree clean. Nothing to commit.', ); } })() .then(() => { // Check for exit errors if (exitErrors.length === 1) throw exitErrors[0]; else if (exitErrors.length > 1) { exitErrors.forEach(e => core.error(e)); throw 'There have been multiple runtime errors.'; } }) .then(logOutputs) .catch(e => { core.endGroup(); logOutputs(); core.setFailed(e); }); async function logDryRunRemainingSteps() { safeInfo( `> Would set git identity: ${getInput('author_name')} <${getInput( 'author_email', )}> (committer: ${getInput('committer_name')} <${getInput( 'committer_email', )}>)`, ); let fetchOption: string | boolean; try { fetchOption = getInput('fetch', true); } catch { fetchOption = getInput('fetch'); } if (fetchOption) { safeInfo( `> Would fetch repo${ fetchOption === true ? '' : ` with: ${fetchOption}` }.`, ); } else safeInfo('> Would not fetch repo.'); const targetBranch = getInput('new_branch'); if (targetBranch) { safeInfo(`> Would check out branch '${targetBranch}'.`); if (!fetchOption) core.warning( 'Creating a new branch without fetching the repo first could result in an error when pushing to GitHub. Refer to the action README for more info about this topic.', ); } const pullOption = parseBoolOrGitArgs('pull'); if (pullOption) { const pullArgs = parseGitArgs(pullOption === true ? '' : pullOption); safeInfo( `> Would pull from remote${ targetBranch && usesImplicitPullTarget(pullArgs) ? ' unless a new branch is created without an upstream' : '' }${pullOption === true ? '' : ` with: ${pullOption}`}.`, ); } else safeInfo('> Would not pull from repo.'); safeInfo( `> Would create commit with message: "${getInput('message')}"${ getInput('commit') ? ` (extra args: ${getInput('commit')})` : '' }.`, ); if (getInput('tag')) { safeInfo(`> Would tag commit with: ${getInput('tag')}.`); if (!fetchOption) core.warning( 'Creating a tag without fetching the repo first could result in an error when pushing to GitHub. Refer to the action README for more info about this topic.', ); } else safeInfo('> No tag info provided.'); let pushOption: string | boolean; try { pushOption = getInput('push', true); } catch { pushOption = getInput('push'); } if (pushOption) { const pushAttempts = parsePushAttempts(getInput('push_attempts') || '1'); if (pushOption === true) { const branch = getInput('new_branch'); safeInfo( branch ? `> Would push commit to repo (set upstream for '${branch}')${ pushAttempts > 1 ? ` with up to ${pushAttempts} attempts` : '' }.` : `> Would push commit to repo${ pushAttempts > 1 ? ` with up to ${pushAttempts} attempts` : '' }.`, ); } else safeInfo( `> Would push commit to repo with: ${pushOption}${ pushAttempts > 1 ? ` (up to ${pushAttempts} attempts)` : '' }.`, ); if (getInput('tag')) { safeInfo( `> Would push tags to repo${ getInput('tag_push') ? ` with: ${getInput('tag_push')}` : '' }.`, ); } else safeInfo('> No tags to push.'); } else safeInfo('> Would not push anything.'); } async function tagsAtCommit(commit: string): Promise { const tags = await git.raw([ 'for-each-ref', '--points-at=' + commit, '--format=%(refname) %(objectname)', 'refs/tags/', ]); return tags.trim().split('\n').filter(Boolean); } async function pullFromRemote( args: string[], options: { restage: boolean; ignoreErrors: 'all' | 'pathspec' | 'none'; createdBranch?: string; retryFromOrigin?: boolean; }, ) { if (options.createdBranch && usesImplicitPullTarget(args)) { // A configured pull target may have no local tracking-ref mapping when // remote.fetch is narrow. Let Git resolve it rather than treating it as absent. const upstream = await git.getConfig( `branch.${options.createdBranch}.merge`, ); if (upstream.value === null) { // The default push explicitly selects origin. Custom push commands // need an explicit pull target; do not guess their remote or refspec. if (!options.retryFromOrigin) { safeInfo('> Skipping pull because the new branch has no upstream.'); return; } const localRef = `refs/heads/${options.createdBranch}`; // A source-only push uses remote.origin.push to expand its destination. // Ask Git for the remote ref, even if there is no local tracking ref. const mappedRef = await git.raw([ '-c', `branch.${options.createdBranch}.pushRemote=origin`, 'for-each-ref', '--format=%(push:remoteref)', '--', localRef, ]); const remoteRef = mappedRef.trim() || localRef; if (!remoteRef.startsWith('refs/heads/')) throw new Error( 'Set an explicit pull target for a non-branch push destination.', ); const remoteBranch = await git.listRemote([ '--heads', 'origin', remoteRef, ]); if (!remoteBranch.trim()) { safeInfo( '> Skipping pull because the new branch is not on origin yet.', ); return; } args = [...args, 'origin', remoteRef]; } } safeInfo('> Pulling from remote...'); core.debug(`Current git pull arguments: ${args.join(' ')}`); await git.fetch(undefined, log).pull(undefined, undefined, args, log); safeInfo('> Checking for conflicts...'); const status = await git.status(undefined, log); if (status.conflicted.length) { throw new Error( `There are ${ status.conflicted.length } conflicting files: ${status.conflicted .map(neutralizeLogString) .join(', ')}`, ); } safeInfo('> No conflicts found.'); if (options.restage) { safeInfo('> Re-staging files...'); if (getInput('add')) await add(options.ignoreErrors); if (getInput('remove')) await remove(options.ignoreErrors); } } async function pushCommit(pushOption: true | string, mayRetag: boolean) { if (pushOption === true) { // With push.followTags enabled, Git can publish an annotated tag even when // it rejects the branch. The separate tag push publishes it after success. const options = ['--set-upstream']; if (mayRetag) options.push('--no-follow-tags'); const branch = getInput('new_branch'); if (branch) { core.debug(`Running: git push ${options.join(' ')} origin -- ${branch}`); await git.raw( ['push', ...options, 'origin', '--', branch], (err, data?) => { if (data) setOutput('pushed', 'true'); return log(err, data); }, ); } else { core.debug(`Running: git push origin ${options.join(' ')}`); await git.push('origin', undefined, options, (err, data?) => { if (data) setOutput('pushed', 'true'); return log(err, data); }); } } else { core.debug(`Running: git push ${pushOption}`); await git.push( undefined, undefined, parseGitArgs(pushOption), (err, data?) => { if (data) setOutput('pushed', 'true'); return log(err, data); }, ); } } async function add( ignoreErrors: 'all' | 'pathspec' | 'none' = 'none', dryRun = false, ) { const input = getInput('add'); if (!input) return []; const parsed = parseInputArray(input); const res: (string | void)[] = []; for (const args of parsed) { const gitArgs = dryRun ? ['--dry-run', ...parseGitArgs(args)] : parseGitArgs(args); res.push( // Push the result of every git command (which are executed in order) to the array // If any of them fails, the whole function will return a Promise rejection await git .add(gitArgs, (err, data) => log(ignoreErrors === 'all' ? null : err, data), ) .catch((e: Error) => { // if I should ignore every error, return if (ignoreErrors === 'all') return; // if it's a pathspec error... if ( e.message.includes('fatal: pathspec') && e.message.includes('did not match any files') ) { if (ignoreErrors === 'pathspec') return; const peh = getInput('pathspec_error_handling'), err = new Error( `Add command did not match any file: git add ${neutralizeLogString(args)}`, ); if (peh === 'exitImmediately') throw err; if (peh === 'exitAtEnd') exitErrors.push(err); } else throw e; }), ); } if (dryRun) { await assertGitlinksWithTempIndex(parsed, ignoreErrors); } else { const cachedRaw = await git.raw(['diff', '--cached', '--raw']); assertNoUnexpectedGitlinks(findUnexpectedGitlinks(cachedRaw)); } return res; } /** * Stages `add` pathspecs into an isolated temporary index and rejects unexpected * gitlinks, without touching the repository's real index. */ async function assertGitlinksWithTempIndex( addArgGroups: string[], ignoreErrors: 'all' | 'pathspec' | 'none', ) { const tmpIndex = path.join( os.tmpdir(), `add-and-commit-${process.pid}-${Date.now()}.index`, ); try { const indexPathRaw = ( await git.raw(['rev-parse', '--git-path', 'index']) ).trim(); const indexPath = path.isAbsolute(indexPathRaw) ? indexPathRaw : path.join(baseDir, indexPathRaw); if (fs.existsSync(indexPath)) { fs.copyFileSync(indexPath, tmpIndex); } else { const gitSeed = createGit().env(gitChildEnv({GIT_INDEX_FILE: tmpIndex})); const headResolves = await git .raw(['rev-parse', '--verify', 'HEAD']) .then(() => true) .catch(() => false); if (headResolves) { await gitSeed.raw(['read-tree', 'HEAD']); } else { await gitSeed.raw(['read-tree', '--empty']); } } const gitTmp = createGit().env(gitChildEnv({GIT_INDEX_FILE: tmpIndex})); for (const args of addArgGroups) { await gitTmp .add(parseGitArgs(args), (err, data) => log(ignoreErrors === 'all' ? null : err, data), ) .catch((e: Error) => { if (ignoreErrors === 'all') return; if ( e.message.includes('fatal: pathspec') && e.message.includes('did not match any files') ) { // Pathspec outcomes were already handled by the dry-run add probes. if (ignoreErrors === 'pathspec') return; const peh = getInput('pathspec_error_handling'); if (peh === 'exitImmediately') { throw new Error( `Add command did not match any file: git add ${neutralizeLogString(args)}`, ); } return; } throw e; }); } const cachedRaw = await gitTmp.raw(['diff', '--cached', '--raw']); assertNoUnexpectedGitlinks(findUnexpectedGitlinks(cachedRaw)); } finally { fs.rmSync(tmpIndex, {force: true}); fs.rmSync(`${tmpIndex}.lock`, {force: true}); } } async function remove( ignoreErrors: 'all' | 'pathspec' | 'none' = 'none', dryRun = false, ): Promise<(void | Response | string)[]> { const input = getInput('remove'); if (!input) return []; const parsed = parseInputArray(input); const res: (void | Response | string)[] = []; for (const args of parsed) { const gitArgs = dryRun ? ['--dry-run', ...parseGitArgs(args)] : parseGitArgs(args); res.push( // Push the result of every git command (which are executed in order) to the array // If any of them fails, the whole function will return a Promise rejection await git .rm(gitArgs, (e, d) => log(ignoreErrors === 'all' ? null : e, d)) .catch((e: Error) => { // if I should ignore every error, return if (ignoreErrors === 'all') return; // if it's a pathspec error... if ( e.message.includes('fatal: pathspec') && e.message.includes('did not match any files') ) { if (ignoreErrors === 'pathspec') return; const peh = getInput('pathspec_error_handling'), err = new Error( `Remove command did not match any file:\n git rm ${neutralizeLogString(args)}`, ); if (peh === 'exitImmediately') throw err; if (peh === 'exitAtEnd') exitErrors.push(err); } else throw e; }), ); } return res; }