docusaurus/packages/docusaurus-plugin-content-docs/src/lastUpdate.ts
Sébastien Lorber a4c8a7f55b
refactor(v2): docs plugin refactor (#3245)
* safe refactorings

* safe refactors

* add code to read versions more generically

* refactor docs plugin

* refactors

* stable docs refactor

* progress on refactor

* stable docs refactor

* stable docs refactor

* stable docs refactor

* attempt to fix admonition :(

* configureWebpack docs: better typing

* more refactors

* rename cli

* refactor docs metadata processing => move to pure function

* stable docs refactor

* stable docs refactor

* named exports

* basic sidebars refactor

* add getElementsAround utils

* refactor sidebar + ordering/navigation logic

* stable retrocompatible refactor

* add proper versions metadata tests

* fix docs metadata tests

* fix docs tests

* fix test due to absolute path

* fix webpack tests

* refactor linkify + add broken markdown links warning

* fix DOM warning due to forwarding legacy prop to div element

* add todo
2020-08-17 17:50:22 +02:00

58 lines
1.4 KiB
TypeScript

/**
* 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 shell from 'shelljs';
import execa from 'execa';
type FileLastUpdateData = {timestamp?: number; author?: string};
const GIT_COMMIT_TIMESTAMP_AUTHOR_REGEX = /^(\d+), (.+)$/;
let showedGitRequirementError = false;
export async function getFileLastUpdate(
filePath?: string,
): Promise<FileLastUpdateData | null> {
if (!filePath) {
return null;
}
function getTimestampAndAuthor(str: string): FileLastUpdateData | null {
if (!str) {
return null;
}
const temp = str.match(GIT_COMMIT_TIMESTAMP_AUTHOR_REGEX);
return !temp || temp.length < 3
? null
: {timestamp: +temp[1], author: temp[2]};
}
// Wrap in try/catch in case the shell commands fail
// (e.g. project doesn't use Git, etc).
try {
if (!shell.which('git')) {
if (!showedGitRequirementError) {
showedGitRequirementError = true;
console.warn('Sorry, the docs plugin last update options require Git.');
}
return null;
}
const {stdout} = await execa('git', [
'log',
'-1',
'--format=%ct, %an',
filePath,
]);
return getTimestampAndAuthor(stdout);
} catch (error) {
console.error(error);
}
return null;
}