Skip to content

Commit

Permalink
preserve cross-platform EOF newline when writing package.json (#9)
Browse files Browse the repository at this point in the history
  • Loading branch information
cody-dot-js authored Aug 18, 2024
1 parent dc5394d commit 78c333e
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 7 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@ngrok/gen-x",
"version": "0.0.5",
"version": "0.0.6",
"description": "Generate package.json#exports from src",
"author": "ngrok",
"repository": {
Expand Down
2 changes: 1 addition & 1 deletion src/meta.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@

export const packageName = "@ngrok/gen-x";

export const packageVersion = "0.0.5";
export const packageVersion = "0.0.6";
20 changes: 15 additions & 5 deletions src/update-package-json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,30 +24,40 @@ type Args = {
*/
async function updatePackageJson({ dryRun = false, exports, packageJsonPath }: Args) {
// read the package.json file
const packageJsonFile = await fs.readFile(packageJsonPath, "utf8");
const originalPackageJsonFile = await fs.readFile(packageJsonPath, "utf8");

// convert the package.json file to a JSON object
const currentPackageJson = JSON.parse(packageJsonFile) as Record<string, unknown>;
const originalPackageJson = JSON.parse(originalPackageJsonFile) as Record<string, unknown>;

// delete the exports field from the package.json object so it is always at the end
delete currentPackageJson.exports;
delete originalPackageJson.exports;

// set the exports field to the new exports object
const updatedPackageJson = {
...currentPackageJson,
...originalPackageJson,
exports,
};

// don't write to disk if dry run is set, just preview the changes in stdout
if (dryRun) {
console.log("Dry run:");
console.log(updatedPackageJson);
return;
}

console.log(`Writing exports to ${packageJsonPath}`);

// stringify the updated package.json object
const data = JSON.stringify(updatedPackageJson, null, 2);
let data = JSON.stringify(updatedPackageJson, null, 2);

// preserve cross-platform EOF newline if original package.json file has one
let eofNewline = "";
if (originalPackageJsonFile.endsWith("\r\n")) {
eofNewline = "\r\n"; // Windows-style newline
} else if (originalPackageJsonFile.endsWith("\n")) {
eofNewline = "\n"; // Unix-style newline
}
data += eofNewline;

// write the updated package.json file
await fs.writeFile(packageJsonPath, data, "utf8");
Expand Down

0 comments on commit 78c333e

Please sign in to comment.