code
stringlengths
28
313k
docstring
stringlengths
25
85.3k
func_name
stringlengths
1
74
language
stringclasses
1 value
repo
stringlengths
5
60
path
stringlengths
4
172
url
stringlengths
44
218
license
stringclasses
7 values
function disableEventListeners() { if (this.state.eventsEnabled) { cancelAnimationFrame(this.scheduleUpdate); this.state = removeEventListeners(this.reference, this.state); } }
It will remove resize/scroll events and won't recalculate popper position when they are triggered. It also won't trigger `onUpdate` callback anymore, unless you call `update` method manually. @method @memberof Popper
disableEventListeners
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
function isNumeric(n) { return n !== '' && !isNaN(parseFloat(n)) && isFinite(n); }
Tells if a given input is a number @method @memberof Popper.Utils @param {*} input to check @return {Boolean}
isNumeric
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
function setStyles(element, styles) { Object.keys(styles).forEach(function (prop) { var unit = ''; // add unit if the value is numeric and is one of the following if (['width', 'height', 'top', 'right', 'bottom', 'left'].indexOf(prop) !== -1 && isNumeric(styles[prop])) { unit = 'px'; ...
Set the style to the given popper @method @memberof Popper.Utils @argument {Element} element - Element to apply the style to @argument {Object} styles Object with a list of properties and values which will be applied to the element
setStyles
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
function setAttributes(element, attributes) { Object.keys(attributes).forEach(function (prop) { var value = attributes[prop]; if (value !== false) { element.setAttribute(prop, attributes[prop]); } else { element.removeAttribute(prop); } }); }
Set the attributes to the given popper @method @memberof Popper.Utils @argument {Element} element - Element to apply the attributes to @argument {Object} styles Object with a list of properties and values which will be applied to the element
setAttributes
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
function applyStyle(data) { // any property present in `data.styles` will be applied to the popper, // in this way we can make the 3rd party modifiers add custom styles to it // Be aware, modifiers could override the properties defined in the previous // lines of this modifier! setStyles(data.instan...
@function @memberof Modifiers @argument {Object} data - The data object generated by `update` method @argument {Object} data.styles - List of style properties - values to apply to popper element @argument {Object} data.attributes - List of attribute properties - values to apply to popper element @argument {Object} opti...
applyStyle
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
function applyStyleOnLoad(reference, popper, options, modifierOptions, state) { // compute reference element offsets var referenceOffsets = getReferenceOffsets(state, popper, reference, options.positionFixed); // compute auto placement, store placement inside the data object, // modifiers will be able ...
Set the x-placement attribute before everything else because it could be used to add margins to the popper margins needs to be calculated to get the correct popper offsets. @method @memberof Popper.modifiers @param {HTMLElement} reference - The reference element used to position the popper @param {HTMLElement} popper -...
applyStyleOnLoad
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
function getRoundedOffsets(data, shouldRound) { var _data$offsets = data.offsets, popper = _data$offsets.popper, reference = _data$offsets.reference; var round = Math.round, floor = Math.floor; var noRound = function noRound(v) { return v; }; var referenceWidth = roun...
@function @memberof Popper.Utils @argument {Object} data - The data object generated by `update` method @argument {Boolean} shouldRound - If the offsets should be rounded at all @returns {Object} The popper's position offsets rounded The tale of pixel-perfect positioning. It's still not 100% perfect, but as good as it...
getRoundedOffsets
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
function computeStyle(data, options) { var x = options.x, y = options.y; var popper = data.offsets.popper; // Remove this legacy support in Popper.js v2 var legacyGpuAccelerationOption = find(data.instance.modifiers, function (modifier) { return modifier.name === 'applyStyle'; }).gpu...
@function @memberof Modifiers @argument {Object} data - The data object generated by `update` method @argument {Object} options - Modifiers configuration and options @returns {Object} The data object, properly modified
computeStyle
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
function isModifierRequired(modifiers, requestingName, requestedName) { var requesting = find(modifiers, function (_ref) { var name = _ref.name; return name === requestingName; }); var isRequired = !!requesting && modifiers.some(function (modifier) { return modifier.name === requestedName...
Helper used to know if the given modifier depends from another one.<br /> It checks if the needed modifier is listed and enabled. @method @memberof Popper.Utils @param {Array} modifiers - list of modifiers @param {String} requestingName - name of requesting modifier @param {String} requestedName - name of requested mod...
isModifierRequired
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
function arrow(data, options) { var _data$offsets$arrow; // arrow depends on keepTogether in order to work if (!isModifierRequired(data.instance.modifiers, 'arrow', 'keepTogether')) { return data; } var arrowElement = options.element; // if arrowElement is a string, suppose it's a CSS s...
@function @memberof Modifiers @argument {Object} data - The data object generated by update method @argument {Object} options - Modifiers configuration and options @returns {Object} The data object, properly modified
arrow
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
function getOppositeVariation(variation) { if (variation === 'end') { return 'start'; } else if (variation === 'start') { return 'end'; } return variation; }
Get the opposite placement variation of the given one @method @memberof Popper.Utils @argument {String} placement variation @returns {String} flipped placement variation
getOppositeVariation
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
function clockwise(placement) { var counter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var index = validPlacements.indexOf(placement); var arr = validPlacements.slice(index + 1).concat(validPlacements.slice(0, index)); return counter ? arr.reverse() : arr; }
Given an initial placement, returns all the subsequent placements clockwise (or counter-clockwise). @method @memberof Popper.Utils @argument {String} placement - A valid placement (it accepts variations) @argument {Boolean} counter - Set to true to walk the placements counterclockwise @returns {Array} placements inclu...
clockwise
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
function toValue(str, measurement, popperOffsets, referenceOffsets) { // separate value from unit var split = str.match(/((?:\-|\+)?\d*\.?\d*)(.*)/); var value = +split[1]; var unit = split[2]; // If it's not a number it's an operator, I guess if (!value) { return str; } if (unit...
Converts a string containing value + unit into a px value number @function @memberof {modifiers~offset} @private @argument {String} str - Value + unit string @argument {String} measurement - `height` or `width` @argument {Object} popperOffsets @argument {Object} referenceOffsets @returns {Number|String} Value in pixels...
toValue
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
function parseOffset(offset, popperOffsets, referenceOffsets, basePlacement) { var offsets = [0, 0]; // Use height if placement is left or right and index is 0 otherwise use width // in this way the first offset will use an axis and the second one // will use the other one var useHeight = ['right',...
Parse an `offset` string to extrapolate `x` and `y` numeric offsets. @function @memberof {modifiers~offset} @private @argument {String} offset @argument {Object} popperOffsets @argument {Object} referenceOffsets @argument {String} basePlacement @returns {Array} a two cells array with x and y offsets in numbers
parseOffset
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
function offset(data, _ref) { var offset = _ref.offset; var placement = data.placement, _data$offsets = data.offsets, popper = _data$offsets.popper, reference = _data$offsets.reference; var basePlacement = placement.split('-')[0]; var offsets = void 0; if (isNumeric(+offset...
@function @memberof Modifiers @argument {Object} data - The data object generated by update method @argument {Object} options - Modifiers configuration and options @argument {Number|String} options.offset=0 The offset value as described in the modifier description @returns {Object} The data object, properly modified
offset
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
function Popper(reference, popper) { var _this = this; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; classCallCheck(this, Popper); this.scheduleUpdate = function () { return requestAnimationFrame(_this.update); }; // make update() de...
Creates a new Popper.js instance. @class Popper @param {HTMLElement|referenceObject} reference - The reference element used to position the popper @param {HTMLElement} popper - The HTML element used as the popper @param {Object} options - Your custom options to override the ones defined in [Defaults](#defaults) @return...
Popper
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
transitionComplete = function transitionComplete() { if (_this3._config.focus) { _this3._element.focus(); } _this3._isTransitioning = false; $(_this3._element).trigger(shownEvent); }
`document` has 2 events `Event.FOCUSIN` and `Event.CLICK_DATA_API` Do not move `document` in `htmlElements` array It will remove `Event.CLICK_DATA_API` event that should remain
transitionComplete
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
function allowedAttribute(attr, allowedAttributeList) { var attrName = attr.nodeName.toLowerCase(); if (allowedAttributeList.indexOf(attrName) !== -1) { if (uriAttrs.indexOf(attrName) !== -1) { return Boolean(attr.nodeValue.match(SAFE_URL_PATTERN) || attr.nodeValue.match(DATA_URL_PATTERN)); ...
A pattern that matches safe data URLs. Only matches image, video and audio types. Shoutout to Angular 7 https://github.com/angular/angular/blob/7.2.4/packages/core/src/sanitization/url_sanitizer.ts
allowedAttribute
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
complete = function complete() { if (_this.config.animation) { _this._fixTransition(); } var prevHoverState = _this._hoverState; _this._hoverState = null; $(_this.element).trigger(_this.constructor.Event.SHOWN); if (prevHoverState === HoverState....
Check for Popper dependency Popper - https://popper.js.org
complete
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
function makeFailHTML(msg) { return '\n<table style="background-color: #8CE; width: 100%; height: 100%;"><tr>\n<td align="center">\n<div style="display: table-cell; vertical-align: middle;">\n<div style="">' + msg + '</div>\n</div>\n</td></tr></table>\n'; }
Creates the HTLM for a failure message @param {string} canvasContainerId id of container of th canvas. @return {string} The html.
makeFailHTML
javascript
patriciogonzalezvivo/glslGallery
build/glslGallery.js
https://github.com/patriciogonzalezvivo/glslGallery/blob/master/build/glslGallery.js
MIT
function setupWebGL(canvas, optAttribs, onError) { function showLink(str) { var container = canvas.parentNode; if (container) { container.innerHTML = makeFailHTML(str); } } function handleError(errorCode, msg) { if (typeof onError === 'function') { on...
Creates a webgl context. If creation fails it will change the contents of the container of the <canvas> tag to an error message with the correct links for WebGL, unless `onError` option is defined to a callback, which allows for custom error handling.. @param {Element} canvas. The canvas element to create a context...
setupWebGL
javascript
patriciogonzalezvivo/glslGallery
build/glslGallery.js
https://github.com/patriciogonzalezvivo/glslGallery/blob/master/build/glslGallery.js
MIT
function create3DContext(canvas, optAttribs) { var names = ['webgl', 'experimental-webgl']; var context = null; for (var ii = 0; ii < names.length; ++ii) { try { context = canvas.getContext(names[ii], optAttribs); } catch (e) { if (context) { break; ...
Creates a webgl context. @param {!Canvas} canvas The canvas tag to get context from. If one is not passed in one will be created. @return {!WebGLContext} The created context.
create3DContext
javascript
patriciogonzalezvivo/glslGallery
build/glslGallery.js
https://github.com/patriciogonzalezvivo/glslGallery/blob/master/build/glslGallery.js
MIT
function createProgram(main, shaders, optAttribs, optLocations) { var gl = main.gl; var program = gl.createProgram(); for (var ii = 0; ii < shaders.length; ++ii) { gl.attachShader(program, shaders[ii]); } if (optAttribs) { for (var _ii = 0; _ii < optAttribs.length; ++_ii) { ...
Loads a shader. @param {!WebGLContext} gl The WebGLContext to use. @param {string} shaderSource The shader source. @param {number} shaderType The type of shader. @param {function(string): void) opt_errorCallback callback for errors. @return {!WebGLShader} The created shader.
createProgram
javascript
patriciogonzalezvivo/glslGallery
build/glslGallery.js
https://github.com/patriciogonzalezvivo/glslGallery/blob/master/build/glslGallery.js
MIT
Point = (x, y, r) => { return { x, y, radius: r }; }
Tests for server/lib/util.js This is mostly a regression suite, to make sure behavior is preserved throughout changes to the server infrastructure.
Point
javascript
owenashurst/agar.io-clone
test/util.js
https://github.com/owenashurst/agar.io-clone/blob/master/test/util.js
MIT
function build () { console.log('Installing node_modules...') rimraf.sync(NODE_MODULES_PATH) cp.execSync('npm ci', { stdio: 'inherit' }) console.log('Nuking dist/ and build/...') rimraf.sync(DIST_PATH) rimraf.sync(BUILD_PATH) console.log('Build: Transpiling to ES5...') cp.execSync('npm run build', { N...
Builds app binaries for Mac, Windows, and Linux.
build
javascript
webtorrent/webtorrent-desktop
bin/package.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/bin/package.js
MIT
function packagePortable (filesPath, cb) { console.log('Windows: Creating portable app...') const portablePath = path.join(filesPath, 'Portable Settings') fs.mkdirSync(portablePath, { recursive: true }) const downloadsPath = path.join(portablePath, 'Downloads') fs.mkdirSync(downloadsPath...
Delete extraneous Squirrel files (i.e. *.nupkg delta files for older versions of the app)
packagePortable
javascript
webtorrent/webtorrent-desktop
bin/package.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/bin/package.js
MIT
function init () { const get = require('simple-get') get.concat(ANNOUNCEMENT_URL, onResponse) }
In certain situations, the WebTorrent team may need to show an announcement to all WebTorrent Desktop users. For example: a security notice, or an update notification (if the auto-updater stops working). When there is an announcement, the `ANNOUNCEMENT_URL` endpoint should return an HTTP 200 status code with a JSON ob...
init
javascript
webtorrent/webtorrent-desktop
src/main/announcement.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/announcement.js
MIT
function openSeedFile () { if (!windows.main.win) return log('openSeedFile') const opts = { title: 'Select a file for the torrent.', properties: ['openFile'] } showOpenSeed(opts) }
Show open dialog to create a single-file torrent.
openSeedFile
javascript
webtorrent/webtorrent-desktop
src/main/dialog.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/dialog.js
MIT
function setTitle (title) { if (process.platform === 'darwin') { windows.main.dispatch('setTitle', title) } }
Dialogs on do not show a title on Mac, so the window title is used instead.
setTitle
javascript
webtorrent/webtorrent-desktop
src/main/dialog.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/dialog.js
MIT
function showOpenSeed (opts) { setTitle(opts.title) const selectedPaths = dialog.showOpenDialogSync(windows.main.win, opts) resetTitle() if (!Array.isArray(selectedPaths)) return windows.main.dispatch('showCreateTorrent', selectedPaths) }
Pops up an Open File dialog with the given options. After the user selects files / folders, shows the Create Torrent page.
showOpenSeed
javascript
webtorrent/webtorrent-desktop
src/main/dialog.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/dialog.js
MIT
function init () { if (!app.dock) return const menu = Menu.buildFromTemplate(getMenuTemplate()) app.dock.setMenu(menu) }
Add a right-click menu to the dock icon. (Mac)
init
javascript
webtorrent/webtorrent-desktop
src/main/dock.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/dock.js
MIT
function downloadFinished (path) { if (!app.dock) return log(`downloadFinished: ${path}`) app.dock.downloadFinished(path) }
Bounce the Downloads stack if `path` is inside the Downloads folder. (Mac)
downloadFinished
javascript
webtorrent/webtorrent-desktop
src/main/dock.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/dock.js
MIT
function setBadge (count) { if (process.platform === 'darwin' || (process.platform === 'linux' && app.isUnityRunning())) { log(`setBadge: ${count}`) app.badgeCount = Number(count) } }
Display a counter badge for the app. (Mac, Linux)
setBadge
javascript
webtorrent/webtorrent-desktop
src/main/dock.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/dock.js
MIT
function registerProtocolHandlerWin32 (protocol, name, icon, command) { const protocolKey = new Registry({ hive: Registry.HKCU, // HKEY_CURRENT_USER key: '\\Software\\Classes\\' + protocol }) setProtocol() function setProtocol (err) { if (err) return log.error(err.message) prot...
To add a protocol handler, the following keys must be added to the Windows registry: HKEY_CLASSES_ROOT $PROTOCOL (Default) = "$NAME" URL Protocol = "" DefaultIcon (Default) = "$ICON" shell open command (Default) = "$COMMAND" "%1" Source: https://msdn.microsoft.com/en-us...
registerProtocolHandlerWin32
javascript
webtorrent/webtorrent-desktop
src/main/handlers.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/handlers.js
MIT
function registerFileHandlerWin32 (ext, id, name, icon, command) { setExt() function setExt () { const extKey = new Registry({ hive: Registry.HKCU, // HKEY_CURRENT_USER key: `\\Software\\Classes\\${ext}` }) extKey.set('', Registry.REG_SZ, id, setId) } function setId (...
To add a file handler, the following keys must be added to the Windows registry: HKEY_CLASSES_ROOT $EXTENSION (Default) = "$EXTENSION_ID" $EXTENSION_ID (Default) = "$NAME" DefaultIcon (Default) = "$ICON" shell open command (Default) = "$COMMAND" "%1"
registerFileHandlerWin32
javascript
webtorrent/webtorrent-desktop
src/main/handlers.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/handlers.js
MIT
function log (...args) { if (app.ipcReady) { windows.main.send('log', ...args) } else { app.once('ipcReady', () => windows.main.send('log', ...args)) } }
In the main electron process, we do not use console.log() statements because they do not show up in a convenient location when running the packaged (i.e. production) version of the app. Instead use this module, which sends the logs to the main window where they can be viewed in Developer Tools.
log
javascript
webtorrent/webtorrent-desktop
src/main/log.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/log.js
MIT
function enable () { if (powerSaveBlocker.isStarted(blockId)) { // If a power saver block already exists, do nothing. return } blockId = powerSaveBlocker.start('prevent-display-sleep') log(`powerSaveBlocker.enable: ${blockId}`) }
Block the system from entering low-power (sleep) mode or turning off the display.
enable
javascript
webtorrent/webtorrent-desktop
src/main/power-save-blocker.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/power-save-blocker.js
MIT
function disable () { if (!powerSaveBlocker.isStarted(blockId)) { // If a power saver block does not exist, do nothing. return } powerSaveBlocker.stop(blockId) log(`powerSaveBlocker.disable: ${blockId}`) }
Stop blocking the system from entering low-power mode.
disable
javascript
webtorrent/webtorrent-desktop
src/main/power-save-blocker.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/power-save-blocker.js
MIT
function showItemInFolder (path) { log(`showItemInFolder: ${path}`) shell.showItemInFolder(path) }
Show the given file in a file manager. If possible, select the file.
showItemInFolder
javascript
webtorrent/webtorrent-desktop
src/main/shell.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/shell.js
MIT
function moveItemToTrash (path) { log(`moveItemToTrash: ${path}`) shell.trashItem(path) }
Move the given file to trash and returns a boolean status for the operation.
moveItemToTrash
javascript
webtorrent/webtorrent-desktop
src/main/shell.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/shell.js
MIT
function enable () { buttons = [ { tooltip: 'Previous Track', icon: PREV_ICON, click: () => windows.main.dispatch('previousTrack') }, { tooltip: 'Pause', icon: PAUSE_ICON, click: () => windows.main.dispatch('playPause') }, { tooltip: 'Next Track', ic...
Show the Windows thumbnail toolbar buttons.
enable
javascript
webtorrent/webtorrent-desktop
src/main/thumbar.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/thumbar.js
MIT
function disable () { buttons = [] update() }
Hide the Windows thumbnail toolbar buttons.
disable
javascript
webtorrent/webtorrent-desktop
src/main/thumbar.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/thumbar.js
MIT
function hasTray () { return !!tray }
Returns true if there a tray icon is active.
hasTray
javascript
webtorrent/webtorrent-desktop
src/main/tray.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/tray.js
MIT
function checkLinuxTraySupport (cb) { const cp = require('child_process') // Check that libappindicator libraries are installed in system. cp.exec('ldconfig -p | grep libappindicator', (err, stdout) => { if (err) return cb(err) cb(null) }) }
Check for libappindicator support before creating tray icon.
checkLinuxTraySupport
javascript
webtorrent/webtorrent-desktop
src/main/tray.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/tray.js
MIT
function init () { if (process.platform !== 'win32') return app.setUserTasks(getUserTasks()) }
Add a user task menu to the app icon on right-click. (Windows)
init
javascript
webtorrent/webtorrent-desktop
src/main/user-tasks.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/user-tasks.js
MIT
function setAspectRatio (aspectRatio) { if (!main.win) return main.win.setAspectRatio(aspectRatio) }
Enforce window aspect ratio. Remove with 0. (Mac)
setAspectRatio
javascript
webtorrent/webtorrent-desktop
src/main/windows/main.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/windows/main.js
MIT
function setBounds (bounds, maximize) { // Do nothing in fullscreen if (!main.win || main.win.isFullScreen()) { log('setBounds: not setting bounds because already in full screen mode') return } // Maximize or minimize, if the second argument is present if (maximize === true && !main.win.isMaximized()...
Change the size of the window. TODO: Clean this up? Seems overly complicated.
setBounds
javascript
webtorrent/webtorrent-desktop
src/main/windows/main.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/windows/main.js
MIT
function setProgress (progress) { if (!main.win) return main.win.setProgressBar(progress) }
Set progress bar to [0, 1]. Indeterminate when > 1. Remove with < 0.
setProgress
javascript
webtorrent/webtorrent-desktop
src/main/windows/main.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/windows/main.js
MIT
function onState (err, _state) { if (err) return onError(err) // Make available for easier debugging state = window.state = _state window.dispatch = dispatch telemetry.init(state) sound.init(state) // Log uncaught JS errors window.addEventListener( 'error', (e) => telemetry.logUncaughtError('wind...
Perf optimization: Hook into require() to modify how certain modules load: - `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not actually used because auto-prefixing is disabled with `darkBaseTheme.userAgent = false`. Return a fake object.
onState
javascript
webtorrent/webtorrent-desktop
src/renderer/main.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js
MIT
function init () { listenToClientEvents() ipcRenderer.on('wt-set-global-trackers', (e, globalTrackers) => setGlobalTrackers(globalTrackers)) ipcRenderer.on('wt-start-torrenting', (e, torrentKey, torrentID, path, fileModtimes, selections) => startTorrenting(torrentKey, torrentID, path, fileModtimes, selec...
Generate an ephemeral peer ID each time.
init
javascript
webtorrent/webtorrent-desktop
src/renderer/webtorrent.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js
MIT
function calculateDataLengthByExtension (torrent, extensions) { const files = filterOnExtension(torrent, extensions) if (files.length === 0) return 0 return files .map(file => file.length) .reduce((a, b) => a + b) }
Calculate the total data size of file matching one of the provided extensions @param torrent @param extensions List of extension to match @returns {number} total size, of matches found (>= 0)
calculateDataLengthByExtension
javascript
webtorrent/webtorrent-desktop
src/renderer/lib/torrent-poster.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/lib/torrent-poster.js
MIT
function getLargestFileByExtension (torrent, extensions) { const files = filterOnExtension(torrent, extensions) if (files.length === 0) return undefined return files.reduce((a, b) => a.length > b.length ? a : b) }
Get the largest file of a given torrent, filtered by provided extension @param torrent Torrent to search in @param extensions Extension whitelist filter @returns Torrent file object
getLargestFileByExtension
javascript
webtorrent/webtorrent-desktop
src/renderer/lib/torrent-poster.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/lib/torrent-poster.js
MIT
function filterOnExtension (torrent, extensions) { return torrent.files.filter(file => { const extname = path.extname(file.name).toLowerCase() return extensions.indexOf(extname) !== -1 }) }
Filter file on a list extension, can be used to find al image files @param torrent Torrent to filter files from @param extensions File extensions to filter on @returns {Array} Array of torrent file objects matching one of the given extensions
filterOnExtension
javascript
webtorrent/webtorrent-desktop
src/renderer/lib/torrent-poster.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/lib/torrent-poster.js
MIT
function scoreAudioCoverFile (imgFile) { const fileName = path.basename(imgFile.name, path.extname(imgFile.name)).toLowerCase() const relevanceScore = { cover: 80, folder: 80, album: 80, front: 80, back: 20, spectrogram: -80 } for (const keyword in relevanceScore) { if (fileName ===...
Returns a score how likely the file is suitable as a poster @param imgFile File object of an image @returns {number} Score, higher score is a better match
scoreAudioCoverFile
javascript
webtorrent/webtorrent-desktop
src/renderer/lib/torrent-poster.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/lib/torrent-poster.js
MIT
function renderTrack (common, key) { // Audio metadata: track-number if (common[key] && common[key].no) { let str = `${common[key].no}` if (common[key].of) { str += ` of ${common[key].of}` } const style = { textTransform: 'capitalize' } return ( <div className={`audio-${key}`}> ...
Render track or disk number string @param common metadata.common part @param key should be either 'track' or 'disk' @return track or disk number metadata as JSX block
renderTrack
javascript
webtorrent/webtorrent-desktop
src/renderer/pages/player-page.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js
MIT
constructor(name, description) { this.description = description || ''; this.variadic = false; this.parseArg = undefined; this.defaultValue = undefined; this.defaultValueDescription = undefined; this.argChoices = undefined; switch (name[0]) { case '<': // e.g. <required> this.r...
Initialize a new command argument with the given name and description. The default is that the argument is required, and you can explicitly indicate this with <> around the name. Put [] around the name for an optional argument. @param {string} name @param {string} [description]
constructor
javascript
tj/commander.js
lib/argument.js
https://github.com/tj/commander.js/blob/master/lib/argument.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 {Argument}
default
javascript
tj/commander.js
lib/argument.js
https://github.com/tj/commander.js/blob/master/lib/argument.js
MIT
argParser(fn) { this.parseArg = fn; return this; }
Set the custom handler for processing CLI command arguments into argument values. @param {Function} [fn] @return {Argument}
argParser
javascript
tj/commander.js
lib/argument.js
https://github.com/tj/commander.js/blob/master/lib/argument.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 argument value to be one of choices. @param {string[]} values @return {Argument}
choices
javascript
tj/commander.js
lib/argument.js
https://github.com/tj/commander.js/blob/master/lib/argument.js
MIT
function humanReadableArgName(arg) { const nameOutput = arg.name() + (arg.variadic === true ? '...' : ''); return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']'; }
Takes an argument and returns its human readable equivalent for help usage. @param {Argument} arg @return {string} @private
humanReadableArgName
javascript
tj/commander.js
lib/argument.js
https://github.com/tj/commander.js/blob/master/lib/argument.js
MIT
constructor(name) { super(); /** @type {Command[]} */ this.commands = []; /** @type {Option[]} */ this.options = []; this.parent = null; this._allowUnknownOption = false; this._allowExcessArguments = false; /** @type {Argument[]} */ this.registeredArguments = []; this._args =...
Initialize a new `Command`. @param {string} [name]
constructor
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
copyInheritedSettings(sourceCommand) { this._outputConfiguration = sourceCommand._outputConfiguration; this._helpOption = sourceCommand._helpOption; this._helpCommand = sourceCommand._helpCommand; this._helpConfiguration = sourceCommand._helpConfiguration; this._exitCallback = sourceCommand._exitCal...
Copy settings that are useful to have in common across root command and subcommands. (Used internally when adding a command using `.command()` so subcommands inherit parent settings.) @param {Command} sourceCommand @return {Command} `this` command for chaining
copyInheritedSettings
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
command(nameAndArgs, actionOptsOrExecDesc, execOpts) { let desc = actionOptsOrExecDesc; let opts = execOpts; if (typeof desc === 'object' && desc !== null) { opts = desc; desc = null; } opts = opts || {}; const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/); const cmd = thi...
Define a command. There are two styles of command: pay attention to where to put the description. @example // Command implemented using action handler (description is supplied separately to `.command`) program .command('clone <source> [destination]') .description('clone a repository into a newly created directory...
command
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
createCommand(name) { return new Command(name); }
Factory routine to create a new unattached command. See .command() for creating an attached subcommand, which uses this routine to create the command. You can override createCommand to customise subcommands. @param {string} [name] @return {Command} new command
createCommand
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
createHelp() { return Object.assign(new Help(), this.configureHelp()); }
You can customise the help with a subclass of Help by overriding createHelp, or by overriding Help properties using configureHelp(). @return {Help}
createHelp
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
configureHelp(configuration) { if (configuration === undefined) return this._helpConfiguration; this._helpConfiguration = configuration; return this; }
You can customise the help by overriding Help properties using configureHelp(), or with a subclass of Help by overriding createHelp(). @param {object} [configuration] - configuration options @return {(Command | object)} `this` command for chaining, or stored configuration
configureHelp
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
configureOutput(configuration) { if (configuration === undefined) return this._outputConfiguration; this._outputConfiguration = Object.assign( {}, this._outputConfiguration, configuration, ); return this; }
The default output goes to stdout and stderr. You can customise this for special applications. You can also customise the display of errors by overriding outputError. The configuration properties are all functions: // change how output being written, defaults to stdout and stderr writeOut(str) writeErr(st...
configureOutput
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
showHelpAfterError(displayHelp = true) { if (typeof displayHelp !== 'string') displayHelp = !!displayHelp; this._showHelpAfterError = displayHelp; return this; }
Display the help or a custom message after an error occurs. @param {(boolean|string)} [displayHelp] @return {Command} `this` command for chaining
showHelpAfterError
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
showSuggestionAfterError(displaySuggestion = true) { this._showSuggestionAfterError = !!displaySuggestion; return this; }
Display suggestion of similar commands for unknown commands, or options for unknown options. @param {boolean} [displaySuggestion] @return {Command} `this` command for chaining
showSuggestionAfterError
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
addCommand(cmd, opts) { if (!cmd._name) { throw new Error(`Command passed to .addCommand() must have a name - specify the name in Command constructor or using .name()`); } opts = opts || {}; if (opts.isDefault) this._defaultCommandName = cmd._name; if (opts.noHelp || opts.hidden) cmd._hidden ...
Add a prepared subcommand. See .command() for creating an attached subcommand which inherits settings from its parent. @param {Command} cmd - new subcommand @param {object} [opts] - configuration options @return {Command} `this` command for chaining
addCommand
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
createArgument(name, description) { return new Argument(name, description); }
Factory routine to create a new unattached argument. See .argument() for creating an attached argument, which uses this routine to create the argument. You can override createArgument to return a custom argument. @param {string} name @param {string} [description] @return {Argument} new argument
createArgument
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
argument(name, description, parseArg, defaultValue) { const argument = this.createArgument(name, description); if (typeof parseArg === 'function') { argument.default(defaultValue).argParser(parseArg); } else { argument.default(parseArg); } this.addArgument(argument); return this; }
Define argument syntax for command. The default is that the argument is required, and you can explicitly indicate this with <> around the name. Put [] around the name for an optional argument. @example program.argument('<input-file>'); program.argument('[output-file]'); @param {string} name @param {string} [descript...
argument
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
arguments(names) { names .trim() .split(/ +/) .forEach((detail) => { this.argument(detail); }); return this; }
Define argument syntax for command, adding multiple at once (without descriptions). See also .argument(). @example program.arguments('<cmd> [env]'); @param {string} names @return {Command} `this` command for chaining
arguments
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
addArgument(argument) { const previousArgument = this.registeredArguments.slice(-1)[0]; if (previousArgument && previousArgument.variadic) { throw new Error( `only the last argument can be variadic '${previousArgument.name()}'`, ); } if ( argument.required && argument.def...
Define argument syntax for command, adding a prepared argument. @param {Argument} argument @return {Command} `this` command for chaining
addArgument
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
helpCommand(enableOrNameAndArgs, description) { if (typeof enableOrNameAndArgs === 'boolean') { this._addImplicitHelpCommand = enableOrNameAndArgs; if (enableOrNameAndArgs && this._defaultCommandGroup) { // make the command to store the group this._initCommandGroup(this._getHelpCommand()...
Customise or override default help command. By default a help command is automatically added if your command has subcommands. @example program.helpCommand('help [cmd]'); program.helpCommand('help [cmd]', 'show help'); program.helpCommand(false); // suppress default help command program.helpCommand(true); /...
helpCommand
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
addHelpCommand(helpCommand, deprecatedDescription) { // If not passed an object, call through to helpCommand for backwards compatibility, // as addHelpCommand was originally used like helpCommand is now. if (typeof helpCommand !== 'object') { this.helpCommand(helpCommand, deprecatedDescription); ...
Add prepared custom help command. @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()` @param {string} [deprecatedDescription] - deprecated custom description used with custom name only @return {Command} `this` command for chaining
addHelpCommand
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
_getHelpCommand() { const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand('help')); if (hasImplicitHelpCommand) { if (this._helpCommand === undefined) { this.helpCommand(undefined, undefined);...
Lazy create help command. @return {(Command|null)} @package
_getHelpCommand
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
hook(event, listener) { const allowedValues = ['preSubcommand', 'preAction', 'postAction']; if (!allowedValues.includes(event)) { throw new Error(`Unexpected value for event passed to hook : '${event}'. Expecting one of '${allowedValues.join("', '")}'`); } if (this._lifeCycleHooks[event]) { ...
Add hook for life cycle event. @param {string} event @param {Function} listener @return {Command} `this` command for chaining
hook
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
exitOverride(fn) { if (fn) { this._exitCallback = fn; } else { this._exitCallback = (err) => { if (err.code !== 'commander.executeSubCommandAsync') { throw err; } else { // Async callback from spawn events, not useful to throw. } }; } return ...
Register callback to use as replacement for calling process.exit. @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing @return {Command} `this` command for chaining
exitOverride
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
_exit(exitCode, code, message) { if (this._exitCallback) { this._exitCallback(new CommanderError(exitCode, code, message)); // Expecting this line is not reached. } process.exit(exitCode); }
Call process.exit, and _exitCallback if defined. @param {number} exitCode exit code for using with process.exit @param {string} code an id string representing the error @param {string} message human-readable description of the error @return never @private
_exit
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
action(fn) { const listener = (args) => { // The .action callback takes an extra parameter which is the command or options. const expectedArgsCount = this.registeredArguments.length; const actionArgs = args.slice(0, expectedArgsCount); if (this._storeOptionsAsProperties) { actionArgs...
Register callback `fn` for the command. @example program .command('serve') .description('start service') .action(function() { // do work here }); @param {Function} fn @return {Command} `this` command for chaining
action
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
createOption(flags, description) { return new Option(flags, description); }
Factory routine to create a new unattached option. See .option() for creating an attached option, which uses this routine to create the option. You can override createOption to return a custom option. @param {string} flags @param {string} [description] @return {Option} new option
createOption
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
_callParseArg(target, value, previous, invalidArgumentMessage) { try { return target.parseArg(value, previous); } catch (err) { if (err.code === 'commander.invalidArgument') { const message = `${invalidArgumentMessage} ${err.message}`; this.error(message, { exitCode: err.exitCode, co...
Wrap parseArgs to catch 'commander.invalidArgument'. @param {(Option | Argument)} target @param {string} value @param {*} previous @param {string} invalidArgumentMessage @private
_callParseArg
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
_registerOption(option) { const matchingOption = (option.short && this._findOption(option.short)) || (option.long && this._findOption(option.long)); if (matchingOption) { const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;...
Check for option flag conflicts. Register option if no conflicts found, or throw on conflict. @param {Option} option @private
_registerOption
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
_registerCommand(command) { const knownBy = (cmd) => { return [cmd.name()].concat(cmd.aliases()); }; const alreadyUsed = knownBy(command).find((name) => this._findCommand(name), ); if (alreadyUsed) { const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|'); cons...
Check for command name and alias conflicts with existing commands. Register command if no conflicts found, or throw on conflict. @param {Command} command @private
_registerCommand
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
addOption(option) { this._registerOption(option); const oname = option.name(); const name = option.attributeName(); // store default value if (option.negate) { // --no-foo is special and defaults foo to true, unless a --foo option is already defined const positiveLongFlag = option.long...
Add an option. @param {Option} option @return {Command} `this` command for chaining
addOption
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
_optionEx(config, flags, description, fn, defaultValue) { if (typeof flags === 'object' && flags instanceof Option) { throw new Error( 'To add an Option object use addOption() instead of option() or requiredOption()', ); } const option = this.createOption(flags, description); option....
Internal implementation shared by .option() and .requiredOption() @return {Command} `this` command for chaining @private
_optionEx
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
option(flags, description, parseArg, defaultValue) { return this._optionEx({}, flags, description, parseArg, defaultValue); }
Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both. The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required option-argument is indicated by `<>` and an optional option-argument by `[]`. See the README for more de...
option
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
requiredOption(flags, description, parseArg, defaultValue) { return this._optionEx( { mandatory: true }, flags, description, parseArg, defaultValue, ); }
Add a required option which must have a value after parsing. This usually means the option must be specified on the command line. (Otherwise the same as .option().) The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. @param {string} flags @param {string} [description] @param ...
requiredOption
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
enablePositionalOptions(positional = true) { this._enablePositionalOptions = !!positional; return this; }
Enable positional options. Positional means global options are specified before subcommands which lets subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions. The default behaviour is non-positional and global options may appear anywhere on the command line. @param {boolean...
enablePositionalOptions
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
passThroughOptions(passThrough = true) { this._passThroughOptions = !!passThrough; this._checkForBrokenPassThrough(); return this; }
Pass through options that come after command-arguments rather than treat them as command-options, so actual command-options come before command-arguments. Turning this on for a subcommand requires positional options to have been enabled on the program (parent commands). The default behaviour is non-positional and optio...
passThroughOptions
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
storeOptionsAsProperties(storeAsProperties = true) { if (this.options.length) { throw new Error('call .storeOptionsAsProperties() before adding options'); } if (Object.keys(this._optionValues).length) { throw new Error( 'call .storeOptionsAsProperties() before setting option values', ...
Whether to store option values as properties on command object, or store separately (specify false). In both cases the option values can be accessed using .opts(). @param {boolean} [storeAsProperties=true] @return {Command} `this` command for chaining
storeOptionsAsProperties
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
getOptionValue(key) { if (this._storeOptionsAsProperties) { return this[key]; } return this._optionValues[key]; }
Retrieve option value. @param {string} key @return {object} value
getOptionValue
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
setOptionValue(key, value) { return this.setOptionValueWithSource(key, value, undefined); }
Store option value. @param {string} key @param {object} value @return {Command} `this` command for chaining
setOptionValue
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
setOptionValueWithSource(key, value, source) { if (this._storeOptionsAsProperties) { this[key] = value; } else { this._optionValues[key] = value; } this._optionValueSources[key] = source; return this; }
Store option value and where the value came from. @param {string} key @param {object} value @param {string} source - expected values are default/config/env/cli/implied @return {Command} `this` command for chaining
setOptionValueWithSource
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
getOptionValueSource(key) { return this._optionValueSources[key]; }
Get source of option value. Expected values are default | config | env | cli | implied @param {string} key @return {string}
getOptionValueSource
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
getOptionValueSourceWithGlobals(key) { // global overwrites local, like optsWithGlobals let source; this._getCommandAndAncestors().forEach((cmd) => { if (cmd.getOptionValueSource(key) !== undefined) { source = cmd.getOptionValueSource(key); } }); return source; }
Get source of option value. See also .optsWithGlobals(). Expected values are default | config | env | cli | implied @param {string} key @return {string}
getOptionValueSourceWithGlobals
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
_prepareUserArgs(argv, parseOptions) { if (argv !== undefined && !Array.isArray(argv)) { throw new Error('first parameter to parse must be array or undefined'); } parseOptions = parseOptions || {}; // auto-detect argument conventions if nothing supplied if (argv === undefined && parseOptions....
Get user arguments from implied or explicit arguments. Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches. @private
_prepareUserArgs
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
parse(argv, parseOptions) { this._prepareForParse(); const userArgs = this._prepareUserArgs(argv, parseOptions); this._parseCommand([], userArgs); return this; }
Parse `argv`, setting options and invoking commands when defined. Use parseAsync instead of parse if any of your action handlers are async. Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode! Or call with an array of strings to parse, and optional...
parse
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
async parseAsync(argv, parseOptions) { this._prepareForParse(); const userArgs = this._prepareUserArgs(argv, parseOptions); await this._parseCommand([], userArgs); return this; }
Parse `argv`, setting options and invoking commands when defined. Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode! Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `fr...
parseAsync
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT