From 260874fa1ddbb09279942bdeec9454c4d2b615e8 Mon Sep 17 00:00:00 2001 From: Eric Amodio Date: Sun, 10 Sep 2017 17:44:26 -0400 Subject: [PATCH] Adds better filename sanitization --- src/git/git.ts | 4 ++-- src/system/string.ts | 16 ++++++++++++---- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/src/git/git.ts b/src/git/git.ts index 495e581..88b8b5d 100644 --- a/src/git/git.ts +++ b/src/git/git.ts @@ -1,4 +1,5 @@ 'use strict'; +import { Strings } from '../system'; import { findGitPath, IGit } from './gitLocator'; import { Logger } from '../logger'; import { spawnPromise } from 'spawn-rx'; @@ -99,8 +100,7 @@ export class Git { static async getVersionedFile(repoPath: string | undefined, fileName: string, branchOrSha: string) { const data = await Git.show(repoPath, fileName, branchOrSha, 'binary'); - // TODO: Sanitize the filename - const suffix = Git.isSha(branchOrSha) ? Git.shortenSha(branchOrSha) : branchOrSha.replace(/\\/g, '_').replace(/\//g, '_'); + const suffix = Strings.truncate(Strings.sanitizeForFS(Git.isSha(branchOrSha) ? Git.shortenSha(branchOrSha) : branchOrSha), 50, ''); const ext = path.extname(fileName); return new Promise((resolve, reject) => { tmp.file({ prefix: `${path.basename(fileName, ext)}-${suffix}__`, postfix: ext }, diff --git a/src/system/string.ts b/src/system/string.ts index d7d584f..8676b06 100644 --- a/src/system/string.ts +++ b/src/system/string.ts @@ -101,12 +101,20 @@ export namespace Strings { return s; } - export function truncate(s: string, truncateTo?: number) { - if (!s || truncateTo === undefined) return s; + // Removes \ / : * ? " < > | and C0 and C1 control codes + const illegalCharsForFSRegEx = /[\\/:*?"<>|\x00-\x1f\x80-\x9f]/g; + + export function sanitizeForFS(s: string, replacement: string = '_') { + if (!s) return s; + return s.replace(illegalCharsForFSRegEx, replacement); + } + + export function truncate(s: string, truncateTo: number, ellipsis: string = '\u2026') { + if (!s) return s; const len = getWidth(s); if (len <= truncateTo) return s; - if (len === s.length) return `${s.substring(0, truncateTo - 1)}\u2026`; + if (len === s.length) return `${s.substring(0, truncateTo - 1)}${ellipsis}`; // Skip ahead to start as far as we can by assuming all the double-width characters won't be truncated let chars = Math.floor(truncateTo / (len / s.length)); @@ -119,6 +127,6 @@ export namespace Strings { chars--; } - return `${s.substring(0, chars)}\u2026`; + return `${s.substring(0, chars)}${ellipsis}`; } } \ No newline at end of file