From 604b04619fa37d31a72a447c7e4d2215968d4c6f Mon Sep 17 00:00:00 2001 From: George Cadwallader Date: Tue, 1 Oct 2024 18:43:15 +0100 Subject: [PATCH] feat(core): source control commands for retrieving commits These two commands will be used to retrieve commits from the source control provider. One retrieves the latest, current commit; and the other returns a list of commits. The commit list can accept from and to arguments that filter the list of commits that will be returned. Ref: #75 --- src/lib/source-control/git.ts | 32 ++++++++++++++++++++++++++++++++ src/lib/source-control/index.ts | 13 +++++++++++++ 2 files changed, 45 insertions(+) diff --git a/src/lib/source-control/git.ts b/src/lib/source-control/git.ts index 8715774..b842269 100644 --- a/src/lib/source-control/git.ts +++ b/src/lib/source-control/git.ts @@ -1,4 +1,5 @@ import {run} from '../exec'; +import * as fs from 'fs'; import type {SourceControlProvider} from '.'; const git: SourceControlProvider = { @@ -17,6 +18,37 @@ const git: SourceControlProvider = { const {stdout} = await run(`git rev-parse --show-toplevel`); return stdout.trim(); }, + getCurrentCommitMessage: async () => { + const root = await git.root(); + + const commitEditMessagePath = `${root}/.git/COMMIT_EDITMSG`; + + if (fs.existsSync(commitEditMessagePath)) { + const commitEditMessage = fs + .readFileSync(commitEditMessagePath) + .toString(); + + const scissors = commitEditMessage.indexOf( + '------------------------ >8 ------------------------', + ); + + const end = scissors > -1 ? scissors : commitEditMessage.length; + const editMessage = commitEditMessage.substring(0, end).replace(/^#.*$/gm, '').trim(); + + if (editMessage.length) { + return editMessage; + } + } + + return null; + }, + getCommits: async (from, to) => { + const range = from && to ? `${from}..${to}` : ''; + const {stdout: commitsString} = await run( + `git log ${range} --pretty=format:"%B%x00"`, + ); + return commitsString.split('\0'); + }, }; export default git; diff --git a/src/lib/source-control/index.ts b/src/lib/source-control/index.ts index 08023c9..4e87fca 100644 --- a/src/lib/source-control/index.ts +++ b/src/lib/source-control/index.ts @@ -16,6 +16,19 @@ export interface SourceControlProvider { * Get the current root directory of for the repository. */ root(): Promise; + /** + * Get the current commit message from the source provider. + */ + getCurrentCommitMessage(): Promise; + /** + * Get a list of commits from the source provider to lint. + * + * @param from A string representing the starting commit hash or reference to + * begin retrieving commits from. + * @param to A string representing the ending commit hash or reference to + * stop retrieving commits from. + */ + getCommits(from?: string, to?: string): Promise; } const PROVIDERS = [git, sapling];