Only remove lines from shell scripts if we're sure it's safe to remove

This commit is contained in:
Sander Declerck 2025-08-06 15:08:57 +02:00
parent 56f62240a6
commit df8bb9be74
No known key found for this signature in database
2 changed files with 139 additions and 2 deletions

View file

@ -28,11 +28,35 @@ export function removeLinesMatchingPattern(filePath, pattern) {
}
const fileContent = fs.readFileSync(filePath, "utf-8");
const lines = fileContent.split(os.EOL);
const updatedLines = lines.filter((line) => !pattern.test(line));
const lines = fileContent.split(/[\r\n]+/);
const updatedLines = lines.filter((line) => !shouldRemoveLine(line, pattern));
fs.writeFileSync(filePath, updatedLines.join(os.EOL), "utf-8");
}
const maxLineLength = 100;
function shouldRemoveLine(line, pattern) {
const isPatternMatch = pattern.test(line);
if (!isPatternMatch) {
return false;
}
if (line.length > maxLineLength) {
// safe-chain only adds lines shorter than maxLineLength
// so if the line is longer, it must be from a different
// source and could be dangerous to remove
return false;
}
if (line.includes("\n") || line.includes("\r") || line.includes("\u2028") || line.includes("\u2029")) {
// If the line contains newlines, something has gone wrong in splitting
// \u2028 and \u2029 are Unicode line separator characters (line and paragraph separators)
return false;
}
return true;
}
export function addLineToFile(filePath, line) {
if (!fs.existsSync(filePath)) {
fs.writeFileSync(filePath, "", "utf-8");