From 83204074cef11d000bdcb68d5d339b5b1977ab01 Mon Sep 17 00:00:00 2001 From: Nils Maier Date: Wed, 21 Aug 2019 16:34:30 +0200 Subject: [PATCH] Special path sanitizer for Windows --- lib/util.ts | 37 +++++++++++++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/lib/util.ts b/lib/util.ts index 59b070e..5d983d8 100644 --- a/lib/util.ts +++ b/lib/util.ts @@ -49,7 +49,7 @@ export function lazy(object: any, name: string, fun: (...any: any[]) => T) { export function none() { /* ignored */ } -export const sanitizePath = identity(function sanitizePath(path: string) { +export function sanitizePathGeneric(path: string) { return path. replace(/:+/g, "ː"). replace(/\?+/g, "_"). @@ -61,7 +61,40 @@ export const sanitizePath = identity(function sanitizePath(path: string) { replace(/#+/g, "♯"). replace(/[.\s]+$/g, ""). trim(); -}); +} + +const REG_TRIMMORE = /^[\s.]+|[\s.]+$/g; +const REG_RESERVED = new RegExp( + `^(?:${"CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, LPT9".split(", ").join("|")})(?:\\..*)$`, + "i"); + +export function sanitizePathWindows(path: string) { + path = path. + replace(/:+/g, "ː"). + replace(/\?+/g, "_"). + replace(/\*+/g, "_"). + replace(/<+/g, "◄"). + replace(/>+/g, "▶"). + replace(/"+/g, "'"). + replace(/\|+/g, "¦"). + replace(/#+/g, "♯"). + replace(/[.\s]+$/g, ""). + replace(REG_TRIMMORE, ""); + // Legacy file names + if (REG_RESERVED.test(path)) { + path = `!${path}`; + } + return path; +} + +// Cannot use browser.runtime here +export const IS_WIN = typeof navigator !== "undefined" && + navigator.platform && + navigator.platform.includes("Win"); + + +export const sanitizePath = identity( + IS_WIN ? sanitizePathWindows : sanitizePathGeneric); // XXX cleanup + test export const parsePath = memoize(function parsePath(path: string | URL) {