CoolFace
Datasetpublic

basant307/AI_Governance_Project

sourceHugging Faceapache-2.0updated 2mo agoView on Hugging Face
0likes48downloads
parse.js262 linesDownload Raw Back to shell-quote
1'use strict';2 3/**4 * @import {5 * 	ControlOperator,6 * 	Env,7 * 	GlobPattern,8 * 	ParseEntry,9 * } from './parse' */10 11// '<(' is process substitution operator and12// can be parsed the same as control operator13var CONTROL = /** @type {const} */ ('(?:') + /** @type {const} */ ([14	'\\|\\|',15	'\\&\\&',16	';;',17	'\\|\\&',18	'\\<\\(',19	'\\<\\<\\<',20	'>>',21	'>\\&',22	'<\\&',23	'[&;()|<>]'24]).join(/** @type {const} */ ('|')) + /** @type {const} */ (')');25var controlRE = new RegExp('^' + CONTROL + '$');26var META = /** @type {const} */ ('|&;()<> \\t');27var SINGLE_QUOTE = /** @type {const} */ ('"((\\\\"|[^"])*?)"');28var DOUBLE_QUOTE = /** @type {const} */ ('\'((\\\\\'|[^\'])*?)\'');29var hash = /^#$/;30 31var SQ = /** @type {const} */ ("'");32var DQ = /** @type {const} */ ('"');33var DS = /** @type {const} */ ('$');34 35var TOKEN = '';36var mult = /** @type {const} */ (0x100000000); // Math.pow(16, 8);37for (var i = 0; i < 4; i++) {38	TOKEN += (mult * Math.random()).toString(16);39}40var startsWithToken = new RegExp('^' + TOKEN);41 42/**43 * @param {string} s44 * @param {RegExp} r45 */46function matchAll(s, r) {47	var origIndex = r.lastIndex;48 49	var matches = [];50	var matchObj;51 52	while ((matchObj = r.exec(s))) {53		matches[matches.length] = matchObj;54		if (r.lastIndex === matchObj.index) {55			r.lastIndex += 1;56		}57	}58 59	r.lastIndex = origIndex;60 61	return matches;62}63 64/**65 * @param {Env} env66 * @param {string} pre67 * @param {string} key68 */69function getVar(env, pre, key) {70	var r = typeof env === 'function' ? env(key) : env[key];71	if (typeof r === 'undefined' && key != '') {72		r = '';73	} else if (typeof r === 'undefined') {74		r = '$';75	}76 77	if (typeof r === 'object') {78		return pre + TOKEN + JSON.stringify(r) + TOKEN;79	}80	return pre + r;81}82 83/**84 * @param {string} string85 * @param {Env} [env]86 * @param {{ escape?: string }} [opts]87 * @returns {ParseEntry[]}88 */89function parseInternal(string, env, opts) {90	if (!opts) {91		opts = {};92	}93	var BS = opts.escape || '\\';94	var BAREWORD = '(\\' + BS + '[\'"' + META + ']|[^\\s\'"' + META + '])+';95 96	var chunker = new RegExp([97		'(' + CONTROL + ')', // control chars98		'(' + BAREWORD + '|' + SINGLE_QUOTE + '|' + DOUBLE_QUOTE + ')+'99	].join('|'), 'g');100 101	var matches = matchAll(string, chunker);102 103	if (matches.length === 0) {104		return [];105	}106	if (!env) {107		env = {};108	}109 110	var commented = false;111 112	return matches.map(function (match) {113		var s = match[0];114		if (!s || commented) {115			return void undefined;116		}117		if (controlRE.test(s)) {118			return /** @type {ControlOperator} */ ({ op: s });119		}120 121		// Hand-written scanner/parser for Bash quoting rules:122		//123		// 1. inside single quotes, all characters are printed literally.124		// 2. inside double quotes, all characters are printed literally125		//    except variables prefixed by '$' and backslashes followed by126		//    either a double quote or another backslash.127		// 3. outside of any quotes, backslashes are treated as escape128		//    characters and not printed (unless they are themselves escaped)129		// 4. quote context can switch mid-token if there is no whitespace130		//     between the two quote contexts (e.g. all'one'"token" parses as131		//     "allonetoken")132		/** @type {string | boolean} */133		var quote = false;134		var esc = false;135		var out = '';136		var isGlob = false;137		/** @type {number} */138		var i;139 140		function parseEnvVar() {141			i += 1;142			/** @type {number | RegExpMatchArray | null} */143			var varend;144			/** @type {string} */145			var varname;146			var char = s.charAt(i);147 148			if (char === '{') {149				i += 1;150				if (s.charAt(i) === '}') {151					throw new Error('Bad substitution: ' + s.slice(i - 2, i + 1));152				}153				varend = s.indexOf('}', i);154				if (varend < 0) {155					throw new Error('Bad substitution: ' + s.slice(i));156				}157				varname = s.slice(i, varend);158				i = varend;159			} else if ((/[*@#?$!_-]/).test(char)) {160				varname = char;161				i += 1;162			} else {163				var slicedFromI = s.slice(i);164				varend = slicedFromI.match(/[^\w\d_]/);165				if (!varend) {166					varname = slicedFromI;167					i = s.length;168				} else {169					varname = slicedFromI.slice(0, varend.index);170					i += /** @type {number} */ (varend.index) - 1;171				}172			}173			return getVar(/** @type {NonNullable<typeof env>} */ (env), '', varname);174		}175 176		for (i = 0; i < s.length; i++) {177			var c = s.charAt(i);178			isGlob = isGlob || (!quote && (c === '*' || c === '?'));179			if (esc) {180				out += c;181				esc = false;182			} else if (quote) {183				if (c === quote) {184					quote = false;185				} else if (quote == SQ) {186					out += c;187				} else { // Double quote188					if (c === BS) {189						i += 1;190						c = s.charAt(i);191						if (c === DQ || c === BS || c === DS) {192							out += c;193						} else {194							out += BS + c;195						}196					} else if (c === DS) {197						out += parseEnvVar();198					} else {199						out += c;200					}201				}202			} else if (c === DQ || c === SQ) {203				quote = c;204			} else if (controlRE.test(c)) {205				return /** @type {ControlOperator} */ ({ op: s });206			} else if (hash.test(c)) {207				commented = true;208				var commentObj = { comment: string.slice(match.index + i + 1) };209				if (out.length) {210					return /** @type {const} */ ([out, commentObj]);211				}212				return /** @type {const} */ ([commentObj]);213			} else if (c === BS) {214				esc = true;215			} else if (c === DS) {216				out += parseEnvVar();217			} else {218				out += c;219			}220		}221 222		if (isGlob) {223			return /** @type {GlobPattern} */ ({ op: 'glob', pattern: out });224		}225 226		return out;227	}).reduce(function (prev, arg) { // finalize parsed arguments228		if (typeof arg === 'undefined') {229			return prev;230		}231		/** @type {ParseEntry[]} */ ([]).concat(arg).forEach(function (entry) {232			prev[prev.length] = entry;233		});234		return prev;235	}, /** @type {ParseEntry[]} */ ([]));236}237 238/** @type {import('./parse')} */239module.exports = function parse(s, env, opts) {240	var mapped = parseInternal(s, env, opts);241	if (typeof env !== 'function') {242		return mapped;243	}244	return mapped.reduce(function (acc, s) {245		if (typeof s === 'object') {246			acc[acc.length] = s;247			return acc;248		}249		var xs = s.split(RegExp('(' + TOKEN + '.*?' + TOKEN + ')', 'g'));250		if (xs.length === 1) {251			acc[acc.length] = xs[0];252			return acc;253		}254		xs.filter(Boolean).forEach(function (x) {255			acc[acc.length] = startsWithToken.test(x)256				? JSON.parse(x.split(TOKEN)[1])257				: x;258		});259		return acc;260	}, /** @type {ParseEntry[]} */ ([]));261};262 
basant307/AI_Governance_Project · CoolFace