pr-check / src / git / getCommitHashesFromGitLog.ts
getCommitHashesFromGitLog.ts
Raw
import { getOutputFromRunningCommands } from "../commandline/getOutputFromRunningCommands";

/**
 * Get the commit hashes for commits that are not on the master branch.
 * These are the commits that we want to inspect, as they are the ones that would be included in a pull request.
 * @returns An array of commit hashes.
 */
async function getCommitHashesFromGitLog(): Promise<string[]> {
  const nameOfRemoteMasterBranch = process.env.NAME_OF_DEFAULT_GIT_BRANCH as string;
  const commandsToGetPreviousCommits = ["git", "--no-pager", "log", nameOfRemoteMasterBranch + "..HEAD", "--oneline"];

  const previousCommitsString = await getOutputFromRunningCommands(commandsToGetPreviousCommits)

  if (previousCommitsString === "") {
    process.stdout.write("No commits found. This script works by reading committed code that is not on the master branch. See README. Exiting.")
    process.exit(0);
  }

  let previousCommits = previousCommitsString.split("\n");
  previousCommits = previousCommits.filter((commit) => {
    return commit !== "";
  })

  if (previousCommits.length === 0) {
    throw new Error("No commits found. Exiting.")
  }

  const previousCommitHashes = previousCommits.map((commit) => {
    return commit.split(" ")[0];
  });

  return previousCommitHashes;
}

export { getCommitHashesFromGitLog }