UNPKG

2.58 kBJavaScriptView Raw
1const path = require('path');
2const unixify = require('unixify');
3const { ALLOWED_EXTENSIONS } = require('./lib/constants');
4
5const convertToUnixPath = _path => {
6 return unixify(path.normalize(_path));
7};
8
9const convertToWindowsPath = _path => {
10 const rgx = new RegExp(`\\${path.posix.sep}`, 'g');
11 return path.normalize(_path).replace(rgx, path.win32.sep);
12};
13
14const convertToLocalFileSystemPath = _path => {
15 switch (path.sep) {
16 case path.posix.sep:
17 return convertToUnixPath(_path);
18 case path.win32.sep:
19 return convertToWindowsPath(_path);
20 default:
21 return path.normalize(_path);
22 }
23};
24
25/**
26 * @param {string[]} parts
27 */
28const removeTrailingSlashFromSplits = parts => {
29 if (parts.length > 1 && parts[parts.length - 1] === '') {
30 return parts.slice(0, parts.length - 1);
31 }
32 return parts;
33};
34
35/**
36 * Splits a filepath for local file system sources.
37 *
38 * @param {string} filepath
39 * @param {object} pathImplementation - For testing
40 * @returns {string[]}
41 */
42const splitLocalPath = (filepath, pathImplementation = path) => {
43 if (!filepath) return [];
44 const { sep } = pathImplementation;
45 const rgx = new RegExp(`\\${sep}+`, 'g');
46 const parts = pathImplementation.normalize(filepath).split(rgx);
47 // Restore posix root if present
48 if (sep === path.posix.sep && parts[0] === '') {
49 parts[0] = '/';
50 }
51 return removeTrailingSlashFromSplits(parts);
52};
53
54/**
55 * Splits a filepath for remote sources (HubSpot).
56 *
57 * @param {string} filepath
58 * @returns {string[]}
59 */
60const splitHubSpotPath = filepath => {
61 if (!filepath) return [];
62 const rgx = new RegExp(`\\${path.posix.sep}+`, 'g');
63 const parts = convertToUnixPath(filepath).split(rgx);
64 // Restore root if present
65 if (parts[0] === '') {
66 parts[0] = '/';
67 }
68 return removeTrailingSlashFromSplits(parts);
69};
70
71const getCwd = () => {
72 if (process.env.INIT_CWD) {
73 return process.env.INIT_CWD;
74 }
75 return process.cwd();
76};
77
78function getExt(filepath) {
79 if (typeof filepath !== 'string') return '';
80 const ext = path
81 .extname(filepath)
82 .trim()
83 .toLowerCase();
84 return ext[0] === '.' ? ext.slice(1) : ext;
85}
86
87const getAllowedExtensions = () => {
88 return ALLOWED_EXTENSIONS;
89};
90
91const isAllowedExtension = filepath => {
92 const ext = getExt(filepath);
93 const allowedExtensions = getAllowedExtensions();
94 return allowedExtensions.has(ext);
95};
96
97module.exports = {
98 convertToUnixPath,
99 convertToWindowsPath,
100 convertToLocalFileSystemPath,
101 getAllowedExtensions,
102 getCwd,
103 getExt,
104 isAllowedExtension,
105 splitHubSpotPath,
106 splitLocalPath,
107};