Skip to content

Commit

Permalink
feat: add fs.sanitizeFilename method
Browse files Browse the repository at this point in the history
  • Loading branch information
sahachide committed Oct 14, 2020
1 parent b4e02ec commit f4a4eff
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/filesystem/FS.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@ import { log } from '../log/logger'
import { promises } from 'fs'
import { readDirRecursive } from './readDirRecursiveGenerator'

const illegalRegEx = /[/?<>\\:*|"]/g
// eslint-disable-next-line no-control-regex
const controlRegEx = /[\x00-\x1f\x80-\x9f]/g
const reservedRegEx = /^\.+$/
const windowsReservedRegEx = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i
const windowsTrailingRegEx = /[. ]+$/

export abstract class fs {
// @ts-ignore
public static isTsNode = !!process[Symbol.for('ts-node.register.instance')]
Expand Down Expand Up @@ -75,6 +82,17 @@ export abstract class fs {
return !this.isDev() ? `${filename}.js` : `${filename}.ts`
}

public static sanitizeFilename(filename: string): string {
const sanitized = filename
.replace(illegalRegEx, '')
.replace(controlRegEx, '')
.replace(reservedRegEx, '')
.replace(windowsReservedRegEx, '')
.replace(windowsTrailingRegEx, '')

return sanitized.substring(0, 255)
}

public static appDir(): string {
return appDir
}
Expand Down

0 comments on commit f4a4eff

Please sign in to comment.