All files / libs/vendors/git/src/lib git.ts

30.61% Statements 15/49
100% Branches 2/2
50% Functions 2/4
30.61% Lines 15/49

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 501x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x               1x 1x                                                        
import { execSync } from 'node:child_process';
 
import { simpleGit } from 'simple-git';
 
import { formatSha } from './sha.formatter';
 
export const git = simpleGit();
 
export const getHeadSha = (): string => formatSha(execSync('git rev-parse HEAD', { encoding: 'utf-8' }));
 
export const getPreviousCommitSha = (): string => formatSha(execSync('git rev-parse HEAD~1', { encoding: 'utf-8' }));
 
export const commitExists = (sha: string): boolean => {
  try {
    execSync(`git cat-file -e ${sha}^{commit}`, { stdio: ['pipe', 'pipe', /* silence stderr & throw err */ null] });
    return true;
  } catch {
    return false;
  }
};
 
export async function stashAndSyncBranch(targetBranch: string) {
  const currentBranch = (await git.branch()).current;
  const isWorkingDirectoryClean = (await git.status()).isClean();

  // Stash current changes if any.
  if (!isWorkingDirectoryClean) {
    await git.stash(['push', '--include-untracked', '--message', 'WIP']);
  }

  // Checkbout target branch.
  if (currentBranch !== targetBranch) {
    await git.checkout(targetBranch);
  }

  // Sync target branch.
  await git.fetch(['--all']);

  // Pull only if the branch is also on remote.
  const { tracking } = await git.status(['-sb']);
  if (tracking) {
    await git.pull(['--ff-only']);
  }

  return {
    currentBranch,
    isWorkingDirectoryClean,
  };
}