code
stringlengths
24
2.07M
docstring
stringlengths
25
85.3k
func_name
stringlengths
1
92
language
stringclasses
1 value
repo
stringlengths
5
64
path
stringlengths
4
172
url
stringlengths
44
218
license
stringclasses
7 values
getSortKey = (option) => { // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated. return option.short ? option.short.replace(/^-/, '') : option.long.replace(/^--/, ''); }
Compare options for sort. @param {Option} a @param {Option} b @returns {number}
getSortKey
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
getSortKey = (option) => { // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated. return option.short ? option.short.replace(/^-/, '') : option.long.replace(/^--/, ''); }
Compare options for sort. @param {Option} a @param {Option} b @returns {number}
getSortKey
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
visibleOptions(cmd) { const visibleOptions = cmd.options.filter((option) => !option.hidden); // Built-in help option. const helpOption = cmd._getHelpOption(); if (helpOption && !helpOption.hidden) { // Automatically hide conflicting flags. Bit dubious but a historical behaviour that is convenient for single-command programs. const removeShort = helpOption.short && cmd._findOption(helpOption.short); const removeLong = helpOption.long && cmd._findOption(helpOption.long); if (!removeShort && !removeLong) { visibleOptions.push(helpOption); // no changes needed } else if (helpOption.long && !removeLong) { visibleOptions.push( cmd.createOption(helpOption.long, helpOption.description), ); } else if (helpOption.short && !removeShort) { visibleOptions.push( cmd.createOption(helpOption.short, helpOption.description), ); } } if (this.sortOptions) { visibleOptions.sort(this.compareOptions); } return visibleOptions; }
Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one. @param {Command} cmd @returns {Option[]}
visibleOptions
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
visibleGlobalOptions(cmd) { if (!this.showGlobalOptions) return []; const globalOptions = []; for ( let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent ) { const visibleOptions = ancestorCmd.options.filter( (option) => !option.hidden, ); globalOptions.push(...visibleOptions); } if (this.sortOptions) { globalOptions.sort(this.compareOptions); } return globalOptions; }
Get an array of the visible global options. (Not including help.) @param {Command} cmd @returns {Option[]}
visibleGlobalOptions
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
visibleArguments(cmd) { // Side effect! Apply the legacy descriptions before the arguments are displayed. if (cmd._argsDescription) { cmd.registeredArguments.forEach((argument) => { argument.description = argument.description || cmd._argsDescription[argument.name()] || ''; }); } // If there are any arguments with a description then return all the arguments. if (cmd.registeredArguments.find((argument) => argument.description)) { return cmd.registeredArguments; } return []; }
Get an array of the arguments if any have a description. @param {Command} cmd @returns {Argument[]}
visibleArguments
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
subcommandTerm(cmd) { // Legacy. Ignores custom usage string, and nested commands. const args = cmd.registeredArguments .map((arg) => humanReadableArgName(arg)) .join(' '); return ( cmd._name + (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') + (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option (args ? ' ' + args : '') ); }
Get the command term to show in the list of subcommands. @param {Command} cmd @returns {string}
subcommandTerm
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
optionTerm(option) { return option.flags; }
Get the option term to show in the list of options. @param {Option} option @returns {string}
optionTerm
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
argumentTerm(argument) { return argument.name(); }
Get the argument term to show in the list of arguments. @param {Argument} argument @returns {string}
argumentTerm
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
longestSubcommandTermLength(cmd, helper) { return helper.visibleCommands(cmd).reduce((max, command) => { return Math.max( max, this.displayWidth( helper.styleSubcommandTerm(helper.subcommandTerm(command)), ), ); }, 0); }
Get the longest command term length. @param {Command} cmd @param {Help} helper @returns {number}
longestSubcommandTermLength
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
longestOptionTermLength(cmd, helper) { return helper.visibleOptions(cmd).reduce((max, option) => { return Math.max( max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))), ); }, 0); }
Get the longest option term length. @param {Command} cmd @param {Help} helper @returns {number}
longestOptionTermLength
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
longestGlobalOptionTermLength(cmd, helper) { return helper.visibleGlobalOptions(cmd).reduce((max, option) => { return Math.max( max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))), ); }, 0); }
Get the longest global option term length. @param {Command} cmd @param {Help} helper @returns {number}
longestGlobalOptionTermLength
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
longestArgumentTermLength(cmd, helper) { return helper.visibleArguments(cmd).reduce((max, argument) => { return Math.max( max, this.displayWidth( helper.styleArgumentTerm(helper.argumentTerm(argument)), ), ); }, 0); }
Get the longest argument term length. @param {Command} cmd @param {Help} helper @returns {number}
longestArgumentTermLength
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
commandUsage(cmd) { // Usage let cmdName = cmd._name; if (cmd._aliases[0]) { cmdName = cmdName + '|' + cmd._aliases[0]; } let ancestorCmdNames = ''; for ( let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent ) { ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames; } return ancestorCmdNames + cmdName + ' ' + cmd.usage(); }
Get the command usage to be displayed at the top of the built-in help. @param {Command} cmd @returns {string}
commandUsage
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
commandDescription(cmd) { // @ts-ignore: because overloaded return type return cmd.description(); }
Get the description for the command. @param {Command} cmd @returns {string}
commandDescription
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
subcommandDescription(cmd) { // @ts-ignore: because overloaded return type return cmd.summary() || cmd.description(); }
Get the subcommand summary to show in the list of subcommands. (Fallback to description for backwards compatibility.) @param {Command} cmd @returns {string}
subcommandDescription
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
optionDescription(option) { const extraInfo = []; if (option.argChoices) { extraInfo.push( // use stringify to match the display of the default value `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`, ); } if (option.defaultValue !== undefined) { // default for boolean and negated more for programmer than end user, // but show true/false for boolean option as may be for hand-rolled env or config processing. const showDefault = option.required || option.optional || (option.isBoolean() && typeof option.defaultValue === 'boolean'); if (showDefault) { extraInfo.push( `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`, ); } } // preset for boolean and negated are more for programmer than end user if (option.presetArg !== undefined && option.optional) { extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`); } if (option.envVar !== undefined) { extraInfo.push(`env: ${option.envVar}`); } if (extraInfo.length > 0) { const extraDescription = `(${extraInfo.join(', ')})`; if (option.description) { return `${option.description} ${extraDescription}`; } return extraDescription; } return option.description; }
Get the option description to show in the list of options. @param {Option} option @return {string}
optionDescription
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
argumentDescription(argument) { const extraInfo = []; if (argument.argChoices) { extraInfo.push( // use stringify to match the display of the default value `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`, ); } if (argument.defaultValue !== undefined) { extraInfo.push( `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`, ); } if (extraInfo.length > 0) { const extraDescription = `(${extraInfo.join(', ')})`; if (argument.description) { return `${argument.description} ${extraDescription}`; } return extraDescription; } return argument.description; }
Get the argument description to show in the list of arguments. @param {Argument} argument @return {string}
argumentDescription
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
formatItemList(heading, items, helper) { if (items.length === 0) return []; return [helper.styleTitle(heading), ...items, '']; }
Format a list of items, given a heading and an array of formatted items. @param {string} heading @param {string[]} items @param {Help} helper @returns string[]
formatItemList
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
groupItems(unsortedItems, visibleItems, getGroup) { const result = new Map(); // Add groups in order of appearance in unsortedItems. unsortedItems.forEach((item) => { const group = getGroup(item); if (!result.has(group)) result.set(group, []); }); // Add items in order of appearance in visibleItems. visibleItems.forEach((item) => { const group = getGroup(item); if (!result.has(group)) { result.set(group, []); } result.get(group).push(item); }); return result; }
Group items by their help group heading. @param {Command[] | Option[]} unsortedItems @param {Command[] | Option[]} visibleItems @param {Function} getGroup @returns {Map<string, Command[] | Option[]>}
groupItems
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
formatHelp(cmd, helper) { const termWidth = helper.padWidth(cmd, helper); const helpWidth = helper.helpWidth ?? 80; // in case prepareContext() was not called function callFormatItem(term, description) { return helper.formatItem(term, termWidth, description, helper); } // Usage let output = [ `${helper.styleTitle('Usage:')} ${helper.styleUsage(helper.commandUsage(cmd))}`, '', ]; // Description const commandDescription = helper.commandDescription(cmd); if (commandDescription.length > 0) { output = output.concat([ helper.boxWrap( helper.styleCommandDescription(commandDescription), helpWidth, ), '', ]); } // Arguments const argumentList = helper.visibleArguments(cmd).map((argument) => { return callFormatItem( helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)), ); }); output = output.concat( this.formatItemList('Arguments:', argumentList, helper), ); // Options const optionGroups = this.groupItems( cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? 'Options:', ); optionGroups.forEach((options, group) => { const optionList = options.map((option) => { return callFormatItem( helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)), ); }); output = output.concat(this.formatItemList(group, optionList, helper)); }); if (helper.showGlobalOptions) { const globalOptionList = helper .visibleGlobalOptions(cmd) .map((option) => { return callFormatItem( helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)), ); }); output = output.concat( this.formatItemList('Global Options:', globalOptionList, helper), ); } // Commands const commandGroups = this.groupItems( cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || 'Commands:', ); commandGroups.forEach((commands, group) => { const commandList = commands.map((sub) => { return callFormatItem( helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)), ); }); output = output.concat(this.formatItemList(group, commandList, helper)); }); return output.join('\n'); }
Generate the built-in help text. @param {Command} cmd @param {Help} helper @returns {string}
formatHelp
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
function callFormatItem(term, description) { return helper.formatItem(term, termWidth, description, helper); }
Generate the built-in help text. @param {Command} cmd @param {Help} helper @returns {string}
callFormatItem
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
displayWidth(str) { return stripColor(str).length; }
Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations. @param {string} str @returns {number}
displayWidth
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
styleTitle(str) { return str; }
Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc. @param {string} str @returns {string}
styleTitle
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
styleUsage(str) { // Usage has lots of parts the user might like to color separately! Assume default usage string which is formed like: // command subcommand [options] [command] <foo> [bar] return str .split(' ') .map((word) => { if (word === '[options]') return this.styleOptionText(word); if (word === '[command]') return this.styleSubcommandText(word); if (word[0] === '[' || word[0] === '<') return this.styleArgumentText(word); return this.styleCommandText(word); // Restrict to initial words? }) .join(' '); }
Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc. @param {string} str @returns {string}
styleUsage
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
styleCommandDescription(str) { return this.styleDescriptionText(str); }
Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc. @param {string} str @returns {string}
styleCommandDescription
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
styleOptionDescription(str) { return this.styleDescriptionText(str); }
Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc. @param {string} str @returns {string}
styleOptionDescription
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
styleSubcommandDescription(str) { return this.styleDescriptionText(str); }
Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc. @param {string} str @returns {string}
styleSubcommandDescription
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
styleArgumentDescription(str) { return this.styleDescriptionText(str); }
Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc. @param {string} str @returns {string}
styleArgumentDescription
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
styleDescriptionText(str) { return str; }
Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc. @param {string} str @returns {string}
styleDescriptionText
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
styleOptionTerm(str) { return this.styleOptionText(str); }
Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc. @param {string} str @returns {string}
styleOptionTerm
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
styleSubcommandTerm(str) { // This is very like usage with lots of parts! Assume default string which is formed like: // subcommand [options] <foo> [bar] return str .split(' ') .map((word) => { if (word === '[options]') return this.styleOptionText(word); if (word[0] === '[' || word[0] === '<') return this.styleArgumentText(word); return this.styleSubcommandText(word); // Restrict to initial words? }) .join(' '); }
Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc. @param {string} str @returns {string}
styleSubcommandTerm
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
styleArgumentTerm(str) { return this.styleArgumentText(str); }
Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc. @param {string} str @returns {string}
styleArgumentTerm
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
styleOptionText(str) { return str; }
Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc. @param {string} str @returns {string}
styleOptionText
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
styleArgumentText(str) { return str; }
Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc. @param {string} str @returns {string}
styleArgumentText
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
styleSubcommandText(str) { return str; }
Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc. @param {string} str @returns {string}
styleSubcommandText
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
styleCommandText(str) { return str; }
Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc. @param {string} str @returns {string}
styleCommandText
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
padWidth(cmd, helper) { return Math.max( helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper), ); }
Calculate the pad width from the maximum term length. @param {Command} cmd @param {Help} helper @returns {number}
padWidth
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
preformatted(str) { return /\n[^\S\r\n]/.test(str); }
Detect manually wrapped and indented strings by checking for line break followed by whitespace. @param {string} str @returns {boolean}
preformatted
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
formatItem(term, termWidth, description, helper) { const itemIndent = 2; const itemIndentStr = ' '.repeat(itemIndent); if (!description) return itemIndentStr + term; // Pad the term out to a consistent width, so descriptions are aligned. const paddedTerm = term.padEnd( termWidth + term.length - helper.displayWidth(term), ); // Format the description. const spacerWidth = 2; // between term and description const helpWidth = this.helpWidth ?? 80; // in case prepareContext() was not called const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent; let formattedDescription; if ( remainingWidth < this.minWidthToWrap || helper.preformatted(description) ) { formattedDescription = description; } else { const wrappedDescription = helper.boxWrap(description, remainingWidth); formattedDescription = wrappedDescription.replace( /\n/g, '\n' + ' '.repeat(termWidth + spacerWidth), ); } // Construct and overall indent. return ( itemIndentStr + paddedTerm + ' '.repeat(spacerWidth) + formattedDescription.replace(/\n/g, `\n${itemIndentStr}`) ); }
Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines. So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so: TTT DDD DDDD DD DDD @param {string} term @param {number} termWidth @param {string} description @param {Help} helper @returns {string}
formatItem
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
boxWrap(str, width) { if (width < this.minWidthToWrap) return str; const rawLines = str.split(/\r\n|\n/); // split up text by whitespace const chunkPattern = /[\s]*[^\s]+/g; const wrappedLines = []; rawLines.forEach((line) => { const chunks = line.match(chunkPattern); if (chunks === null) { wrappedLines.push(''); return; } let sumChunks = [chunks.shift()]; let sumWidth = this.displayWidth(sumChunks[0]); chunks.forEach((chunk) => { const visibleWidth = this.displayWidth(chunk); // Accumulate chunks while they fit into width. if (sumWidth + visibleWidth <= width) { sumChunks.push(chunk); sumWidth += visibleWidth; return; } wrappedLines.push(sumChunks.join('')); const nextChunk = chunk.trimStart(); // trim space at line break sumChunks = [nextChunk]; sumWidth = this.displayWidth(nextChunk); }); wrappedLines.push(sumChunks.join('')); }); return wrappedLines.join('\n'); }
Wrap a string at whitespace, preserving existing line breaks. Wrapping is skipped if the width is less than `minWidthToWrap`. @param {string} str @param {number} width @returns {string}
boxWrap
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
function stripColor(str) { // eslint-disable-next-line no-control-regex const sgrPattern = /\x1b\[\d*(;\d*)*m/g; return str.replace(sgrPattern, ''); }
Strip style ANSI escape sequences from the string. In particular, SGR (Select Graphic Rendition) codes. @param {string} str @returns {string} @package
stripColor
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
constructor(flags, description) { this.flags = flags; this.description = description || ''; this.required = flags.includes('<'); // A value must be supplied when the option is specified. this.optional = flags.includes('['); // A value is optional when the option is specified. // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument this.variadic = /\w\.\.\.[>\]]$/.test(flags); // The option can take multiple values. this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line. const optionFlags = splitOptionFlags(flags); this.short = optionFlags.shortFlag; // May be a short flag, undefined, or even a long flag (if option has two long flags). this.long = optionFlags.longFlag; this.negate = false; if (this.long) { this.negate = this.long.startsWith('--no-'); } this.defaultValue = undefined; this.defaultValueDescription = undefined; this.presetArg = undefined; this.envVar = undefined; this.parseArg = undefined; this.hidden = false; this.argChoices = undefined; this.conflictsWith = []; this.implied = undefined; this.helpGroupHeading = undefined; // soft initialised when option added to command }
Initialize a new `Option` with the given `flags` and `description`. @param {string} flags @param {string} [description]
constructor
javascript
tj/commander.js
lib/option.js
https://github.com/tj/commander.js/blob/master/lib/option.js
MIT
default(value, description) { this.defaultValue = value; this.defaultValueDescription = description; return this; }
Set the default value, and optionally supply the description to be displayed in the help. @param {*} value @param {string} [description] @return {Option}
default
javascript
tj/commander.js
lib/option.js
https://github.com/tj/commander.js/blob/master/lib/option.js
MIT
preset(arg) { this.presetArg = arg; return this; }
Preset to use when option used without option-argument, especially optional but also boolean and negated. The custom processing (parseArg) is called. @example new Option('--color').default('GREYSCALE').preset('RGB'); new Option('--donate [amount]').preset('20').argParser(parseFloat); @param {*} arg @return {Option}
preset
javascript
tj/commander.js
lib/option.js
https://github.com/tj/commander.js/blob/master/lib/option.js
MIT
conflicts(names) { this.conflictsWith = this.conflictsWith.concat(names); return this; }
Add option name(s) that conflict with this option. An error will be displayed if conflicting options are found during parsing. @example new Option('--rgb').conflicts('cmyk'); new Option('--js').conflicts(['ts', 'jsx']); @param {(string | string[])} names @return {Option}
conflicts
javascript
tj/commander.js
lib/option.js
https://github.com/tj/commander.js/blob/master/lib/option.js
MIT
implies(impliedOptionValues) { let newImplied = impliedOptionValues; if (typeof impliedOptionValues === 'string') { // string is not documented, but easy mistake and we can do what user probably intended. newImplied = { [impliedOptionValues]: true }; } this.implied = Object.assign(this.implied || {}, newImplied); return this; }
Specify implied option values for when this option is set and the implied options are not. The custom processing (parseArg) is not called on the implied values. @example program .addOption(new Option('--log', 'write logging information to file')) .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' })); @param {object} impliedOptionValues @return {Option}
implies
javascript
tj/commander.js
lib/option.js
https://github.com/tj/commander.js/blob/master/lib/option.js
MIT
env(name) { this.envVar = name; return this; }
Set environment variable to check for option value. An environment variable is only used if when processed the current option value is undefined, or the source of the current value is 'default' or 'config' or 'env'. @param {string} name @return {Option}
env
javascript
tj/commander.js
lib/option.js
https://github.com/tj/commander.js/blob/master/lib/option.js
MIT
argParser(fn) { this.parseArg = fn; return this; }
Set the custom handler for processing CLI option arguments into option values. @param {Function} [fn] @return {Option}
argParser
javascript
tj/commander.js
lib/option.js
https://github.com/tj/commander.js/blob/master/lib/option.js
MIT
makeOptionMandatory(mandatory = true) { this.mandatory = !!mandatory; return this; }
Whether the option is mandatory and must have a value after parsing. @param {boolean} [mandatory=true] @return {Option}
makeOptionMandatory
javascript
tj/commander.js
lib/option.js
https://github.com/tj/commander.js/blob/master/lib/option.js
MIT
hideHelp(hide = true) { this.hidden = !!hide; return this; }
Hide option in help. @param {boolean} [hide=true] @return {Option}
hideHelp
javascript
tj/commander.js
lib/option.js
https://github.com/tj/commander.js/blob/master/lib/option.js
MIT
choices(values) { this.argChoices = values.slice(); this.parseArg = (arg, previous) => { if (!this.argChoices.includes(arg)) { throw new InvalidArgumentError( `Allowed choices are ${this.argChoices.join(', ')}.`, ); } if (this.variadic) { return this._concatValue(arg, previous); } return arg; }; return this; }
Only allow option value to be one of choices. @param {string[]} values @return {Option}
choices
javascript
tj/commander.js
lib/option.js
https://github.com/tj/commander.js/blob/master/lib/option.js
MIT
attributeName() { if (this.negate) { return camelcase(this.name().replace(/^no-/, '')); } return camelcase(this.name()); }
Return option name, in a camelcase format that can be used as an object attribute key. @return {string}
attributeName
javascript
tj/commander.js
lib/option.js
https://github.com/tj/commander.js/blob/master/lib/option.js
MIT
helpGroup(heading) { this.helpGroupHeading = heading; return this; }
Set the help group heading. @param {string} heading @return {Option}
helpGroup
javascript
tj/commander.js
lib/option.js
https://github.com/tj/commander.js/blob/master/lib/option.js
MIT
is(arg) { return this.short === arg || this.long === arg; }
Check if `arg` matches the short or long flag. @param {string} arg @return {boolean} @package
is
javascript
tj/commander.js
lib/option.js
https://github.com/tj/commander.js/blob/master/lib/option.js
MIT
isBoolean() { return !this.required && !this.optional && !this.negate; }
Return whether a boolean option. Options are one of boolean, negated, required argument, or optional argument. @return {boolean} @package
isBoolean
javascript
tj/commander.js
lib/option.js
https://github.com/tj/commander.js/blob/master/lib/option.js
MIT
valueFromOption(value, option) { const optionKey = option.attributeName(); if (!this.dualOptions.has(optionKey)) return true; // Use the value to deduce if (probably) came from the option. const preset = this.negativeOptions.get(optionKey).presetArg; const negativeValue = preset !== undefined ? preset : false; return option.negate === (negativeValue === value); }
Did the value come from the option, and not from possible matching dual option? @param {*} value @param {Option} option @returns {boolean}
valueFromOption
javascript
tj/commander.js
lib/option.js
https://github.com/tj/commander.js/blob/master/lib/option.js
MIT
function camelcase(str) { return str.split('-').reduce((str, word) => { return str + word[0].toUpperCase() + word.slice(1); }); }
Convert string from kebab-case to camelCase. @param {string} str @return {string} @private
camelcase
javascript
tj/commander.js
lib/option.js
https://github.com/tj/commander.js/blob/master/lib/option.js
MIT
function splitOptionFlags(flags) { let shortFlag; let longFlag; // short flag, single dash and single character const shortFlagExp = /^-[^-]$/; // long flag, double dash and at least one character const longFlagExp = /^--[^-]/; const flagParts = flags.split(/[ |,]+/).concat('guard'); // Normal is short and/or long. if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift(); if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift(); // Long then short. Rarely used but fine. if (!shortFlag && shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift(); // Allow two long flags, like '--ws, --workspace' // This is the supported way to have a shortish option flag. if (!shortFlag && longFlagExp.test(flagParts[0])) { shortFlag = longFlag; longFlag = flagParts.shift(); } // Check for unprocessed flag. Fail noisily rather than silently ignore. if (flagParts[0].startsWith('-')) { const unsupportedFlag = flagParts[0]; const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`; if (/^-[^-][^-]/.test(unsupportedFlag)) throw new Error( `${baseError} - a short flag is a single dash and a single character - either use a single dash and a single character (for a short flag) - or use a double dash for a long option (and can have two, like '--ws, --workspace')`, ); if (shortFlagExp.test(unsupportedFlag)) throw new Error(`${baseError} - too many short flags`); if (longFlagExp.test(unsupportedFlag)) throw new Error(`${baseError} - too many long flags`); throw new Error(`${baseError} - unrecognised flag format`); } if (shortFlag === undefined && longFlag === undefined) throw new Error( `option creation failed due to no flags found in '${flags}'.`, ); return { shortFlag, longFlag }; }
Split the short and long flag out of something like '-m,--mixed <value>' @private
splitOptionFlags
javascript
tj/commander.js
lib/option.js
https://github.com/tj/commander.js/blob/master/lib/option.js
MIT
function suggestSimilar(word, candidates) { if (!candidates || candidates.length === 0) return ''; // remove possible duplicates candidates = Array.from(new Set(candidates)); const searchingOptions = word.startsWith('--'); if (searchingOptions) { word = word.slice(2); candidates = candidates.map((candidate) => candidate.slice(2)); } let similar = []; let bestDistance = maxDistance; const minSimilarity = 0.4; candidates.forEach((candidate) => { if (candidate.length <= 1) return; // no one character guesses const distance = editDistance(word, candidate); const length = Math.max(word.length, candidate.length); const similarity = (length - distance) / length; if (similarity > minSimilarity) { if (distance < bestDistance) { // better edit distance, throw away previous worse matches bestDistance = distance; similar = [candidate]; } else if (distance === bestDistance) { similar.push(candidate); } } }); similar.sort((a, b) => a.localeCompare(b)); if (searchingOptions) { similar = similar.map((candidate) => `--${candidate}`); } if (similar.length > 1) { return `\n(Did you mean one of ${similar.join(', ')}?)`; } if (similar.length === 1) { return `\n(Did you mean ${similar[0]}?)`; } return ''; }
Find close matches, restricted to same number of edits. @param {string} word @param {string[]} candidates @returns {string}
suggestSimilar
javascript
tj/commander.js
lib/suggestSimilar.js
https://github.com/tj/commander.js/blob/master/lib/suggestSimilar.js
MIT
get_date_offset = function (date) { var offset = -date.getTimezoneOffset(); return (offset !== null ? offset : 0); }
Gets the offset in minutes from UTC for a certain date. @param {Date} date @returns {Number}
get_date_offset
javascript
Serhioromano/bootstrap-calendar
components/jstimezonedetect/jstz.js
https://github.com/Serhioromano/bootstrap-calendar/blob/master/components/jstimezonedetect/jstz.js
MIT
get_date = function (year, month, date) { var d = new Date(); if (year !== undefined) { d.setFullYear(year); } d.setMonth(month); d.setDate(date); return d; }
Gets the offset in minutes from UTC for a certain date. @param {Date} date @returns {Number}
get_date
javascript
Serhioromano/bootstrap-calendar
components/jstimezonedetect/jstz.js
https://github.com/Serhioromano/bootstrap-calendar/blob/master/components/jstimezonedetect/jstz.js
MIT
get_january_offset = function (year) { return get_date_offset(get_date(year, 0 ,2)); }
Gets the offset in minutes from UTC for a certain date. @param {Date} date @returns {Number}
get_january_offset
javascript
Serhioromano/bootstrap-calendar
components/jstimezonedetect/jstz.js
https://github.com/Serhioromano/bootstrap-calendar/blob/master/components/jstimezonedetect/jstz.js
MIT
get_june_offset = function (year) { return get_date_offset(get_date(year, 5, 2)); }
Gets the offset in minutes from UTC for a certain date. @param {Date} date @returns {Number}
get_june_offset
javascript
Serhioromano/bootstrap-calendar
components/jstimezonedetect/jstz.js
https://github.com/Serhioromano/bootstrap-calendar/blob/master/components/jstimezonedetect/jstz.js
MIT
date_is_dst = function (date) { var is_southern = date.getMonth() > 7, base_offset = is_southern ? get_june_offset(date.getFullYear()) : get_january_offset(date.getFullYear()), date_offset = get_date_offset(date), is_west = base_offset < 0, dst_offset = base_offset - date_offset; if (!is_west && !is_southern) { return dst_offset < 0; } return dst_offset !== 0; }
Private method. Checks whether a given date is in daylight saving time. If the date supplied is after august, we assume that we're checking for southern hemisphere DST. @param {Date} date @returns {Boolean}
date_is_dst
javascript
Serhioromano/bootstrap-calendar
components/jstimezonedetect/jstz.js
https://github.com/Serhioromano/bootstrap-calendar/blob/master/components/jstimezonedetect/jstz.js
MIT
lookup_key = function () { var january_offset = get_january_offset(), june_offset = get_june_offset(), diff = january_offset - june_offset; if (diff < 0) { return january_offset + ",1"; } else if (diff > 0) { return june_offset + ",1," + HEMISPHERE_SOUTH; } return january_offset + ",0"; }
This function does some basic calculations to create information about the user's timezone. It uses REFERENCE_YEAR as a solid year for which the script has been tested rather than depend on the year set by the client device. Returns a key that can be used to do lookups in jstz.olson.timezones. eg: "720,1,2". @returns {String}
lookup_key
javascript
Serhioromano/bootstrap-calendar
components/jstimezonedetect/jstz.js
https://github.com/Serhioromano/bootstrap-calendar/blob/master/components/jstimezonedetect/jstz.js
MIT
dst_start_for = function (tz_name) { var ru_pre_dst_change = new Date(2010, 6, 15, 1, 0, 0, 0), // In 2010 Russia had DST, this allows us to detect Russia :) dst_starts = { 'America/Denver': new Date(2011, 2, 13, 3, 0, 0, 0), 'America/Mazatlan': new Date(2011, 3, 3, 3, 0, 0, 0), 'America/Chicago': new Date(2011, 2, 13, 3, 0, 0, 0), 'America/Mexico_City': new Date(2011, 3, 3, 3, 0, 0, 0), 'America/Asuncion': new Date(2012, 9, 7, 3, 0, 0, 0), 'America/Santiago': new Date(2012, 9, 3, 3, 0, 0, 0), 'America/Campo_Grande': new Date(2012, 9, 21, 5, 0, 0, 0), 'America/Montevideo': new Date(2011, 9, 2, 3, 0, 0, 0), 'America/Sao_Paulo': new Date(2011, 9, 16, 5, 0, 0, 0), 'America/Los_Angeles': new Date(2011, 2, 13, 8, 0, 0, 0), 'America/Santa_Isabel': new Date(2011, 3, 5, 8, 0, 0, 0), 'America/Havana': new Date(2012, 2, 10, 2, 0, 0, 0), 'America/New_York': new Date(2012, 2, 10, 7, 0, 0, 0), 'Europe/Helsinki': new Date(2013, 2, 31, 5, 0, 0, 0), 'Pacific/Auckland': new Date(2011, 8, 26, 7, 0, 0, 0), 'America/Halifax': new Date(2011, 2, 13, 6, 0, 0, 0), 'America/Goose_Bay': new Date(2011, 2, 13, 2, 1, 0, 0), 'America/Miquelon': new Date(2011, 2, 13, 5, 0, 0, 0), 'America/Godthab': new Date(2011, 2, 27, 1, 0, 0, 0), 'Europe/Moscow': ru_pre_dst_change, 'Asia/Amman': new Date(2013, 2, 29, 1, 0, 0, 0), 'Asia/Beirut': new Date(2013, 2, 31, 2, 0, 0, 0), 'Asia/Damascus': new Date(2013, 3, 6, 2, 0, 0, 0), 'Asia/Jerusalem': new Date(2013, 2, 29, 5, 0, 0, 0), 'Asia/Yekaterinburg': ru_pre_dst_change, 'Asia/Omsk': ru_pre_dst_change, 'Asia/Krasnoyarsk': ru_pre_dst_change, 'Asia/Irkutsk': ru_pre_dst_change, 'Asia/Yakutsk': ru_pre_dst_change, 'Asia/Vladivostok': ru_pre_dst_change, 'Asia/Baku': new Date(2013, 2, 31, 4, 0, 0), 'Asia/Yerevan': new Date(2013, 2, 31, 3, 0, 0), 'Asia/Kamchatka': ru_pre_dst_change, 'Asia/Gaza': new Date(2010, 2, 27, 4, 0, 0), 'Africa/Cairo': new Date(2010, 4, 1, 3, 0, 0), 'Europe/Minsk': ru_pre_dst_change, 'Pacific/Apia': new Date(2010, 10, 1, 1, 0, 0, 0), 'Pacific/Fiji': new Date(2010, 11, 1, 0, 0, 0), 'Australia/Perth': new Date(2008, 10, 1, 1, 0, 0, 0) }; return dst_starts[tz_name]; }
This object contains information on when daylight savings starts for different timezones. The list is short for a reason. Often we do not have to be very specific to single out the correct timezone. But when we do, this list comes in handy. Each value is a date denoting when daylight savings starts for that timezone.
dst_start_for
javascript
Serhioromano/bootstrap-calendar
components/jstimezonedetect/jstz.js
https://github.com/Serhioromano/bootstrap-calendar/blob/master/components/jstimezonedetect/jstz.js
MIT
ambiguity_check = function () { var ambiguity_list = AMBIGUITIES[timezone_name], length = ambiguity_list.length, i = 0, tz = ambiguity_list[0]; for (; i < length; i += 1) { tz = ambiguity_list[i]; if (jstz.date_is_dst(jstz.dst_start_for(tz))) { timezone_name = tz; return; } } }
Checks if a timezone has possible ambiguities. I.e timezones that are similar. For example, if the preliminary scan determines that we're in America/Denver. We double check here that we're really there and not in America/Mazatlan. This is done by checking known dates for when daylight savings start for different timezones during 2010 and 2011.
ambiguity_check
javascript
Serhioromano/bootstrap-calendar
components/jstimezonedetect/jstz.js
https://github.com/Serhioromano/bootstrap-calendar/blob/master/components/jstimezonedetect/jstz.js
MIT
is_ambiguous = function () { return typeof (AMBIGUITIES[timezone_name]) !== 'undefined'; }
Checks if it is possible that the timezone is ambiguous.
is_ambiguous
javascript
Serhioromano/bootstrap-calendar
components/jstimezonedetect/jstz.js
https://github.com/Serhioromano/bootstrap-calendar/blob/master/components/jstimezonedetect/jstz.js
MIT
function buildEventsUrl(events_url, data) { var separator, key, url; url = events_url; separator = (events_url.indexOf('?') < 0) ? '?' : '&'; for(key in data) { url += separator + key + '=' + encodeURIComponent(data[key]); separator = '&'; } return url; }
Bootstrap based calendar full view. https://github.com/Serhioromano/bootstrap-calendar User: Sergey Romanov <[email protected]>
buildEventsUrl
javascript
Serhioromano/bootstrap-calendar
js/calendar.js
https://github.com/Serhioromano/bootstrap-calendar/blob/master/js/calendar.js
MIT
function getExtentedOption(cal, option_name) { var fromOptions = (cal.options[option_name] != null) ? cal.options[option_name] : null; var fromLanguage = (cal.locale[option_name] != null) ? cal.locale[option_name] : null; if((option_name == 'holidays') && cal.options.merge_holidays) { var holidays = {}; $.extend(true, holidays, fromLanguage ? fromLanguage : defaults_extended.holidays); if(fromOptions) { $.extend(true, holidays, fromOptions); } return holidays; } else { if(fromOptions != null) { return fromOptions; } if(fromLanguage != null) { return fromLanguage; } return defaults_extended[option_name]; } }
Bootstrap based calendar full view. https://github.com/Serhioromano/bootstrap-calendar User: Sergey Romanov <[email protected]>
getExtentedOption
javascript
Serhioromano/bootstrap-calendar
js/calendar.js
https://github.com/Serhioromano/bootstrap-calendar/blob/master/js/calendar.js
MIT
function getHolidays(cal, year) { var hash = []; var holidays_def = getExtentedOption(cal, 'holidays'); for(var k in holidays_def) { hash.push(k + ':' + holidays_def[k]); } hash.push(year); hash = hash.join('|'); if(hash in getHolidays.cache) { return getHolidays.cache[hash]; } var holidays = []; $.each(holidays_def, function(key, name) { var firstDay = null, lastDay = null, failed = false; $.each(key.split('>'), function(i, chunk) { var m, date = null; if(m = /^(\d\d)-(\d\d)$/.exec(chunk)) { date = new Date(year, parseInt(m[2], 10) - 1, parseInt(m[1], 10)); } else if(m = /^(\d\d)-(\d\d)-(\d\d\d\d)$/.exec(chunk)) { if(parseInt(m[3], 10) == year) { date = new Date(year, parseInt(m[2], 10) - 1, parseInt(m[1], 10)); } } else if(m = /^easter(([+\-])(\d+))?$/.exec(chunk)) { date = getEasterDate(year, m[1] ? parseInt(m[1], 10) : 0); } else if(m = /^(\d\d)([+\-])([1-5])\*([0-6])$/.exec(chunk)) { var month = parseInt(m[1], 10) - 1; var direction = m[2]; var offset = parseInt(m[3]); var weekday = parseInt(m[4]); switch(direction) { case '+': var d = new Date(year, month, 1 - 7); while(d.getDay() != weekday) { d = new Date(d.getFullYear(), d.getMonth(), d.getDate() + 1); } date = new Date(d.getFullYear(), d.getMonth(), d.getDate() + 7 * offset); break; case '-': var d = new Date(year, month + 1, 0 + 7); while(d.getDay() != weekday) { d = new Date(d.getFullYear(), d.getMonth(), d.getDate() - 1); } date = new Date(d.getFullYear(), d.getMonth(), d.getDate() - 7 * offset); break; } } if(!date) { warn('Unknown holiday: ' + key); failed = true; return false; } switch(i) { case 0: firstDay = date; break; case 1: if(date.getTime() <= firstDay.getTime()) { warn('Unknown holiday: ' + key); failed = true; return false; } lastDay = date; break; default: warn('Unknown holiday: ' + key); failed = true; return false; } }); if(!failed) { var days = []; if(lastDay) { for(var date = new Date(firstDay.getTime()); date.getTime() <= lastDay.getTime(); date.setDate(date.getDate() + 1)) { days.push(new Date(date.getTime())); } } else { days.push(firstDay); } holidays.push({name: name, days: days}); } }); getHolidays.cache[hash] = holidays; return getHolidays.cache[hash]; }
Bootstrap based calendar full view. https://github.com/Serhioromano/bootstrap-calendar User: Sergey Romanov <[email protected]>
getHolidays
javascript
Serhioromano/bootstrap-calendar
js/calendar.js
https://github.com/Serhioromano/bootstrap-calendar/blob/master/js/calendar.js
MIT
function warn(message) { if($.type(window.console) == 'object' && $.type(window.console.warn) == 'function') { window.console.warn('[Bootstrap-Calendar] ' + message); } }
Bootstrap based calendar full view. https://github.com/Serhioromano/bootstrap-calendar User: Sergey Romanov <[email protected]>
warn
javascript
Serhioromano/bootstrap-calendar
js/calendar.js
https://github.com/Serhioromano/bootstrap-calendar/blob/master/js/calendar.js
MIT
function Calendar(params, context) { this.options = $.extend(true, {position: {start: new Date(), end: new Date()}}, defaults, params); this.setLanguage(this.options.language); this.context = context; context.css('width', this.options.width).addClass('cal-context'); this.view(); return this; }
Bootstrap based calendar full view. https://github.com/Serhioromano/bootstrap-calendar User: Sergey Romanov <[email protected]>
Calendar
javascript
Serhioromano/bootstrap-calendar
js/calendar.js
https://github.com/Serhioromano/bootstrap-calendar/blob/master/js/calendar.js
MIT
addClass = function(which, to) { var cls; cls = (self.options.classes && (class_group in self.options.classes) && (which in self.options.classes[class_group])) ? self.options.classes[class_group][which] : ""; if((typeof(cls) == "string") && cls.length) { to.push(cls); } }
Bootstrap based calendar full view. https://github.com/Serhioromano/bootstrap-calendar User: Sergey Romanov <[email protected]>
addClass
javascript
Serhioromano/bootstrap-calendar
js/calendar.js
https://github.com/Serhioromano/bootstrap-calendar/blob/master/js/calendar.js
MIT
function showEventsList(event, that, slider, self) { event.stopPropagation(); var that = $(that); var cell = that.closest('.cal-cell'); var row = cell.closest('.cal-before-eventlist'); var tick_position = cell.data('cal-row'); that.fadeOut('fast'); slider.slideUp('fast', function() { var event_list = $('.events-list', cell); slider.html(self.options.templates['events-list']({ cal: self, events: self.getEventsBetween(parseInt(event_list.data('cal-start')), parseInt(event_list.data('cal-end'))) })); row.after(slider); self.activecell = $('[data-cal-date]', cell).text(); $('#cal-slide-tick').addClass('tick' + tick_position).show(); slider.slideDown('fast', function() { $('body').one('click', function() { slider.slideUp('fast'); self.activecell = 0; }); }); }); // Wait 400ms before updating the modal & attach the mouseenter&mouseleave(400ms is the time for the slider to fade out and slide up) setTimeout(function() { $('a.event-item').mouseenter(function() { $('a[data-event-id="' + $(this).data('event-id') + '"]').closest('.cal-cell1').addClass('day-highlight dh-' + $(this).data('event-class')); }); $('a.event-item').mouseleave(function() { $('div.cal-cell1').removeClass('day-highlight dh-' + $(this).data('event-class')); }); self._update_modal(); }, 400); }
Bootstrap based calendar full view. https://github.com/Serhioromano/bootstrap-calendar User: Sergey Romanov <[email protected]>
showEventsList
javascript
Serhioromano/bootstrap-calendar
js/calendar.js
https://github.com/Serhioromano/bootstrap-calendar/blob/master/js/calendar.js
MIT
function getEasterDate(year, offsetDays) { var a = year % 19; var b = Math.floor(year / 100); var c = year % 100; var d = Math.floor(b / 4); var e = b % 4; var f = Math.floor((b + 8) / 25); var g = Math.floor((b - f + 1) / 3); var h = (19 * a + b - d - g + 15) % 30; var i = Math.floor(c / 4); var k = c % 4; var l = (32 + 2 * e + 2 * i - h - k) % 7; var m = Math.floor((a + 11 * h + 22 * l) / 451); var n0 = (h + l + 7 * m + 114) var n = Math.floor(n0 / 31) - 1; var p = n0 % 31 + 1; return new Date(year, n, p + (offsetDays ? offsetDays : 0), 0, 0, 0); }
Bootstrap based calendar full view. https://github.com/Serhioromano/bootstrap-calendar User: Sergey Romanov <[email protected]>
getEasterDate
javascript
Serhioromano/bootstrap-calendar
js/calendar.js
https://github.com/Serhioromano/bootstrap-calendar/blob/master/js/calendar.js
MIT
function _getPathFromNpm () { return new Promise((resolve) => { exec('npm config --global get prefix', (err, stdout) => { if (err) { resolve(null) } else { const npmPath = stdout.replace(/\n/, '') debug(`PowerShell: _getPathFromNpm() resolving with: ${npmPath}`) resolve(npmPath) } }) }) }
Attempts to get npm's path by calling out to "npm config" @returns {Promise.<string>} - Promise that resolves with the found path (or null if not found)
_getPathFromNpm
javascript
felixrieseberg/npm-windows-upgrade
src/find-npm.js
https://github.com/felixrieseberg/npm-windows-upgrade/blob/master/src/find-npm.js
MIT
function _getPathFromPowerShell () { return new Promise(resolve => { const psArgs = 'Get-Command npm | Select-Object -ExpandProperty Definition' const args = [ '-NoProfile', '-NoLogo', psArgs ] const child = spawn('powershell.exe', args) let stdout = [] let stderr = [] child.stdout.on('data', (data) => { debug(`PowerShell: Stdout received: ${data.toString()}`) stdout.push(data.toString()) }) child.stderr.on('data', (data) => { debug(`PowerShell: Stderr received: ${data.toString()}`) stderr.push(data.toString()) }) child.on('exit', () => { const cmdPath = (stdout[0] && stdout[0].trim) ? stdout[0].trim() : null if (stderr.length === 0 && cmdPath && cmdPath.slice(cmdPath.length - 7) === 'npm.cmd') { // We're probably installed in a location like C:\Program Files\nodejs\npm.cmd, // meaning that we should not use the global prefix installation location const npmPath = cmdPath.slice(0, cmdPath.length - 8) debug(`PowerShell: _getPathFromPowerShell() resolving with: ${npmPath}`) resolve(npmPath) } else { resolve(null) } }) child.stdin.end() }) }
Attempts to get npm's path by calling out to "Get-Command npm" @returns {Promise.<string>} - Promise that resolves with the found path (or null if not found)
_getPathFromPowerShell
javascript
felixrieseberg/npm-windows-upgrade
src/find-npm.js
https://github.com/felixrieseberg/npm-windows-upgrade/blob/master/src/find-npm.js
MIT
function _getPath () { return Promise.all([_getPathFromPowerShell(), _getPathFromNpm()]) .then((results) => { const fromNpm = results[1] || '' const fromPowershell = results[0] || '' // Quickly check if there's an npm folder in there const fromPowershellPath = path.join(fromPowershell, 'node_modules', 'npm') const fromNpmPath = path.join(fromNpm, 'node_modules', 'npm') const isFromPowershell = utils.isPathAccessible(fromPowershellPath) const isFromNpm = utils.isPathAccessible(fromNpmPath) // Found in... // Powershell: -> return powershell path // npm: -> return npm path // nowhere: -> return powershell path if (isFromPowershell) { return { path: fromPowershell, message: strings.npmFoundIn(fromPowershell, fromNpm, fromPowershell) } } else if (isFromNpm) { return { path: fromNpm, message: strings.npmFoundIn(fromPowershell, fromNpm, fromNpm) } } else { return { path: fromPowershell, message: strings.npmNotFoundGuessing(fromPowershell, fromNpm, fromPowershell) } } }) }
Attempts to get the current installation location of npm by looking up the global prefix. Prefer PowerShell, be falls back to npm's opinion @return {Promise.<string>} - NodeJS installation path
_getPath
javascript
felixrieseberg/npm-windows-upgrade
src/find-npm.js
https://github.com/felixrieseberg/npm-windows-upgrade/blob/master/src/find-npm.js
MIT
function _checkPath (npmPath) { return new Promise((resolve, reject) => { if (npmPath) { fs.lstat(npmPath, (err, stats) => { if (err || !stats || (stats.isDirectory && !stats.isDirectory())) { reject(new Error(strings.givenPathNotValid(npmPath))) } else { resolve({ path: npmPath, message: strings.givenPathValid(npmPath) }) } }) } else { reject(new Error('Called _checkPath() with insufficient parameters')) } }) }
Attempts to get npm's path by calling out to "npm config" @param {string} npmPath - Input path if given by user @returns {Promise.<string>}
_checkPath
javascript
felixrieseberg/npm-windows-upgrade
src/find-npm.js
https://github.com/felixrieseberg/npm-windows-upgrade/blob/master/src/find-npm.js
MIT
function findNpm (npmPath) { if (npmPath) { return _checkPath(npmPath) } else { return _getPath() } }
Finds npm - either by checking a given path, or by asking the system for the location @param {string} npmPath - Input path if given by user @returns {Promise.<string>}
findNpm
javascript
felixrieseberg/npm-windows-upgrade
src/find-npm.js
https://github.com/felixrieseberg/npm-windows-upgrade/blob/master/src/find-npm.js
MIT
function runUpgrade (version, npmPath) { return new Promise((resolve, reject) => { const scriptPath = path.resolve(__dirname, '../powershell/upgrade-npm.ps1') const psArgs = npmPath === null ? `& {& '${scriptPath}' -version '${version}' }` : `& {& '${scriptPath}' -version '${version}' -NodePath '${npmPath}' }` const args = [ '-ExecutionPolicy', 'Bypass', '-NoProfile', '-NoLogo', psArgs ] if (process.env.DEBUG) { args.push('-debug') } let stdout = [] let stderr = [] let child try { child = spawn('powershell.exe', args) } catch (error) { return reject(error) } child.stdout.on('data', (data) => { debug('PowerShell: Stdout received: ' + data.toString()) stdout.push(data.toString()) }) child.stderr.on('data', (data) => { debug('PowerShell: Stderr received: ' + data.toString()) stderr.push(data.toString()) }) child.on('exit', () => resolve({ stderr, stdout })) child.stdin.end() }) }
Executes the PS1 script upgrading npm @param {string} version - The version to be installed (npm install npm@{version}) @param {string} npmPath - Path to Node installation (optional) @return {Promise.<stderr[], stdout[]>} - stderr and stdout received from the PS1 process
runUpgrade
javascript
felixrieseberg/npm-windows-upgrade
src/powershell.js
https://github.com/felixrieseberg/npm-windows-upgrade/blob/master/src/powershell.js
MIT
function runSimpleUpgrade (version) { return new Promise((resolve) => { let npmCommand = (version) ? `npm install -g npm@${version}` : 'npm install -g npm' let stdout = [] let stderr = [] let child try { child = spawn('powershell.exe', [ '-NoProfile', '-NoLogo', npmCommand ]) } catch (error) { // This is dirty, but the best way for us to try/catch right now resolve({ error }) } child.stdout.on('data', (data) => stdout.push(data.toString())) child.stderr.on('data', (data) => stderr.push(data.toString())) child.on('exit', () => resolve({ stderr, stdout })) child.stdin.end() }) }
Executes 'npm install -g npm' upgrading npm @param {string} version - The version to be installed (npm install npm@{version}) @return {Promise.<stderr[], stdout[]>} - stderr and stdout received from the PS1 process
runSimpleUpgrade
javascript
felixrieseberg/npm-windows-upgrade
src/powershell.js
https://github.com/felixrieseberg/npm-windows-upgrade/blob/master/src/powershell.js
MIT
async ensureInternet () { if (this.options.dnsCheck !== false) { const isOnline = await utils.checkInternetConnection() if (!isOnline) { utils.exit(1, strings.noInternet) } } }
Executes the upgrader's "let's check the user's internet" logic, eventually quietly resolving or quitting the process with an error if the connection is not sufficient
ensureInternet
javascript
felixrieseberg/npm-windows-upgrade
src/upgrader.js
https://github.com/felixrieseberg/npm-windows-upgrade/blob/master/src/upgrader.js
MIT
async ensureExecutionPolicy () { if (this.options.executionPolicyCheck !== false) { try { const isExecutable = await utils.checkExecutionPolicy() if (!isExecutable) { utils.exit(1, strings.noExecutionPolicy) } } catch (err) { utils.exit(1, strings.executionPolicyCheckError, err) } } }
Executes the upgrader's "let's check the user's powershell execution policy" logic, eventually quietly resolving or quitting the process with an error if the policy is not sufficient
ensureExecutionPolicy
javascript
felixrieseberg/npm-windows-upgrade
src/upgrader.js
https://github.com/felixrieseberg/npm-windows-upgrade/blob/master/src/upgrader.js
MIT
async wasUpgradeSuccessful () { this.installedVersion = await versions.getInstalledNPMVersion() return (this.installedVersion === this.options.npmVersion) }
Checks if the upgrade was successful @return {boolean} - was the upgrade successful?
wasUpgradeSuccessful
javascript
felixrieseberg/npm-windows-upgrade
src/upgrader.js
https://github.com/felixrieseberg/npm-windows-upgrade/blob/master/src/upgrader.js
MIT
async chooseVersion () { if (!this.options.npmVersion) { const availableVersions = await versions.getAvailableNPMVersions() const versionList = [{ type: 'list', name: 'version', message: 'Which version do you want to install?', choices: availableVersions.reverse() }] this.options.npmVersion = await inquirer.prompt(versionList) .then(answer => answer.version) } if (this.options.npmVersion === 'latest') { this.options.npmVersion = await versions.getLatestNPMVersion() } }
Executes the upgrader's "let's have the user choose a version" logic
chooseVersion
javascript
felixrieseberg/npm-windows-upgrade
src/upgrader.js
https://github.com/felixrieseberg/npm-windows-upgrade/blob/master/src/upgrader.js
MIT
async choosePath () { try { const npmPaths = await findNpm(this.options.npmPath) this.log(npmPaths.message) this.options.npmPath = npmPaths.path debug(`Upgrader: Chosen npm path: ${this.options.npmPath}`) } catch (err) { utils.exit(1, err) } }
Executes the upgrader's "let's find npm" logic
choosePath
javascript
felixrieseberg/npm-windows-upgrade
src/upgrader.js
https://github.com/felixrieseberg/npm-windows-upgrade/blob/master/src/upgrader.js
MIT
async upgradeSimple () { this.spinner = new Spinner(`${strings.startingUpgradeSimple} %s`) if (this.options.spinner === false) { console.log(strings.startingUpgradeSimple) } else { this.spinner.start() } const output = await powershell.runSimpleUpgrade(this.options.npmVersion) this.spinner.stop(false) console.log('\n') if (output.error) { throw output.error } }
Attempts a simple upgrade, eventually calling npm install -g npm @param {string} version - Version that should be installed @private
upgradeSimple
javascript
felixrieseberg/npm-windows-upgrade
src/upgrader.js
https://github.com/felixrieseberg/npm-windows-upgrade/blob/master/src/upgrader.js
MIT
async upgradeComplex () { this.spinner = new Spinner(`${strings.startingUpgradeComplex} %s`) if (this.options.spinner === false) { console.log(strings.startingUpgradeComplex) } else { this.spinner.start() } const output = await powershell.runUpgrade(this.options.npmVersion, this.options.npmPath) this.spinner.stop(false) console.log('\n') // If we failed to elevate to administrative rights, we have to abort. if (output.stdout[0] && output.stdout[0].includes('NOTADMIN')) { utils.exit(1, strings.noAdmin) } }
Upgrades npm in the correct directory, securing and reapplying existing configuration @param {string} version - Version that should be installed @param {string} npmPath - Path where npm should be installed @private
upgradeComplex
javascript
felixrieseberg/npm-windows-upgrade
src/upgrader.js
https://github.com/felixrieseberg/npm-windows-upgrade/blob/master/src/upgrader.js
MIT
log (message) { if (!this.options.quiet) { console.log(message) } }
Logs a message to console, unless the user specified quiet mode @param {string} message - message to log @private
log
javascript
felixrieseberg/npm-windows-upgrade
src/upgrader.js
https://github.com/felixrieseberg/npm-windows-upgrade/blob/master/src/upgrader.js
MIT
logUpgradeFailure (...errors) { // Uh-oh, something didn't work as it should have. versions.getVersions().then((debugVersions) => { let info if (this.options.npmVersion && this.installedVersion) { info = `You wanted to install npm ${this.options.npmVersion}, but the installed version is ${this.installedVersion}.\n\n` info += 'A common reason is an attempted "npm install npm" or "npm upgrade npm". ' info += 'As of today, the only solution is to completely uninstall and then reinstall Node.js. ' info += 'For a small tutorial, please see https://github.com/felixrieseberg/npm-windows-upgrade#fix-an-attempted-upgrade.\n' } else if (this.options.npmVersion) { info = `You wanted to install npm ${this.options.npmVersion}, but we could not confirm that the installation succeeded.` } else { info = 'We encountered an error during installation.\n' } info += '\nPlease consider reporting your trouble to https://aka.ms/npm-issues.' console.log(chalk.red(info)) console.log(chalk.bold('\nDebug Information:\n')) console.log(debugVersions) if (errors && errors.length && errors.length > 0) console.log('Here is the error:') // If we just got an error string (we shouldn't handle that) if (typeof errors !== 'string') { console.log('\n' + errors + '\n') return process.exit(1) } for (let i = 0; i < errors.length; i++) { console.log('\n' + errors[i] + '\n') } setTimeout(() => { process.exit(1) }, 1000) }) }
If the whole upgrade failed, we use this method to log a detailed trace with versions - all to make it easier for users to create meaningful issues. @param errors {array} - AS many errors as found
logUpgradeFailure
javascript
felixrieseberg/npm-windows-upgrade
src/upgrader.js
https://github.com/felixrieseberg/npm-windows-upgrade/blob/master/src/upgrader.js
MIT
function exit (status, ...messages) { if (messages) { messages.forEach(message => console.log(message)) } process.exit(status) }
Exits the process with a given status, logging a given message before exiting. @param {number} status - exit status @param {string} messages - message to log
exit
javascript
felixrieseberg/npm-windows-upgrade
src/utils.js
https://github.com/felixrieseberg/npm-windows-upgrade/blob/master/src/utils.js
MIT
function checkInternetConnection () { return new Promise((resolve) => { require('dns').lookup('microsoft.com', (err) => { if (err && err.code === 'ENOTFOUND') { resolve(false) } else { resolve(true) } }) }) }
Checks for an active Internet connection by doing a DNS lookup of Microsoft.com. @return {Promise.<boolean>} - True if lookup succeeded (or if we skip the test)
checkInternetConnection
javascript
felixrieseberg/npm-windows-upgrade
src/utils.js
https://github.com/felixrieseberg/npm-windows-upgrade/blob/master/src/utils.js
MIT
function checkExecutionPolicy () { return new Promise((resolve, reject) => { let output = [] let child try { debug('Powershell: Attempting to spawn PowerShell child') child = spawn('powershell.exe', ['-NoProfile', '-NoLogo', 'Get-ExecutionPolicy']) } catch (error) { debug('Powershell: Could not spawn PowerShell child') reject(error) } child.stdout.on('data', (data) => { debug('PowerShell: Stdout received: ' + data.toString()) output.push(data.toString()) }) child.stderr.on('data', (data) => { debug('PowerShell: Stderr received: ' + data.toString()) output.push(data.toString()) }) child.on('exit', () => { const linesHit = output.filter((line) => line.includes('Unrestricted') || line.includes('RemoteSigned') || line.includes('Bypass')) const unrestricted = (linesHit.length > 0) if (!unrestricted) { debug('PowerShell: Resolving restricted (false)') resolve(false) } else { debug('PowerShell: Resolving unrestricted (true)') resolve(true) } }) child.stdin.end() }) }
Checks the current Windows PS1 execution policy. The upgrader requires an unrestricted policy. @return {Promise.<boolean>} - True if unrestricted, false if it isn't
checkExecutionPolicy
javascript
felixrieseberg/npm-windows-upgrade
src/utils.js
https://github.com/felixrieseberg/npm-windows-upgrade/blob/master/src/utils.js
MIT
function isPathAccessible (filePath) { try { fs.accessSync(filePath) debug(`Utils: isPathAccessible(): ${filePath} exists`) return true } catch (err) { debug(`Utils: isPathAccessible(): ${filePath} does not exist`) return false } }
Checks if a path exists @param filePath - file path to check @returns {boolean} - does the file path exist?
isPathAccessible
javascript
felixrieseberg/npm-windows-upgrade
src/utils.js
https://github.com/felixrieseberg/npm-windows-upgrade/blob/master/src/utils.js
MIT
function getInstalledNPMVersion () { return new Promise((resolve, reject) => { let nodeVersion exec('npm -v', (err, stdout) => { if (err) { reject(new Error('Could not determine npm version.')) } else { nodeVersion = stdout.replace(/\n/, '') resolve(nodeVersion) } }) }) }
Gets the currently installed version of npm (npm -v) @return {Promise.<string>} - Installed version of npm
getInstalledNPMVersion
javascript
felixrieseberg/npm-windows-upgrade
src/versions.js
https://github.com/felixrieseberg/npm-windows-upgrade/blob/master/src/versions.js
MIT
function getAvailableNPMVersions () { return new Promise((resolve, reject) => { exec('npm view npm versions --json', (err, stdout) => { if (err) { let error = 'We could not show latest available versions. Try running this script again ' error += 'with the version you want to install (npm-windows-upgrade --npm-version 3.0.0)' return reject(error) } resolve(JSON.parse(stdout)) }) }) }
Fetches the published versions of npm from the npm registry @return {Promise.<versions[]>} - Array of the available versions
getAvailableNPMVersions
javascript
felixrieseberg/npm-windows-upgrade
src/versions.js
https://github.com/felixrieseberg/npm-windows-upgrade/blob/master/src/versions.js
MIT
function getLatestNPMVersion () { return new Promise((resolve, reject) => { exec('npm show npm version', (err, stdout) => { if (err) { let error = 'We could not show latest available versions. Try running this script again ' error += 'with the version you want to install (npm-windows-upgrade --npm-version 3.0.0)' return reject(error) } let latest = stdout.replace(/(\r\n|\n|\r)/gm, '') resolve(latest.trim()) }) }) }
Fetches the published versions of npm from the npm registry @return {Promise.<version>} - Array of the available versions
getLatestNPMVersion
javascript
felixrieseberg/npm-windows-upgrade
src/versions.js
https://github.com/felixrieseberg/npm-windows-upgrade/blob/master/src/versions.js
MIT
function _getWindowsVersion () { return new Promise((resolve, reject) => { const command = 'systeminfo | findstr /B /C:"OS Name" /C:"OS Version"' exec(command, (error, stdout) => { if (error) { reject(error) } else { resolve(stdout) } }) }) }
Get the current name and version of Windows
_getWindowsVersion
javascript
felixrieseberg/npm-windows-upgrade
src/versions.js
https://github.com/felixrieseberg/npm-windows-upgrade/blob/master/src/versions.js
MIT