diff --git a/src/git-utils.test.ts b/src/git-utils.test.ts index 06837e022..67c521356 100644 --- a/src/git-utils.test.ts +++ b/src/git-utils.test.ts @@ -1,4 +1,5 @@ import * as fs from "fs"; +import * as os from "os"; import * as path from "path"; import * as core from "@actions/core"; @@ -392,3 +393,41 @@ test("getFileOidsUnderPath throws on unexpected output format", async (t) => { runGitCommandStub.restore(); } }); + +test("listFiles returns array of file paths", async (t) => { + sinon + .stub(gitUtils, "runGitCommand") + .resolves(["dir/file.txt", "README.txt"].join(os.EOL)); + + await t.notThrowsAsync(async () => { + const result = await gitUtils.listFiles("/some/path"); + t.is(result.length, 2); + t.is(result[0], "dir/file.txt"); + }); +}); + +test("getGeneratedFiles returns generated files only", async (t) => { + const runGitCommandStub = sinon.stub(gitUtils, "runGitCommand"); + + runGitCommandStub + .onFirstCall() + .resolves(["dir/file.txt", "test.json", "README.txt"].join(os.EOL)); + runGitCommandStub + .onSecondCall() + .resolves( + [ + "dir/file.txt: linguist-generated: unspecified", + "test.json: linguist-generated: true", + "README.txt: linguist-generated: false", + ].join(os.EOL), + ); + + await t.notThrowsAsync(async () => { + const result = await gitUtils.getGeneratedFiles("/some/path"); + + t.assert(runGitCommandStub.calledTwice); + + t.is(result.length, 1); + t.is(result[0], "test.json"); + }); +}); diff --git a/src/git-utils.ts b/src/git-utils.ts index 837124027..eb1151521 100644 --- a/src/git-utils.ts +++ b/src/git-utils.ts @@ -1,3 +1,5 @@ +import * as os from "os"; + import * as core from "@actions/core"; import * as toolrunner from "@actions/exec/lib/toolrunner"; import * as io from "@actions/io"; @@ -408,3 +410,34 @@ export async function isAnalyzingDefaultBranch(): Promise { return currentRef === defaultBranch; } + +export async function listFiles(workingDirectory: string): Promise { + const stdout = await runGitCommand( + workingDirectory, + ["ls-files"], + "Unable to list tracked files.", + ); + return stdout.split(os.EOL); +} + +export async function getGeneratedFiles( + workingDirectory: string, +): Promise { + const files = await listFiles(workingDirectory); + const stdout = await runGitCommand( + workingDirectory, + ["check-attr", "linguist-generated", "--", ...files], + "Unable to check attributes of files.", + ); + + const generatedFiles: string[] = []; + const regex = /^([^:]+): linguist-generated: true$/; + for (const result of stdout.split(os.EOL)) { + const match = result.match(regex); + if (match) { + generatedFiles.push(match[1]); + } + } + + return generatedFiles; +}