All files gitLogScraper.ts

100% Statements 83/83
88.24% Branches 30/34
100% Functions 10/10
100% Lines 83/83

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206                      1x   1x                                       7x 7x 7x   6102x   844x   7x   7x                   4x 4x   4x   4x 4x                 4x       4x   4x       4x 4x     4x 4x 4x                           4x 4x       7x 7x 7x 7x     7x             11x 11x 88x   11x 11x       23x       15x 15x 15x   15x 15x   15x 15x 15x     15x 867x 15x   852x 852x 852x 852x   852x 852x 852x     15x   13854x 13854x 852x 852x 852x           852x   13002x 13002x   5996x 5996x 852x   5996x 5964x 5964x 5964x     7038x 5804x 5804x 5804x 5804x 5804x   5804x 5804x 5804x         1234x 390x     15x 15x   15x    
import * as fs from 'fs';
import * as path from 'path';
 
import {
  findGitRoot,
  escapeForCli,
  execSync,
  safelyParseInt,
} from '@git-temporal/commons';
import { createProxies } from '@git-temporal/logger';
 
const { debug } = createProxies('git-log-scraper');
 
const parsedAttributes = {
  id: '%H%n',
  hash: '%h%n',
  authorName: '%an%n',
  authorEmail: '%ae%n',
  relativeDate: '%cr%n',
  authorDate: '%at%n',
  message: '%s%n',
  body: '%b',
};
 
export interface IGetCommitHistoryOptions {
  skip?: number;
  maxCount?: number;
}
 
export function getCommitHistory(
  path: string,
  options: IGetCommitHistoryOptions = { skip: 0, maxCount: 0 }
) {
  const { skip, maxCount } = options;
  const rawLog = fetchFileHistory(path, skip, maxCount);
  const commits = parseGitLogOutput(rawLog)
    .sort((a, b) => {
      return b.authorDate - a.authorDate;
    })
    .map((c, i) => ({ ...c, index: skip + i }));
 
  const isFile = fs.existsSync(path) && !fs.lstatSync(path).isDirectory();
 
  return {
    isFile,
    commits,
    skip,
    maxCount,
    path,
  };
}
 
export function getCommitRange(fileName: string) {
  const gitRoot = findGitRoot(fileName);
  const logFlags = gitLogFlags({ follow: false });
 
  debug('getCommitRange', { fileName, gitRoot, logFlags });
 
  const cmdFileName = fileName === gitRoot ? '.' : fileName;
  const allRevHashes = execGit(
    gitRoot,
    `log --pretty="format:%H" --topo-order --date=local -- ${escapeForCli(
      cmdFileName
    )}`
  ).split('\n');
 
  // debug('allRevHashes', allRevHashes);
 
  const firstCommitRaw = execGit(
    gitRoot,
    `log ${logFlags} -n1 ${allRevHashes[allRevHashes.length - 1]}`
  );
  const firstCommit = parseGitLogOutput(firstCommitRaw)[0];
 
  const lastCommitRaw = execGit(
    gitRoot,
    `log ${logFlags} -n 1 -- ${escapeForCli(fileName)}`
  );
  const lastCommit = parseGitLogOutput(lastCommitRaw)[0];
  const absoluteFileName = fileName.startsWith(gitRoot)
    ? fileName
    : path.resolve(gitRoot, fileName);
  const existsLocally = fs.existsSync(absoluteFileName);
  const hasChanges = existsLocally && hasUncommitedChanges(gitRoot, fileName);
  return {
    gitRoot,
    firstCommit,
    lastCommit,
    existsLocally,
    count: allRevHashes.length,
    path: fileName,
    hasUncommittedChanges: hasChanges,
  };
}
 
// Implementation
 
function hasUncommitedChanges(gitroot: string, fileName: string) {
  const statusRaw = execGit(gitroot, `status ${fileName}`);
  return statusRaw.match(/(new\sfile|modified|deleted)\:/i) !== null;
}
 
function fetchFileHistory(fileName: string, skip: number, maxCount: number) {
  const gitRoot = findGitRoot(fileName);
  const flags = gitLogFlags();
  const skipFlag = skip ? ` --skip=${skip}` : '';
  const countFlag = maxCount ? ` -n ${maxCount}` : '';
 
  // use -- fileName and git log will work on deleted files and paths
  return execGit(
    gitRoot,
    `log ${flags}${skipFlag}${countFlag} -- ${escapeForCli(fileName)}`
  );
}
 
function gitLogFlags(options = { follow: true }) {
  let format = '';
  for (const attr in parsedAttributes) {
    format += `${attr}:${parsedAttributes[attr]}`;
  }
  const follow = false && options.follow ? ' --follow' : '';
  return `--pretty=\"format:${format}\" --topo-order --date=local --numstat ${follow}`;
}
 
function execGit(gitRoot, gitCmd) {
  return execSync(`git ${gitCmd}`, { cwd: gitRoot, logFn: debug });
}
 
function parseGitLogOutput(output) {
  const logItems = [];
  const logLines = output.split(/\n\r?/);
  let commitIndex = 0;
 
  let currentlyParsingAttr = null;
  let parsedValue = null;
 
  let commitObj = null;
  let totalLinesAdded = 0;
  let totalLinesDeleted = 0;
  // let lineNumber = 0;
 
  const addLogItem = () => {
    if (!commitObj) {
      return;
    }
    commitObj.linesAdded = totalLinesAdded;
    commitObj.linesDeleted = totalLinesDeleted;
    commitObj.index = commitIndex;
    logItems.push(commitObj);
 
    totalLinesAdded = 0;
    totalLinesDeleted = 0;
    commitIndex += 1;
  };
 
  for (const line of logLines) {
    // lineNumber += 1;
    let matches = line.match(/^id\:(.*)/);
    if (matches) {
      currentlyParsingAttr = 'id';
      addLogItem();
      commitObj = {
        id: matches[1],
        files: [],
        body: '',
        message: '',
      };
      continue;
    }
    matches = line.match(/^([^\:]+):(.*)/);
    if (matches) {
      let attr: string;
      [, attr, parsedValue] = matches;
      if (attr === 'authorDate') {
        parsedValue = parseInt(parsedValue, 10);
      }
      if (Object.keys(parsedAttributes).includes(attr)) {
        currentlyParsingAttr = attr;
        commitObj[currentlyParsingAttr] = parsedValue;
        continue;
      }
    }
    if ((matches = line.match(/^([\d\-]+)\s+([\d\-]+)\s+(.*)/))) {
      let [linesAdded, linesDeleted, fileName] = matches.slice(1);
      linesAdded = safelyParseInt(linesAdded);
      linesDeleted = safelyParseInt(linesDeleted);
      fileName = fileName.trim();
      currentlyParsingAttr = 'files';
 
      totalLinesAdded += linesAdded;
      totalLinesDeleted += linesDeleted;
      commitObj.files.push({
        linesAdded,
        linesDeleted,
        name: fileName,
      });
    } else if (currentlyParsingAttr === 'body') {
      commitObj.body += `<br>${line}`;
    }
  }
  Eif (commitObj) {
    addLogItem();
  }
  return logItems;
}