【问题标题】:Exclude files from Danger.js addittions and deletions从 Danger.js 添加和删除中排除文件
【发布时间】:2020-12-21 17:22:32
【问题描述】:
我们正在尝试在我们的 prs 中设置最大行更改,但注意到有一些元文件很容易超过此限制,例如 yarn.lock。
有谁知道如何将文件排除在添加和删除之外?
// ...
const linesAdded = danger.github.pr.additions || 0;
const linesRemoved = danger.github.pr.deletions || 0;
// ...
if (linesAdded + linesRemoved > bigPRThreshold) {
fail(
`This PR size is too large (Over ${bigPRThreshold} lines. Please split into separate PRs to enable faster & easier review.`
);
}
// ...
【问题讨论】:
标签:
node.js
github
danger
【解决方案1】:
我发现了以下 gitDSL 函数来访问单个文件中的信息
//This should make it really easy to do work when specific keypaths have changed inside a JSON file.
JSONDiffForFile(filename: string) => Promise
// Provides a JSON patch (rfc6902) between the two versions of a JSON file, returns null if you don't have any changes for the file in the diff.
// Note that if you are looking to just see changes like: before, after, added or removed - you should use `JSONDiffForFile` instead, as this can be a bit unwieldy for a Dangerfile.
JSONPatchForFile(filename: string) => Promise
// Offers the diff for a specific file
diffForFile(filename: string) => Promise
// Offers the overall lines of code added/removed in the diff
linesOfCode() => Promise
// Offers the structured diff for a specific file
structuredDiffForFile(filename: string) => Promise
(有关这些功能的文档:https://danger.systems/js/reference.html#GitDSL)
有了danger.git.structuredDiffForFile,我可以计算出我想排除的行
const file = 'yarn.lock';
const diff1 = await danger.git.structuredDiffForFile(file);
const excludedLines = diff1.chunks[0].changes.length
【解决方案2】:
这很好用:
import { markdown, message, danger, warn } from "danger";
import minimatch from "minimatch";
const pr = danger.github.pr;
const modifiedFiles = danger.git.modified_files;
(async function () {
// Encourage smaller PRs
await checkPRSize();
})();
async function checkPRSize() {
const MAX_ADDITIONS_COUNT = 500;
const ignoredLineCount = await getIgnoredLineCount();
if (pr.additions - ignoredLineCount > MAX_ADDITIONS_COUNT) {
warn("Its too big!");
}
}
// Get the number of additions in files that we want to ignore
// so that we can subtract them from the total additions
// Use a glob to match multiple files in different location
async function getIgnoredLineCount(): Promise<number> {
let ignoredLineCount = 0;
const IGNORE_FILE_GLOB = "**/*+(.schema.json|package.lock)";
const ignoredFiles = modifiedFiles.filter((file) =>
minimatch(file, IGNORE_FILE_GLOB)
);
await Promise.all(
ignoredFiles.map(async (file) => {
const diff = await danger.git.structuredDiffForFile(file);
diff.chunks.map((chunk) => {
// Here we filter to only get the additions
const additions = chunk.changes.filter(({ type }) => type === "add");
ignoredLineCount = ignoredLineCount + additions.length;
});
})
);
return ignoredLineCount;
}