fix(content-docs): suppress git error on multiple occurrences (#6973)

This commit is contained in:
Felipe Santos 2022-03-23 12:35:26 -03:00 committed by GitHub
parent b456a64f61
commit 4b3f568b78
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 112 additions and 57 deletions

View file

@ -202,7 +202,13 @@ module.exports = {
'import/no-unresolved': [ 'import/no-unresolved': [
ERROR, ERROR,
{ {
ignore: ['^@theme', '^@docusaurus', '^@generated', '^@site'], ignore: [
'^@theme',
'^@docusaurus',
'^@generated',
'^@site',
'^@testing-utils',
],
}, },
], ],
'import/order': OFF, 'import/order': OFF,

View file

@ -60,6 +60,8 @@ export default {
// Using src instead of lib, so we always get fresh source // Using src instead of lib, so we always get fresh source
'@docusaurus/plugin-content-docs/client': '@docusaurus/plugin-content-docs/client':
'@docusaurus/plugin-content-docs/src/client/index.ts', '@docusaurus/plugin-content-docs/src/client/index.ts',
'@testing-utils/(.*)': '<rootDir>/jest/utils/$1.ts',
}, },
snapshotSerializers: [ snapshotSerializers: [
'<rootDir>/jest/snapshotPathNormalizer.ts', '<rootDir>/jest/snapshotPathNormalizer.ts',

63
jest/utils/git.ts vendored Normal file
View file

@ -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};
}

View file

@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree. * LICENSE file in the root directory of this source tree.
*/ */
import {createTempRepo} from '@testing-utils/git';
import {jest} from '@jest/globals'; import {jest} from '@jest/globals';
import fs from 'fs-extra'; import fs from 'fs-extra';
import path from 'path'; import path from 'path';
@ -69,7 +70,8 @@ describe('getFileLastUpdate', () => {
const consoleMock = jest const consoleMock = jest
.spyOn(console, 'warn') .spyOn(console, 'warn')
.mockImplementation(() => {}); .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 fs.writeFile(tempFilePath, 'Lorem ipsum :)');
await expect(getFileLastUpdate(tempFilePath)).resolves.toBeNull(); await expect(getFileLastUpdate(tempFilePath)).resolves.toBeNull();
expect(consoleMock).toHaveBeenCalledTimes(1); expect(consoleMock).toHaveBeenCalledTimes(1);
@ -79,6 +81,25 @@ describe('getFileLastUpdate', () => {
await fs.unlink(tempFilePath); 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 () => { it('git does not exist', async () => {
const mock = jest.spyOn(shell, 'which').mockImplementationOnce(() => null); const mock = jest.spyOn(shell, 'which').mockImplementationOnce(() => null);
const consoleMock = jest const consoleMock = jest

View file

@ -31,17 +31,18 @@ export async function getFileLastUpdate(
}); });
return {timestamp: result.timestamp, author: result.author}; return {timestamp: result.timestamp, author: result.author};
} catch (err) { } catch (err) {
if (err instanceof GitNotFoundError && !showedGitRequirementError) { if (err instanceof GitNotFoundError) {
logger.warn('Sorry, the docs plugin last update options require Git.'); if (!showedGitRequirementError) {
showedGitRequirementError = true; logger.warn('Sorry, the docs plugin last update options require Git.');
} else if ( showedGitRequirementError = true;
err instanceof FileNotTrackedError && }
!showedFileNotTrackedError } else if (err instanceof FileNotTrackedError) {
) { if (!showedFileNotTrackedError) {
logger.warn( logger.warn(
'Cannot infer the update date for some files, as they are not tracked by git.', 'Cannot infer the update date for some files, as they are not tracked by git.',
); );
showedFileNotTrackedError = true; showedFileNotTrackedError = true;
}
} else { } else {
logger.warn(err); logger.warn(err);
} }

View file

@ -8,51 +8,12 @@
import {FileNotTrackedError, getFileCommitDate} from '../gitUtils'; import {FileNotTrackedError, getFileCommitDate} from '../gitUtils';
import fs from 'fs-extra'; import fs from 'fs-extra';
import path from 'path'; import path from 'path';
import os from 'os'; import {createTempRepo} from '@testing-utils/git';
import shell from 'shelljs';
// This function is sync so the same mock repo can be shared across tests
/* eslint-disable no-restricted-properties */ /* eslint-disable no-restricted-properties */
function createTempRepo() { function initializeTempRepo() {
const repoDir = fs.mkdtempSync(path.join(os.tmpdir(), 'git-test-repo')); const {repoDir, git} = createTempRepo();
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);
fs.writeFileSync(path.join(repoDir, 'test.txt'), 'Some content'); fs.writeFileSync(path.join(repoDir, 'test.txt'), 'Some content');
git.commit( git.commit(
'Create test.txt', 'Create test.txt',
@ -79,11 +40,12 @@ stdout: ${commitRes.stdout}`);
'Josh-Cena <josh-cena@jc-verse.com>', 'Josh-Cena <josh-cena@jc-verse.com>',
); );
fs.writeFileSync(path.join(repoDir, 'untracked.txt'), "I'm untracked"); fs.writeFileSync(path.join(repoDir, 'untracked.txt'), "I'm untracked");
return repoDir; return repoDir;
} }
describe('getFileCommitDate', () => { describe('getFileCommitDate', () => {
const repoDir = createTempRepo(); const repoDir = initializeTempRepo();
it('returns earliest commit date', async () => { it('returns earliest commit date', async () => {
expect(getFileCommitDate(path.join(repoDir, 'test.txt'), {})).toEqual({ expect(getFileCommitDate(path.join(repoDir, 'test.txt'), {})).toEqual({
date: new Date('2020-06-19'), date: new Date('2020-06-19'),