UNPKG

1.99 kBPlain TextView Raw
1import {EventEmitter} from 'eventemitter3';
2import * as micromatch from 'micromatch';
3import {Correlation, EventEmitter as FSEvents} from './api';
4import {pathSeparator, ShallowDirectory, File} from "./model";
5
6const isGlob = require('is-glob');
7
8// utility logic for filesystem implementations
9
10export function getPathNodes(path: string): Array<string> {
11 return path.split(pathSeparator).filter(n => n.length);
12}
13export function normalizePathNodes(path: Array<string>): string {
14 return path.filter(n => n.length).join(pathSeparator);
15}
16
17export function splitPathToDirAndFile(targetPath: string): { parentPath: string, name: string } {
18 let nameParentSeparator = targetPath.lastIndexOf(pathSeparator);
19 return {
20 parentPath: targetPath.substr(0, nameParentSeparator),
21 name: targetPath.substr(nameParentSeparator + 1)
22 };
23}
24
25export function checkExistsInDir(expectedType: 'file' | 'dir', dirContent: Array<ShallowDirectory | File>, name: string) {
26 for (let node of dirContent) {
27 if (node.type === expectedType && node.name === name) {
28 return true;
29 }
30 }
31 return false;
32}
33
34function extendMatchersWithGlob(paths: Array<string>): Array<string> {
35 return paths.reduce((extended: string[], path) => {
36 extended.push(path);
37 if (!isGlob(path)) {
38 extended.push(`${path}/**`, `**/${path}`, `**/${path}/**`);
39 }
40 return extended;
41 }, []);
42}
43
44export function getIsIgnored(matchers: string[], options: Object = {dot: true}): (path: string) => boolean {
45 const patterns = extendMatchersWithGlob(matchers);
46 return (path: string) => micromatch.any(path, patterns, options);
47}
48
49export type InternalEventsEmitter = FSEvents & EventEmitter;
50
51export function makeEventsEmitter(): InternalEventsEmitter {
52 return (new EventEmitter()) as any as InternalEventsEmitter;
53}
54
55export function makeCorrelationId(): Correlation {
56 return (Math.random().toString(36) + '0000').substr(2, 4);
57}