Skip to content

Commit

Permalink
fix: make git diff relative to current working directory (#11)
Browse files Browse the repository at this point in the history
* fix: make git diff relative to current working directory

* fix test

* add extra test to ensure it works with both relative and absolute cwd path

* refactor path resolving of cwd for git diff command

---------

Co-authored-by: Yann-Fanch GUYOT <[email protected]>
  • Loading branch information
mamatsunami and Yann-Fanch GUYOT authored Jun 29, 2023
1 parent 3c2c916 commit a563fdf
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
17 changes: 16 additions & 1 deletion libs/core/src/git.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { readFile, writeFile } from 'fs/promises';
import * as childProcess from 'node:child_process';

const cwd = 'libs/core/src/__fixtures__/git';
const absoluteCwd = resolve(cwd);
const branch = 'main';

describe('git', () => {
Expand Down Expand Up @@ -115,7 +116,7 @@ describe('git', () => {
});

describe('getChangedFiles', () => {
it('should return changed files with line numbers', () => {
it('should return changed files with line numbers from relative cwd path', () => {
const changedFiles = getChangedFiles({
base: branch,
cwd,
Expand All @@ -129,6 +130,20 @@ describe('git', () => {
]);
});

it('should return changed files with line numbers from absolute cwd path', () => {
const changedFiles = getChangedFiles({
base: branch,
cwd: absoluteCwd,
});

expect(changedFiles).toEqual([
{
filePath: 'index.ts',
changedLines: [3],
},
]);
});

it('should return empty array if no files changed', async () => {
await restoreFile();

Expand Down
7 changes: 6 additions & 1 deletion libs/core/src/git.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { execSync } from 'node:child_process';
import { resolve } from 'node:path';

const TEN_MEGABYTES = 1024 * 10000;

Expand Down Expand Up @@ -41,7 +42,11 @@ export function getMergeBase({

export function getDiff({ base, cwd }: BaseGitActionArgs): string {
try {
return execSync(`git diff ${base} --unified=0`, {
const diffCommand = cwd
? `git diff ${base} --unified=0 --relative -- ${resolve(cwd)}`
: `git diff ${base} --unified=0 `;

return execSync(diffCommand, {
maxBuffer: TEN_MEGABYTES,
cwd,
stdio: 'pipe',
Expand Down

0 comments on commit a563fdf

Please sign in to comment.