-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
parse.js
412 lines (352 loc) · 10.3 KB
/
parse.js
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
/* @flow */
/* eslint quotes: 0 */
import util from 'util';
import invariant from 'invariant';
import stripBOM from 'strip-bom';
import {LOCKFILE_VERSION} from '../constants.js';
import {MessageError} from '../errors.js';
import map from '../util/map.js';
type Token = {
line: number,
col: number,
type: string,
value: boolean | number | string | void,
};
export type ParseResultType = 'merge' | 'success' | 'conflict';
export type ParseResult = {
type: ParseResultType,
object: Object,
};
const VERSION_REGEX = /^yarn lockfile v(\d+)$/;
const TOKEN_TYPES = {
boolean: 'BOOLEAN',
string: 'STRING',
identifier: 'IDENTIFIER',
eof: 'EOF',
colon: 'COLON',
newline: 'NEWLINE',
comment: 'COMMENT',
indent: 'INDENT',
invalid: 'INVALID',
number: 'NUMBER',
comma: 'COMMA',
};
const VALID_PROP_VALUE_TOKENS = [TOKEN_TYPES.boolean, TOKEN_TYPES.string, TOKEN_TYPES.number];
function isValidPropValueToken(token): boolean {
return VALID_PROP_VALUE_TOKENS.indexOf(token.type) >= 0;
}
function* tokenise(input: string): Iterator<Token> {
let lastNewline = false;
let line = 1;
let col = 0;
function buildToken(type, value): Token {
return {line, col, type, value};
}
while (input.length) {
let chop = 0;
if (input[0] === '\n' || input[0] === '\r') {
chop++;
// If this is a \r\n line, ignore both chars but only add one new line
if (input[1] === '\n') {
chop++;
}
line++;
col = 0;
yield buildToken(TOKEN_TYPES.newline);
} else if (input[0] === '#') {
chop++;
let val = '';
while (input[chop] !== '\n') {
val += input[chop];
chop++;
}
yield buildToken(TOKEN_TYPES.comment, val);
} else if (input[0] === ' ') {
if (lastNewline) {
let indent = '';
for (let i = 0; input[i] === ' '; i++) {
indent += input[i];
}
if (indent.length % 2) {
throw new TypeError('Invalid number of spaces');
} else {
chop = indent.length;
yield buildToken(TOKEN_TYPES.indent, indent.length / 2);
}
} else {
chop++;
}
} else if (input[0] === '"') {
let val = '';
for (let i = 0; ; i++) {
const currentChar = input[i];
val += currentChar;
if (i > 0 && currentChar === '"') {
const isEscaped = input[i - 1] === '\\' && input[i - 2] !== '\\';
if (!isEscaped) {
break;
}
}
}
chop = val.length;
try {
yield buildToken(TOKEN_TYPES.string, JSON.parse(val));
} catch (err) {
if (err instanceof SyntaxError) {
yield buildToken(TOKEN_TYPES.invalid);
} else {
throw err;
}
}
} else if (/^[0-9]/.test(input)) {
let val = '';
for (let i = 0; /^[0-9]$/.test(input[i]); i++) {
val += input[i];
}
chop = val.length;
yield buildToken(TOKEN_TYPES.number, +val);
} else if (/^true/.test(input)) {
yield buildToken(TOKEN_TYPES.boolean, true);
chop = 4;
} else if (/^false/.test(input)) {
yield buildToken(TOKEN_TYPES.boolean, false);
chop = 5;
} else if (input[0] === ':') {
yield buildToken(TOKEN_TYPES.colon);
chop++;
} else if (input[0] === ',') {
yield buildToken(TOKEN_TYPES.comma);
chop++;
} else if (/^[a-zA-Z\/-]/g.test(input)) {
let name = '';
for (let i = 0; i < input.length; i++) {
const char = input[i];
if (char === ':' || char === ' ' || char === '\n' || char === '\r' || char === ',') {
break;
} else {
name += char;
}
}
chop = name.length;
yield buildToken(TOKEN_TYPES.string, name);
} else {
yield buildToken(TOKEN_TYPES.invalid);
}
if (!chop) {
// will trigger infinite recursion
yield buildToken(TOKEN_TYPES.invalid);
}
col += chop;
lastNewline = input[0] === '\n' || (input[0] === '\r' && input[1] === '\n');
input = input.slice(chop);
}
yield buildToken(TOKEN_TYPES.eof);
}
class Parser {
constructor(input: string, fileLoc: string = 'lockfile') {
this.comments = [];
this.tokens = tokenise(input);
this.fileLoc = fileLoc;
}
fileLoc: string;
token: Token;
tokens: Iterator<Token>;
comments: Array<string>;
onComment(token: Token) {
const value = token.value;
invariant(typeof value === 'string', 'expected token value to be a string');
const comment = value.trim();
const versionMatch = comment.match(VERSION_REGEX);
if (versionMatch) {
const version = +versionMatch[1];
if (version > LOCKFILE_VERSION) {
throw new MessageError(
`Can't install from a lockfile of version ${version} as you're on an old yarn version that only supports ` +
`versions up to ${LOCKFILE_VERSION}. Run \`$ yarn self-update\` to upgrade to the latest version.`,
);
}
}
this.comments.push(comment);
}
next(): Token {
const item = this.tokens.next();
invariant(item, 'expected a token');
const {done, value} = item;
if (done || !value) {
throw new Error('No more tokens');
} else if (value.type === TOKEN_TYPES.comment) {
this.onComment(value);
return this.next();
} else {
return (this.token = value);
}
}
unexpected(msg: string = 'Unexpected token') {
throw new SyntaxError(`${msg} ${this.token.line}:${this.token.col} in ${this.fileLoc}`);
}
expect(tokType: string) {
if (this.token.type === tokType) {
this.next();
} else {
this.unexpected();
}
}
eat(tokType: string): boolean {
if (this.token.type === tokType) {
this.next();
return true;
} else {
return false;
}
}
parse(indent: number = 0): Object {
const obj = map();
while (true) {
const propToken = this.token;
if (propToken.type === TOKEN_TYPES.newline) {
const nextToken = this.next();
if (!indent) {
// if we have 0 indentation then the next token doesn't matter
continue;
}
if (nextToken.type !== TOKEN_TYPES.indent) {
// if we have no indentation after a newline then we've gone down a level
break;
}
if (nextToken.value === indent) {
// all is good, the indent is on our level
this.next();
} else {
// the indentation is less than our level
break;
}
} else if (propToken.type === TOKEN_TYPES.indent) {
if (propToken.value === indent) {
this.next();
} else {
break;
}
} else if (propToken.type === TOKEN_TYPES.eof) {
break;
} else if (propToken.type === TOKEN_TYPES.string) {
// property key
const key = propToken.value;
invariant(key, 'Expected a key');
const keys = [key];
this.next();
// support multiple keys
while (this.token.type === TOKEN_TYPES.comma) {
this.next(); // skip comma
const keyToken = this.token;
if (keyToken.type !== TOKEN_TYPES.string) {
this.unexpected('Expected string');
}
const key = keyToken.value;
invariant(key, 'Expected a key');
keys.push(key);
this.next();
}
const valToken = this.token;
if (valToken.type === TOKEN_TYPES.colon) {
// object
this.next();
// parse object
const val = this.parse(indent + 1);
for (const key of keys) {
obj[key] = val;
}
if (indent && this.token.type !== TOKEN_TYPES.indent) {
break;
}
} else if (isValidPropValueToken(valToken)) {
// plain value
for (const key of keys) {
obj[key] = valToken.value;
}
this.next();
} else {
this.unexpected('Invalid value type');
}
} else {
this.unexpected(`Unknown token: ${util.inspect(propToken)}`);
}
}
return obj;
}
}
const MERGE_CONFLICT_ANCESTOR = '|||||||';
const MERGE_CONFLICT_END = '>>>>>>>';
const MERGE_CONFLICT_SEP = '=======';
const MERGE_CONFLICT_START = '<<<<<<<';
/**
* Extract the two versions of the lockfile from a merge conflict.
*/
function extractConflictVariants(str: string): [string, string] {
const variants = [[], []];
const lines = str.split(/\r?\n/g);
let skip = false;
while (lines.length) {
const line = lines.shift();
if (line.startsWith(MERGE_CONFLICT_START)) {
// get the first variant
while (lines.length) {
const conflictLine = lines.shift();
if (conflictLine === MERGE_CONFLICT_SEP) {
skip = false;
break;
} else if (skip || conflictLine.startsWith(MERGE_CONFLICT_ANCESTOR)) {
skip = true;
continue;
} else {
variants[0].push(conflictLine);
}
}
// get the second variant
while (lines.length) {
const conflictLine = lines.shift();
if (conflictLine.startsWith(MERGE_CONFLICT_END)) {
break;
} else {
variants[1].push(conflictLine);
}
}
} else {
variants[0].push(line);
variants[1].push(line);
}
}
return [variants[0].join('\n'), variants[1].join('\n')];
}
/**
* Check if a lockfile has merge conflicts.
*/
function hasMergeConflicts(str: string): boolean {
return str.includes(MERGE_CONFLICT_START) && str.includes(MERGE_CONFLICT_SEP) && str.includes(MERGE_CONFLICT_END);
}
/**
* Parse the lockfile.
*/
function parse(str: string, fileLoc: string): Object {
const parser = new Parser(str, fileLoc);
parser.next();
return parser.parse();
}
/**
* Parse and merge the two variants in a conflicted lockfile.
*/
function parseWithConflict(str: string, fileLoc: string): ParseResult {
const variants = extractConflictVariants(str);
try {
return {type: 'merge', object: Object.assign({}, parse(variants[0], fileLoc), parse(variants[1], fileLoc))};
} catch (err) {
if (err instanceof SyntaxError) {
return {type: 'conflict', object: {}};
} else {
throw err;
}
}
}
export default function(str: string, fileLoc: string = 'lockfile'): ParseResult {
str = stripBOM(str);
return hasMergeConflicts(str) ? parseWithConflict(str, fileLoc) : {type: 'success', object: parse(str, fileLoc)};
}