Skip to content

Commit

Permalink
refactor(utils): add leading dot segment removal utility
Browse files Browse the repository at this point in the history
  • Loading branch information
mrmlnc committed Feb 21, 2020
1 parent 2466aea commit 8851e0f
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/utils/path.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,23 @@ describe('Utils → Path', () => {
assert.strictEqual(util.escape('abc@'), 'abc@');
});
});

describe('.removeLeadingDotCharacters', () => {
it('should return path without changes', () => {
assert.strictEqual(util.removeLeadingDotSegment('../a/b'), '../a/b');
assert.strictEqual(util.removeLeadingDotSegment('~/a/b'), '~/a/b');
assert.strictEqual(util.removeLeadingDotSegment('/a/b'), '/a/b');
assert.strictEqual(util.removeLeadingDotSegment('a/b'), 'a/b');

assert.strictEqual(util.removeLeadingDotSegment('..\\a\\b'), '..\\a\\b');
assert.strictEqual(util.removeLeadingDotSegment('~\\a\\b'), '~\\a\\b');
assert.strictEqual(util.removeLeadingDotSegment('\\a\\b'), '\\a\\b');
assert.strictEqual(util.removeLeadingDotSegment('a\\b'), 'a\\b');
});

it('should return path without leading dit characters', () => {
assert.strictEqual(util.removeLeadingDotSegment('./a/b'), 'a/b');
assert.strictEqual(util.removeLeadingDotSegment('.\\a\\b'), 'a\\b');
});
});
});
15 changes: 15 additions & 0 deletions src/utils/path.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as path from 'path';

import { Pattern } from '../types';

const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\
const UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\())/g;

/**
Expand All @@ -18,3 +19,17 @@ export function makeAbsolute(cwd: string, filepath: string): string {
export function escape(pattern: Pattern): Pattern {
return pattern.replace(UNESCAPED_GLOB_SYMBOLS_RE, '\\$2');
}

export function removeLeadingDotSegment(entry: string): string {
// We do not use `startsWith` because this is 10x slower than current implementation for some cases.
// eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with
if (entry.charAt(0) === '.') {
const secondCharactery = entry.charAt(1);

if (secondCharactery === '/' || secondCharactery === '\\') {
return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT);
}
}

return entry;
}

0 comments on commit 8851e0f

Please sign in to comment.