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 ... | 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,
);
... | 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()] || '';
});
... | 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]' ... | 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 = ancestor... | 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 !== undefine... | 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 !==... | 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 v... | 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 outpu... | 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(w... | 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] === '[' ||... | 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... | 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
@... | 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 ===... | 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 ignor... | 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.impli... | 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... | 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._concatVa... | 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 ? pre... | 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... | 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((can... | 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),
... | 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) {
... | 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".
@return... | 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 D... | 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 ... | 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
time... | 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 <serg4172@mail.ru> | 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 = {};
$.e... | Bootstrap based calendar full view.
https://github.com/Serhioromano/bootstrap-calendar
User: Sergey Romanov <serg4172@mail.ru> | 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 = []... | Bootstrap based calendar full view.
https://github.com/Serhioromano/bootstrap-calendar
User: Sergey Romanov <serg4172@mail.ru> | 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 <serg4172@mail.ru> | 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 <serg4172@mail.ru> | 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 <serg4172@mail.ru> | 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... | Bootstrap based calendar full view.
https://github.com/Serhioromano/bootstrap-calendar
User: Sergey Romanov <serg4172@mail.ru> | 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 ... | Bootstrap based calendar full view.
https://github.com/Serhioromano/bootstrap-calendar
User: Sergey Romanov <serg4172@mail.ru> | 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... | 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'... | 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, 'n... | 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({
... | 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 '$... | 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 (e... | 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.executionPoli... | 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()
}... | 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)
thi... | 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.option... | 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 ${t... | 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('Powershel... | 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-win... | 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... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.