Skip to content
This repository has been archived by the owner on Nov 28, 2024. It is now read-only.

Commit

Permalink
fix: restrict filename length & prevent overwriting files with dup. n…
Browse files Browse the repository at this point in the history
…ames

Summary:
- File name (without the extension) is restricted to 40 chars
- If the file name already exists, a short hash based on the file
contents will be added to the file name
  • Loading branch information
rhamzeh authored and vHanda committed Aug 26, 2021
1 parent cbc8417 commit 0dc8226
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
20 changes: 19 additions & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#!/usr/bin/env node

import * as fs from "fs";
import { createHash } from "crypto";
import * as path from "path";
import * as tmp from "tmp";
import { promisify } from "util";
Expand Down Expand Up @@ -96,7 +97,24 @@ function convertNote(filePath: string, outputDir: string): boolean {
var output = serialize(note);

output.forEach(out => {
fs.writeFileSync(path.join(outputDir, out.fileName), out.content);
let outputPath = path.join(outputDir, out.fileName);
if (fs.existsSync(outputPath)) {
const ext = path.extname(outputPath)
const fileNameWithoutExt = out.fileName.replace(
new RegExp(ext + '$'),
''
)
const fileHash = createHash('sha256')
fileHash.update(out.content)
const digest = fileHash
.digest("base64")
.replace(/[^A-Za-z0-9]/g, "")
.substring(0, 4);
const newFileName = `${fileNameWithoutExt}-${digest}${ext}`;
outputPath = path.join(outputDir, newFileName);
}

fs.writeFileSync(outputPath, out.content);
});

return output.length > 0;
Expand Down
6 changes: 4 additions & 2 deletions src/serializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ var uuidV4 = require("uuid/v4");
import * as yaml from "js-yaml";
import { Note } from "./types";

const MAX_FILENAME_LENGTH = 40;

interface SerializedNote {
fileName: string;
content: string | Buffer;
Expand Down Expand Up @@ -61,11 +63,11 @@ function generateFilename(note: Note) {
else newStr += char;
}
}
return newStr;
return newStr.substring(0, MAX_FILENAME_LENGTH);
}
const firstLine = note.content.trim().split('\n')[0];
return sanitizeString(
note.title || firstLine || note.date || uuidV4())
note.title || firstLine || note.date || uuidV4())
+ ".md";
}

Expand Down

0 comments on commit 0dc8226

Please sign in to comment.