Skip to content

Commit

Permalink
fix(content-docs): suppress git error on multiple occurrences (#6973)
Browse files Browse the repository at this point in the history
  • Loading branch information
felipecrs committed Mar 23, 2022
1 parent b456a64 commit 4b3f568
Show file tree
Hide file tree
Showing 6 changed files with 112 additions and 57 deletions.
8 changes: 7 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,13 @@ module.exports = {
'import/no-unresolved': [
ERROR,
{
ignore: ['^@theme', '^@docusaurus', '^@generated', '^@site'],
ignore: [
'^@theme',
'^@docusaurus',
'^@generated',
'^@site',
'^@testing-utils',
],
},
],
'import/order': OFF,
Expand Down
2 changes: 2 additions & 0 deletions jest.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ export default {
// Using src instead of lib, so we always get fresh source
'@docusaurus/plugin-content-docs/client':
'@docusaurus/plugin-content-docs/src/client/index.ts',

'@testing-utils/(.*)': '<rootDir>/jest/utils/$1.ts',
},
snapshotSerializers: [
'<rootDir>/jest/snapshotPathNormalizer.ts',
Expand Down
63 changes: 63 additions & 0 deletions jest/utils/git.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

import fs from 'fs-extra';
import os from 'os';
import path from 'path';
import shell from 'shelljs';

class Git {
constructor(private dir: string) {
const res = shell.exec('git init', {cwd: dir, silent: true});
if (res.code !== 0) {
throw new Error(`git init exited with code ${res.code}.
stderr: ${res.stderr}
stdout: ${res.stdout}`);
}
// Doesn't matter currently
shell.exec('git config user.email "test@jc-verse.com"', {
cwd: dir,
silent: true,
});
shell.exec('git config user.name "Test"', {cwd: dir, silent: true});

shell.exec('git commit --allow-empty -m "First commit"', {
cwd: dir,
silent: true,
});
}
commit(msg: string, date: string, author: string): void {
const addRes = shell.exec('git add .', {cwd: this.dir, silent: true});
const commitRes = shell.exec(
`git commit -m "${msg}" --date "${date}T00:00:00Z" --author "${author}"`,
{
cwd: this.dir,
env: {GIT_COMMITTER_DATE: `${date}T00:00:00Z`},
silent: true,
},
);
if (addRes.code !== 0) {
throw new Error(`git add exited with code ${addRes.code}.
stderr: ${addRes.stderr}
stdout: ${addRes.stdout}`);
}
if (commitRes.code !== 0) {
throw new Error(`git commit exited with code ${commitRes.code}.
stderr: ${commitRes.stderr}
stdout: ${commitRes.stdout}`);
}
}
}

// This function is sync so the same mock repo can be shared across tests
export function createTempRepo(): {repoDir: string; git: Git} {
const repoDir = fs.mkdtempSync(path.join(os.tmpdir(), 'git-test-repo'));

const git = new Git(repoDir);

return {repoDir, git};
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/

import {createTempRepo} from '@testing-utils/git';
import {jest} from '@jest/globals';
import fs from 'fs-extra';
import path from 'path';
Expand Down Expand Up @@ -69,7 +70,8 @@ describe('getFileLastUpdate', () => {
const consoleMock = jest
.spyOn(console, 'warn')
.mockImplementation(() => {});
const tempFilePath = path.join(__dirname, '__fixtures__', '.temp');
const {repoDir} = createTempRepo();
const tempFilePath = path.join(repoDir, 'file.md');
await fs.writeFile(tempFilePath, 'Lorem ipsum :)');
await expect(getFileLastUpdate(tempFilePath)).resolves.toBeNull();
expect(consoleMock).toHaveBeenCalledTimes(1);
Expand All @@ -79,6 +81,25 @@ describe('getFileLastUpdate', () => {
await fs.unlink(tempFilePath);
});

it('multiple files not tracked by git', async () => {
const consoleMock = jest
.spyOn(console, 'warn')
.mockImplementation(() => {});
const {repoDir} = createTempRepo();
const tempFilePath1 = path.join(repoDir, 'file1.md');
const tempFilePath2 = path.join(repoDir, 'file2.md');
await fs.writeFile(tempFilePath1, 'Lorem ipsum :)');
await fs.writeFile(tempFilePath2, 'Lorem ipsum :)');
await expect(getFileLastUpdate(tempFilePath1)).resolves.toBeNull();
await expect(getFileLastUpdate(tempFilePath2)).resolves.toBeNull();
expect(consoleMock).toHaveBeenCalledTimes(1);
expect(consoleMock).toHaveBeenLastCalledWith(
expect.stringMatching(/not tracked by git./),
);
await fs.unlink(tempFilePath1);
await fs.unlink(tempFilePath2);
});

it('git does not exist', async () => {
const mock = jest.spyOn(shell, 'which').mockImplementationOnce(() => null);
const consoleMock = jest
Expand Down
23 changes: 12 additions & 11 deletions packages/docusaurus-plugin-content-docs/src/lastUpdate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,17 +31,18 @@ export async function getFileLastUpdate(
});
return {timestamp: result.timestamp, author: result.author};
} catch (err) {
if (err instanceof GitNotFoundError && !showedGitRequirementError) {
logger.warn('Sorry, the docs plugin last update options require Git.');
showedGitRequirementError = true;
} else if (
err instanceof FileNotTrackedError &&
!showedFileNotTrackedError
) {
logger.warn(
'Cannot infer the update date for some files, as they are not tracked by git.',
);
showedFileNotTrackedError = true;
if (err instanceof GitNotFoundError) {
if (!showedGitRequirementError) {
logger.warn('Sorry, the docs plugin last update options require Git.');
showedGitRequirementError = true;
}
} else if (err instanceof FileNotTrackedError) {
if (!showedFileNotTrackedError) {
logger.warn(
'Cannot infer the update date for some files, as they are not tracked by git.',
);
showedFileNotTrackedError = true;
}
} else {
logger.warn(err);
}
Expand Down
50 changes: 6 additions & 44 deletions packages/docusaurus-utils/src/__tests__/gitUtils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,51 +8,12 @@
import {FileNotTrackedError, getFileCommitDate} from '../gitUtils';
import fs from 'fs-extra';
import path from 'path';
import os from 'os';
import shell from 'shelljs';
import {createTempRepo} from '@testing-utils/git';

// This function is sync so the same mock repo can be shared across tests
/* eslint-disable no-restricted-properties */
function createTempRepo() {
const repoDir = fs.mkdtempSync(path.join(os.tmpdir(), 'git-test-repo'));
class Git {
constructor(private dir: string) {
const res = shell.exec('git init', {cwd: dir, silent: true});
if (res.code !== 0) {
throw new Error(`git init exited with code ${res.code}.
stderr: ${res.stderr}
stdout: ${res.stdout}`);
}
// Doesn't matter currently
shell.exec('git config user.email "test@jc-verse.com"', {
cwd: dir,
silent: true,
});
shell.exec('git config user.name "Test"', {cwd: dir, silent: true});
}
commit(msg: string, date: string, author: string) {
const addRes = shell.exec('git add .', {cwd: this.dir, silent: true});
const commitRes = shell.exec(
`git commit -m "${msg}" --date "${date}T00:00:00Z" --author "${author}"`,
{
cwd: this.dir,
env: {GIT_COMMITTER_DATE: `${date}T00:00:00Z`},
silent: true,
},
);
if (addRes.code !== 0) {
throw new Error(`git add exited with code ${addRes.code}.
stderr: ${addRes.stderr}
stdout: ${addRes.stdout}`);
}
if (commitRes.code !== 0) {
throw new Error(`git commit exited with code ${commitRes.code}.
stderr: ${commitRes.stderr}
stdout: ${commitRes.stdout}`);
}
}
}
const git = new Git(repoDir);
function initializeTempRepo() {
const {repoDir, git} = createTempRepo();

fs.writeFileSync(path.join(repoDir, 'test.txt'), 'Some content');
git.commit(
'Create test.txt',
Expand All @@ -79,11 +40,12 @@ stdout: ${commitRes.stdout}`);
'Josh-Cena <josh-cena@jc-verse.com>',
);
fs.writeFileSync(path.join(repoDir, 'untracked.txt'), "I'm untracked");

return repoDir;
}

describe('getFileCommitDate', () => {
const repoDir = createTempRepo();
const repoDir = initializeTempRepo();
it('returns earliest commit date', async () => {
expect(getFileCommitDate(path.join(repoDir, 'test.txt'), {})).toEqual({
date: new Date('2020-06-19'),
Expand Down

0 comments on commit 4b3f568

Please sign in to comment.