fix(init): sed behavior on macOS

replace sed by a Node native implementation
This commit is contained in:
Thomas Vaillant
2021-01-19 16:15:07 +01:00
committed by Thomas Vaillant
parent 46bab9ede6
commit 132ef7caad
2 changed files with 36 additions and 18 deletions

View File

@@ -10,6 +10,7 @@ import path from "path";
import moment from "moment-timezone"; import moment from "moment-timezone";
import type { AppConsole } from "@log4brains/cli-common"; import type { AppConsole } from "@log4brains/cli-common";
import { FailureExit } from "@log4brains/cli-common"; import { FailureExit } from "@log4brains/cli-common";
import { replaceAllInFile } from "@src/utils";
const assetsPath = path.resolve(path.join(__dirname, "../../assets")); const assetsPath = path.resolve(path.join(__dirname, "../../assets"));
const docLink = "https://github.com/thomvaill/log4brains"; const docLink = "https://github.com/thomvaill/log4brains";
@@ -230,7 +231,7 @@ export class InitCommand {
adrFolder: string, adrFolder: string,
title: string, title: string,
source: string, source: string,
replacements: string[][] = [] replacements: [string, string][] = []
): Promise<string> { ): Promise<string> {
const slug = ( const slug = (
await execa( await execa(
@@ -247,23 +248,13 @@ export class InitCommand {
) )
).stdout; ).stdout;
// eslint-disable-next-line no-restricted-syntax await replaceAllInFile(
for (const replacement of [ forceUnixPath(path.join(cwd, adrFolder, `${slug}.md`)),
["{DATE_YESTERDAY}", moment().subtract(1, "days").format("YYYY-MM-DD")], // we use yesterday's date so that we are sure new ADRs will appear on top [
...replacements ["{DATE_YESTERDAY}", moment().subtract(1, "days").format("YYYY-MM-DD")], // we use yesterday's date so that we are sure new ADRs will appear on top
]) { ...replacements
await execa( ]
"sed", );
[
"-i",
`s/${replacement[0]}/${replacement[1]}/g`,
forceUnixPath(path.join(cwd, adrFolder, `${slug}.md`))
],
{
cwd
}
);
}
return slug; return slug;
} }

View File

@@ -0,0 +1,27 @@
import { promises as fsP } from "fs";
function escapeRegExp(str: string) {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
}
/**
* string.replaceAll() polyfill
* TODO: remove when support down to Node 15
* @param str
* @param search
* @param replacement
*/
function replaceAll(str: string, search: string, replacement: string): string {
return str.replace(new RegExp(escapeRegExp(search), "g"), replacement);
}
export async function replaceAllInFile(
path: string,
replacements: [string, string][]
): Promise<void> {
let content = await fsP.readFile(path, "utf-8");
content = replacements.reduce((prevContent, replacement) => {
return replaceAll(prevContent, replacement[0], replacement[1]);
}, content);
await fsP.writeFile(path, content, "utf-8");
}