@setoelkahfi / svara / commits / f8b403a

feat: checking for invalid filenames

mellbacon committed Oct 8, 2023 at 20:20 UTC f8b403a74f31c6bab8cc8e77acb14ba2086941e9
1 file changed +18
src/lib/File.ts
+18
@@ -246,3 +246,21 @@ export async function renameFile(filename: string, oldpath: string) {
246 renameTab(tab, filename, newpath);
247 return true;
248 }
249 +
250 +export function checkValidFileName(input: string) {
251 + // refer to https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file for invalid characters
252 + // also https://gist.github.com/doctaphred/d01d05291546186941e1b7ddc02034d3
253 + const invalidChars = `<>:"|?*${path.sep}`;
254 + const invalidKeywords = ["CON", "PRN", "AUX", "NUL", "COM0", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT0", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"];
255 + let nonprintable = new RegExp(/[\x00-\x1F]/); // covers all non printable ascii characters (https://en.wikipedia.org/wiki/Control_character)
256 + for (const c of invalidChars) {
257 + if (input.includes(c)) return false;
258 + }
259 + for (const keyword of invalidKeywords) {
260 + if (input.includes(keyword)) return false;
261 + }
262 + if (nonprintable.test(input)) return false;
263 + if (input.endsWith(".")) return false;
264 + if (input === "") return false;
265 + return true;
266 +}
\ No newline at end of file