fix: improve last updated time feature (#1036)

This commit is contained in:
Yangshun Tay 2018-10-14 15:05:00 -07:00 committed by GitHub
parent ff11d17625
commit b577f60d4a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 58 additions and 39 deletions

View file

@ -38,38 +38,46 @@ function idx(target, keyPaths) {
);
}
function isNormalInteger(str) {
return /^\d+$/.test(str);
}
function getGitLastUpdated(filepath) {
// To differentiate between content change and file renaming / moving, use --summary
// To follow the file history until before it is moved (when we create new version), use
// --follow
const silentState = shell.config.silent; // save old silent state
shell.config.silent = true;
const result = shell
.exec(`git log --follow --summary --format=%ct ${filepath}`)
.stdout.trim();
shell.config.silent = silentState;
// Format the log results to be ['1234567', 'rename ...', '1234566', 'move ...', '1234565', '1234564']
const records = result
.toString('utf-8')
.replace(/\n\s*\n/g, '\n')
.split('\n')
.filter(String);
const timeSpan = records.find((item, index, arr) => {
const isTimestamp = isNormalInteger(item);
const isLastTwoItem = index + 2 >= arr.length;
const nextItemIsTimestamp = isNormalInteger(arr[index + 1]);
return isTimestamp && (isLastTwoItem || nextItemIsTimestamp);
});
if (timeSpan) {
const date = new Date(parseInt(timeSpan, 10) * 1000);
return date.toLocaleString();
function isTimestamp(str) {
return /^\d+$/.test(str);
}
// Wrap in try/catch in case the shell commands fail (e.g. project doesn't use Git, etc).
try {
// To differentiate between content change and file renaming / moving, use --summary
// To follow the file history until before it is moved (when we create new version), use
// --follow.
const silentState = shell.config.silent; // Save old silent state.
shell.config.silent = true;
const result = shell
.exec(`git log --follow --summary --format=%ct ${filepath}`)
.stdout.trim();
shell.config.silent = silentState;
// Format the log results to be
// ['1234567', 'rename ...', '1234566', 'move ...', '1234565', '1234564']
const records = result
.toString('utf-8')
.replace(/\n\s*\n/g, '\n')
.split('\n')
.filter(String);
const timeSpan = records.find((item, index, arr) => {
const currentItemIsTimestamp = isTimestamp(item);
const isLastTwoItem = index + 2 >= arr.length;
const nextItemIsTimestamp = isTimestamp(arr[index + 1]);
return currentItemIsTimestamp && (isLastTwoItem || nextItemIsTimestamp);
});
if (timeSpan) {
const date = new Date(parseInt(timeSpan, 10) * 1000);
return date.toLocaleString();
}
} catch (error) {
console.error(error);
}
return null;
}