Browse Source

Adds better filename sanitization

main
Eric Amodio 7 years ago
parent
commit
260874fa1d
2 changed files with 14 additions and 6 deletions
  1. +2
    -2
      src/git/git.ts
  2. +12
    -4
      src/system/string.ts

+ 2
- 2
src/git/git.ts View File

@ -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<string>((resolve, reject) => {
tmp.file({ prefix: `${path.basename(fileName, ext)}-${suffix}__`, postfix: ext },

+ 12
- 4
src/system/string.ts View File

@ -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}`;
}
}

Loading…
Cancel
Save