-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
git-add.js
70 lines (62 loc) · 2.18 KB
/
git-add.js
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
"use strict";
const fs = require("fs");
const log = require("npmlog");
const path = require("path");
const slash = require("slash");
const { workspaceRoot, readJsonFile } = require("@nrwl/devkit");
const childProcess = require("@lerna/child-process");
module.exports.gitAdd = gitAdd;
let resolvedPrettier;
function resolvePrettier() {
if (!resolvedPrettier) {
try {
// If the workspace has prettier (explicitly) installed, apply it to the updated files
const packageJson = readJsonFile(path.join(workspaceRoot, "package.json"));
const hasPrettier = packageJson.devDependencies?.prettier || packageJson.dependencies?.prettier;
if (!hasPrettier) {
return;
}
const prettierPath = path.join(workspaceRoot, "node_modules", "prettier");
// eslint-disable-next-line import/no-dynamic-require, global-require
resolvedPrettier = require(prettierPath);
} catch {
return;
}
}
return resolvedPrettier;
}
function maybeFormatFile(filePath) {
const prettier = resolvePrettier();
if (!prettier) {
return;
}
const config = resolvedPrettier.resolveConfig.sync(filePath);
try {
const input = fs.readFileSync(filePath, "utf8");
fs.writeFileSync(filePath, resolvedPrettier.format(input, { ...config, filepath: filePath }), "utf8");
log.silly("version", `Successfully applied prettier to updated file: ${filePath}`);
} catch {
log.silly("version", `Failed to apply prettier to updated file: ${filePath}`);
}
}
/**
* @param {string[]} changedFiles
* @param {{ granularPathspec: boolean; }} gitOpts
* @param {import("@lerna/child-process").ExecOpts} execOpts
*/
function gitAdd(changedFiles, gitOpts, execOpts) {
let files = [];
for (const file of changedFiles) {
const filePath = slash(path.relative(execOpts.cwd, path.resolve(execOpts.cwd, file)));
maybeFormatFile(filePath);
if (gitOpts.granularPathspec) {
files.push(filePath);
}
}
// granular pathspecs should be relative to the git root, but that isn't necessarily where lerna lives
if (!gitOpts.granularPathspec) {
files = ".";
}
log.silly("gitAdd", files);
return childProcess.exec("git", ["add", "--", ...files], execOpts);
}