-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathutils.ts
More file actions
233 lines (196 loc) · 6.76 KB
/
Copy pathutils.ts
File metadata and controls
233 lines (196 loc) · 6.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
// Copyright 2020 Google Inc. Use of this source code is governed by an
// MIT-style license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
import {List} from 'immutable';
import * as p from 'path';
import * as url from 'url';
import * as proto from './vendor/embedded_sass_pb';
import {Syntax} from './vendor/sass';
export type PromiseOr<
T,
sync extends 'sync' | 'async' = 'async',
> = sync extends 'async' ? T | Promise<T> : T;
// A boolean type that's `true` if `sync` requires synchronous APIs only and
// `false` if it allows asynchronous APIs.
export type SyncBoolean<sync extends 'sync' | 'async'> = sync extends 'async'
? false
: true;
/**
* The equivalent of `Promise.then()`, except that if the first argument is a
* plain value it synchronously invokes `callback()` and returns its result.
*/
export function thenOr<T, V, sync extends 'sync' | 'async'>(
promiseOrValue: PromiseOr<T, sync>,
callback: (value: T) => PromiseOr<V, sync>,
): PromiseOr<V, sync> {
return promiseOrValue instanceof Promise
? (promiseOrValue.then(callback) as PromiseOr<V, sync>)
: callback(promiseOrValue as T);
}
/**
* The equivalent of `Promise.catch()`, except that if the first argument throws
* synchronously it synchronously invokes `callback()` and returns its result.
*/
export function catchOr<T, sync extends 'sync' | 'async'>(
promiseOrValueCallback: () => PromiseOr<T, sync>,
callback: (error: unknown) => PromiseOr<T, sync>,
): PromiseOr<T, sync> {
try {
const result = promiseOrValueCallback();
return result instanceof Promise
? (result.catch(callback) as PromiseOr<T, sync>)
: result;
} catch (error: unknown) {
return callback(error);
}
}
/** Checks for null or undefined. */
export function isNullOrUndefined<T>(
object: T | null | undefined,
): object is null | undefined {
return object === null || object === undefined;
}
/** Returns `collection` as an immutable List. */
export function asImmutableList<T>(collection: T[] | List<T>): List<T> {
return List.isList(collection) ? collection : List(collection);
}
/** Constructs a compiler-caused Error. */
export function compilerError(message: string): Error {
return Error(`Compiler caused error: ${message}.`);
}
/**
* Returns a `compilerError()` indicating that the given `field` should have
* been included but was not.
*/
export function mandatoryError(field: string): Error {
return compilerError(`Missing mandatory field ${field}.`);
}
/** Constructs a host-caused Error. */
export function hostError(message: string): Error {
return Error(`Compiler reported error: ${message}.`);
}
/** Constructs an error caused by an invalid value type. */
export function valueError(message: string, name?: string): Error {
return Error(name ? `$${name}: ${message}.` : `${message}.`);
}
// Node changed its implementation of pathToFileURL:
// https://github.com/nodejs/node/pull/54545
const unsafePathToFileURL = url.pathToFileURL('~').pathname.endsWith('~');
/** Converts a (possibly relative) path on the local filesystem to a URL. */
export function pathToUrlString(path: string): string {
if (p.isAbsolute(path)) return url.pathToFileURL(path).toString();
// percent encode relative path like `pathToFileURL`
let fileUrl = encodeURI(path).replace(/[#?]/g, encodeURIComponent);
if (unsafePathToFileURL) {
fileUrl = fileUrl.replace(/%(5B|5D|5E|7C)/g, decodeURIComponent);
} else {
fileUrl = fileUrl.replace(/~/g, '%7E');
}
if (process.platform === 'win32') {
fileUrl = fileUrl.replace(/%5C/g, '/');
}
return fileUrl;
}
/**
* Like `url.fileURLToPath`, but returns the same result for Windows-style file
* URLs on all platforms.
*/
export function fileUrlToPathCrossPlatform(fileUrl: url.URL | string): string {
const path = url.fileURLToPath(fileUrl);
// Windows file: URLs begin with `file:///C:/` (or another drive letter),
// which `fileURLToPath` converts to `"/C:/"` on non-Windows systems. We want
// to ensure the behavior is consistent across OSes, so we normalize this back
// to a Windows-style path.
return /^\/[A-Za-z]:\//.test(path) ? path.substring(1) : path;
}
/**
* Returns a pretty URL similar to Dart's `path.prettyUri`.
*/
export function prettyUrl(url: string): string {
if (!url.startsWith('file:')) return url;
const absolutePath = fileUrlToPathCrossPlatform(url);
const relativePath = p.relative(process.cwd(), absolutePath);
return relativePath.split(p.sep).length > absolutePath.split(p.sep).length
? absolutePath
: relativePath;
}
/**
* Reformat URLs in formatted text from the embedded compiler.
*/
export function prettyFormatted(formatted: string, stack: string): string {
let longest = 0;
const frames = stack
.split('\n')
.filter(frame => frame !== '')
.map(frame => {
let [location, member] = frame.split(/ +/, 2);
let [url, lineColumn] = location.split(' ', 2);
url = prettyUrl(url);
location = lineColumn === undefined ? url : `${url} ${lineColumn}`;
if (location.length > longest) {
longest = location.length;
}
return {
frame,
location,
member,
};
});
let offset = formatted.length;
frames.reverse().forEach(({frame, location, member}) => {
const index = formatted.lastIndexOf(frame, offset);
if (index !== -1) {
offset = index;
const replacement = `${location.padEnd(longest)} ${member}`;
if (frame !== replacement) {
formatted =
formatted.slice(0, index) +
replacement +
formatted.slice(index + frame.length);
}
}
});
return formatted;
}
/** Returns `path` without an extension, if it had one. */
export function withoutExtension(path: string): string {
const extension = p.extname(path);
return path.substring(0, path.length - extension.length);
}
/** Converts a JS syntax string into a protobuf syntax enum. */
export function protofySyntax(syntax: Syntax): proto.Syntax {
switch (syntax) {
case 'scss':
return proto.Syntax.SCSS;
case 'indented':
return proto.Syntax.INDENTED;
case 'css':
return proto.Syntax.CSS;
default:
throw new Error(`Unknown syntax: "${syntax}"`);
}
}
/** Returns whether `error` is a NodeJS-style exception with an error code. */
export function isErrnoException(
error: unknown,
): error is NodeJS.ErrnoException {
return error instanceof Error && ('errno' in error || 'code' in error);
}
/**
* Dart-style utility. See
* http://go/dart-api/stable/2.8.4/dart-core/Map/putIfAbsent.html.
*/
export function putIfAbsent<K, V>(
map: Map<K, V>,
key: K,
provider: () => V,
): V {
const val = map.get(key);
if (val !== undefined) {
return val;
} else {
const newVal = provider();
map.set(key, newVal);
return newVal;
}
}