id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
|
---|---|---|---|---|---|---|---|---|---|---|---|
1,000 | wix/Detox | generation/core/generator.js | hasProblematicOverloading | function hasProblematicOverloading(instances) {
// Check if there are same lengthed argument sets
const knownLengths = [];
return instances.map(({ args }) => args.length).reduce((carry, item) => {
if (carry || knownLengths.some((l) => l === item)) {
return true;
}
knownLengths.push(item);
return false;
}, false);
} | javascript | function hasProblematicOverloading(instances) {
// Check if there are same lengthed argument sets
const knownLengths = [];
return instances.map(({ args }) => args.length).reduce((carry, item) => {
if (carry || knownLengths.some((l) => l === item)) {
return true;
}
knownLengths.push(item);
return false;
}, false);
} | [
"function",
"hasProblematicOverloading",
"(",
"instances",
")",
"{",
"// Check if there are same lengthed argument sets",
"const",
"knownLengths",
"=",
"[",
"]",
";",
"return",
"instances",
".",
"map",
"(",
"(",
"{",
"args",
"}",
")",
"=>",
"args",
".",
"length",
")",
".",
"reduce",
"(",
"(",
"carry",
",",
"item",
")",
"=>",
"{",
"if",
"(",
"carry",
"||",
"knownLengths",
".",
"some",
"(",
"(",
"l",
")",
"=>",
"l",
"===",
"item",
")",
")",
"{",
"return",
"true",
";",
"}",
"knownLengths",
".",
"push",
"(",
"item",
")",
";",
"return",
"false",
";",
"}",
",",
"false",
")",
";",
"}"
] | We don't handle same lengthed argument sets right now. In the future we could write the type checks in a way that would allow us to do an either or switch in this case | [
"We",
"don",
"t",
"handle",
"same",
"lengthed",
"argument",
"sets",
"right",
"now",
".",
"In",
"the",
"future",
"we",
"could",
"write",
"the",
"type",
"checks",
"in",
"a",
"way",
"that",
"would",
"allow",
"us",
"to",
"do",
"an",
"either",
"or",
"switch",
"in",
"this",
"case"
] | 0ed5e8c7ba279a3a409130b4d4bad3f9a9c2f1f9 | https://github.com/wix/Detox/blob/0ed5e8c7ba279a3a409130b4d4bad3f9a9c2f1f9/generation/core/generator.js#L159-L170 |
1,001 | necolas/react-native-web | packages/react-native-web/src/vendor/react-native/isEmpty/index.js | isEmpty | function isEmpty(obj) {
if (Array.isArray(obj)) {
return obj.length === 0;
} else if (typeof obj === 'object') {
for (var i in obj) {
return false;
}
return true;
} else {
return !obj;
}
} | javascript | function isEmpty(obj) {
if (Array.isArray(obj)) {
return obj.length === 0;
} else if (typeof obj === 'object') {
for (var i in obj) {
return false;
}
return true;
} else {
return !obj;
}
} | [
"function",
"isEmpty",
"(",
"obj",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"obj",
")",
")",
"{",
"return",
"obj",
".",
"length",
"===",
"0",
";",
"}",
"else",
"if",
"(",
"typeof",
"obj",
"===",
"'object'",
")",
"{",
"for",
"(",
"var",
"i",
"in",
"obj",
")",
"{",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"!",
"obj",
";",
"}",
"}"
] | Mimics empty from PHP. | [
"Mimics",
"empty",
"from",
"PHP",
"."
] | 801937748b2f3c96284bee1881164ac0c62a9c6d | https://github.com/necolas/react-native-web/blob/801937748b2f3c96284bee1881164ac0c62a9c6d/packages/react-native-web/src/vendor/react-native/isEmpty/index.js#L14-L25 |
1,002 | jiahaog/nativefier | src/build/buildMain.js | getAppPath | function getAppPath(appPathArray) {
if (appPathArray.length === 0) {
// directory already exists, --overwrite is not set
// exit here
return null;
}
if (appPathArray.length > 1) {
log.warn(
'Warning: This should not be happening, packaged app path contains more than one element:',
appPathArray,
);
}
return appPathArray[0];
} | javascript | function getAppPath(appPathArray) {
if (appPathArray.length === 0) {
// directory already exists, --overwrite is not set
// exit here
return null;
}
if (appPathArray.length > 1) {
log.warn(
'Warning: This should not be happening, packaged app path contains more than one element:',
appPathArray,
);
}
return appPathArray[0];
} | [
"function",
"getAppPath",
"(",
"appPathArray",
")",
"{",
"if",
"(",
"appPathArray",
".",
"length",
"===",
"0",
")",
"{",
"// directory already exists, --overwrite is not set",
"// exit here",
"return",
"null",
";",
"}",
"if",
"(",
"appPathArray",
".",
"length",
">",
"1",
")",
"{",
"log",
".",
"warn",
"(",
"'Warning: This should not be happening, packaged app path contains more than one element:'",
",",
"appPathArray",
",",
")",
";",
"}",
"return",
"appPathArray",
"[",
"0",
"]",
";",
"}"
] | Checks the app path array to determine if the packaging was completed successfully
@param appPathArray Result from electron-packager
@returns {*} | [
"Checks",
"the",
"app",
"path",
"array",
"to",
"determine",
"if",
"the",
"packaging",
"was",
"completed",
"successfully"
] | b959956a38ce51a9dd95d42308f0a6c66489b624 | https://github.com/jiahaog/nativefier/blob/b959956a38ce51a9dd95d42308f0a6c66489b624/src/build/buildMain.js#L23-L38 |
1,003 | jiahaog/nativefier | src/build/buildMain.js | maybeNoIconOption | function maybeNoIconOption(options) {
const packageOptions = JSON.parse(JSON.stringify(options));
if (options.platform === 'win32' && !isWindows()) {
if (!hasBinary.sync('wine')) {
log.warn(
'Wine is required to set the icon for a Windows app when packaging on non-windows platforms',
);
packageOptions.icon = null;
}
}
return packageOptions;
} | javascript | function maybeNoIconOption(options) {
const packageOptions = JSON.parse(JSON.stringify(options));
if (options.platform === 'win32' && !isWindows()) {
if (!hasBinary.sync('wine')) {
log.warn(
'Wine is required to set the icon for a Windows app when packaging on non-windows platforms',
);
packageOptions.icon = null;
}
}
return packageOptions;
} | [
"function",
"maybeNoIconOption",
"(",
"options",
")",
"{",
"const",
"packageOptions",
"=",
"JSON",
".",
"parse",
"(",
"JSON",
".",
"stringify",
"(",
"options",
")",
")",
";",
"if",
"(",
"options",
".",
"platform",
"===",
"'win32'",
"&&",
"!",
"isWindows",
"(",
")",
")",
"{",
"if",
"(",
"!",
"hasBinary",
".",
"sync",
"(",
"'wine'",
")",
")",
"{",
"log",
".",
"warn",
"(",
"'Wine is required to set the icon for a Windows app when packaging on non-windows platforms'",
",",
")",
";",
"packageOptions",
".",
"icon",
"=",
"null",
";",
"}",
"}",
"return",
"packageOptions",
";",
"}"
] | Removes the `icon` parameter from options if building for Windows while not on Windows
and Wine is not installed
@param options | [
"Removes",
"the",
"icon",
"parameter",
"from",
"options",
"if",
"building",
"for",
"Windows",
"while",
"not",
"on",
"Windows",
"and",
"Wine",
"is",
"not",
"installed"
] | b959956a38ce51a9dd95d42308f0a6c66489b624 | https://github.com/jiahaog/nativefier/blob/b959956a38ce51a9dd95d42308f0a6c66489b624/src/build/buildMain.js#L45-L56 |
1,004 | jiahaog/nativefier | src/build/buildMain.js | removeInvalidOptions | function removeInvalidOptions(options, param) {
const packageOptions = JSON.parse(JSON.stringify(options));
if (options.platform === 'win32' && !isWindows()) {
if (!hasBinary.sync('wine')) {
log.warn(
`Wine is required to use "${param}" option for a Windows app when packaging on non-windows platforms`,
);
packageOptions[param] = null;
}
}
return packageOptions;
} | javascript | function removeInvalidOptions(options, param) {
const packageOptions = JSON.parse(JSON.stringify(options));
if (options.platform === 'win32' && !isWindows()) {
if (!hasBinary.sync('wine')) {
log.warn(
`Wine is required to use "${param}" option for a Windows app when packaging on non-windows platforms`,
);
packageOptions[param] = null;
}
}
return packageOptions;
} | [
"function",
"removeInvalidOptions",
"(",
"options",
",",
"param",
")",
"{",
"const",
"packageOptions",
"=",
"JSON",
".",
"parse",
"(",
"JSON",
".",
"stringify",
"(",
"options",
")",
")",
";",
"if",
"(",
"options",
".",
"platform",
"===",
"'win32'",
"&&",
"!",
"isWindows",
"(",
")",
")",
"{",
"if",
"(",
"!",
"hasBinary",
".",
"sync",
"(",
"'wine'",
")",
")",
"{",
"log",
".",
"warn",
"(",
"`",
"${",
"param",
"}",
"`",
",",
")",
";",
"packageOptions",
"[",
"param",
"]",
"=",
"null",
";",
"}",
"}",
"return",
"packageOptions",
";",
"}"
] | Removes invalid parameters from options if building for Windows while not on Windows
and Wine is not installed
@param options | [
"Removes",
"invalid",
"parameters",
"from",
"options",
"if",
"building",
"for",
"Windows",
"while",
"not",
"on",
"Windows",
"and",
"Wine",
"is",
"not",
"installed"
] | b959956a38ce51a9dd95d42308f0a6c66489b624 | https://github.com/jiahaog/nativefier/blob/b959956a38ce51a9dd95d42308f0a6c66489b624/src/build/buildMain.js#L90-L101 |
1,005 | jiahaog/nativefier | app/src/helpers/inferFlash.js | findSync | function findSync(pattern, basePath, findDir) {
const matches = [];
(function findSyncRecurse(base) {
let children;
try {
children = fs.readdirSync(base);
} catch (exception) {
if (exception.code === 'ENOENT') {
return;
}
throw exception;
}
children.forEach((child) => {
const childPath = path.join(base, child);
const childIsDirectory = fs.lstatSync(childPath).isDirectory();
const patternMatches = pattern.test(childPath);
if (!patternMatches) {
if (!childIsDirectory) {
return;
}
findSyncRecurse(childPath);
return;
}
if (!findDir) {
matches.push(childPath);
return;
}
if (childIsDirectory) {
matches.push(childPath);
}
});
})(basePath);
return matches;
} | javascript | function findSync(pattern, basePath, findDir) {
const matches = [];
(function findSyncRecurse(base) {
let children;
try {
children = fs.readdirSync(base);
} catch (exception) {
if (exception.code === 'ENOENT') {
return;
}
throw exception;
}
children.forEach((child) => {
const childPath = path.join(base, child);
const childIsDirectory = fs.lstatSync(childPath).isDirectory();
const patternMatches = pattern.test(childPath);
if (!patternMatches) {
if (!childIsDirectory) {
return;
}
findSyncRecurse(childPath);
return;
}
if (!findDir) {
matches.push(childPath);
return;
}
if (childIsDirectory) {
matches.push(childPath);
}
});
})(basePath);
return matches;
} | [
"function",
"findSync",
"(",
"pattern",
",",
"basePath",
",",
"findDir",
")",
"{",
"const",
"matches",
"=",
"[",
"]",
";",
"(",
"function",
"findSyncRecurse",
"(",
"base",
")",
"{",
"let",
"children",
";",
"try",
"{",
"children",
"=",
"fs",
".",
"readdirSync",
"(",
"base",
")",
";",
"}",
"catch",
"(",
"exception",
")",
"{",
"if",
"(",
"exception",
".",
"code",
"===",
"'ENOENT'",
")",
"{",
"return",
";",
"}",
"throw",
"exception",
";",
"}",
"children",
".",
"forEach",
"(",
"(",
"child",
")",
"=>",
"{",
"const",
"childPath",
"=",
"path",
".",
"join",
"(",
"base",
",",
"child",
")",
";",
"const",
"childIsDirectory",
"=",
"fs",
".",
"lstatSync",
"(",
"childPath",
")",
".",
"isDirectory",
"(",
")",
";",
"const",
"patternMatches",
"=",
"pattern",
".",
"test",
"(",
"childPath",
")",
";",
"if",
"(",
"!",
"patternMatches",
")",
"{",
"if",
"(",
"!",
"childIsDirectory",
")",
"{",
"return",
";",
"}",
"findSyncRecurse",
"(",
"childPath",
")",
";",
"return",
";",
"}",
"if",
"(",
"!",
"findDir",
")",
"{",
"matches",
".",
"push",
"(",
"childPath",
")",
";",
"return",
";",
"}",
"if",
"(",
"childIsDirectory",
")",
"{",
"matches",
".",
"push",
"(",
"childPath",
")",
";",
"}",
"}",
")",
";",
"}",
")",
"(",
"basePath",
")",
";",
"return",
"matches",
";",
"}"
] | Synchronously find a file or directory
@param {RegExp} pattern regex
@param {string} base path
@param {boolean} [findDir] if true, search results will be limited to only directories
@returns {Array} | [
"Synchronously",
"find",
"a",
"file",
"or",
"directory"
] | b959956a38ce51a9dd95d42308f0a6c66489b624 | https://github.com/jiahaog/nativefier/blob/b959956a38ce51a9dd95d42308f0a6c66489b624/app/src/helpers/inferFlash.js#L14-L52 |
1,006 | jiahaog/nativefier | src/options/fields/index.js | wrap | function wrap(fieldName, promise, args) {
return promise(args).then((result) => ({
[fieldName]: result,
}));
} | javascript | function wrap(fieldName, promise, args) {
return promise(args).then((result) => ({
[fieldName]: result,
}));
} | [
"function",
"wrap",
"(",
"fieldName",
",",
"promise",
",",
"args",
")",
"{",
"return",
"promise",
"(",
"args",
")",
".",
"then",
"(",
"(",
"result",
")",
"=>",
"(",
"{",
"[",
"fieldName",
"]",
":",
"result",
",",
"}",
")",
")",
";",
"}"
] | Modifies the result of each promise from a scalar value to a object containing its fieldname | [
"Modifies",
"the",
"result",
"of",
"each",
"promise",
"from",
"a",
"scalar",
"value",
"to",
"a",
"object",
"containing",
"its",
"fieldname"
] | b959956a38ce51a9dd95d42308f0a6c66489b624 | https://github.com/jiahaog/nativefier/blob/b959956a38ce51a9dd95d42308f0a6c66489b624/src/options/fields/index.js#L22-L26 |
1,007 | jiahaog/nativefier | src/infer/inferIcon.js | getMatchingIcons | function getMatchingIcons(iconsWithScores, maxScore) {
return iconsWithScores
.filter((item) => item.score === maxScore)
.map((item) => Object.assign({}, item, { ext: path.extname(item.url) }));
} | javascript | function getMatchingIcons(iconsWithScores, maxScore) {
return iconsWithScores
.filter((item) => item.score === maxScore)
.map((item) => Object.assign({}, item, { ext: path.extname(item.url) }));
} | [
"function",
"getMatchingIcons",
"(",
"iconsWithScores",
",",
"maxScore",
")",
"{",
"return",
"iconsWithScores",
".",
"filter",
"(",
"(",
"item",
")",
"=>",
"item",
".",
"score",
"===",
"maxScore",
")",
".",
"map",
"(",
"(",
"item",
")",
"=>",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"item",
",",
"{",
"ext",
":",
"path",
".",
"extname",
"(",
"item",
".",
"url",
")",
"}",
")",
")",
";",
"}"
] | also maps ext to icon object | [
"also",
"maps",
"ext",
"to",
"icon",
"object"
] | b959956a38ce51a9dd95d42308f0a6c66489b624 | https://github.com/jiahaog/nativefier/blob/b959956a38ce51a9dd95d42308f0a6c66489b624/src/infer/inferIcon.js#L26-L30 |
1,008 | jiahaog/nativefier | src/build/buildApp.js | selectAppArgs | function selectAppArgs(options) {
return {
name: options.name,
targetUrl: options.targetUrl,
counter: options.counter,
bounce: options.bounce,
width: options.width,
height: options.height,
minWidth: options.minWidth,
minHeight: options.minHeight,
maxWidth: options.maxWidth,
maxHeight: options.maxHeight,
x: options.x,
y: options.y,
showMenuBar: options.showMenuBar,
fastQuit: options.fastQuit,
userAgent: options.userAgent,
nativefierVersion: options.nativefierVersion,
ignoreCertificate: options.ignoreCertificate,
disableGpu: options.disableGpu,
ignoreGpuBlacklist: options.ignoreGpuBlacklist,
enableEs3Apis: options.enableEs3Apis,
insecure: options.insecure,
flashPluginDir: options.flashPluginDir,
diskCacheSize: options.diskCacheSize,
fullScreen: options.fullScreen,
hideWindowFrame: options.hideWindowFrame,
maximize: options.maximize,
disableContextMenu: options.disableContextMenu,
disableDevTools: options.disableDevTools,
zoom: options.zoom,
internalUrls: options.internalUrls,
crashReporter: options.crashReporter,
singleInstance: options.singleInstance,
clearCache: options.clearCache,
appCopyright: options.appCopyright,
appVersion: options.appVersion,
buildVersion: options.buildVersion,
win32metadata: options.win32metadata,
versionString: options.versionString,
processEnvs: options.processEnvs,
fileDownloadOptions: options.fileDownloadOptions,
tray: options.tray,
basicAuthUsername: options.basicAuthUsername,
basicAuthPassword: options.basicAuthPassword,
alwaysOnTop: options.alwaysOnTop,
titleBarStyle: options.titleBarStyle,
globalShortcuts: options.globalShortcuts,
};
} | javascript | function selectAppArgs(options) {
return {
name: options.name,
targetUrl: options.targetUrl,
counter: options.counter,
bounce: options.bounce,
width: options.width,
height: options.height,
minWidth: options.minWidth,
minHeight: options.minHeight,
maxWidth: options.maxWidth,
maxHeight: options.maxHeight,
x: options.x,
y: options.y,
showMenuBar: options.showMenuBar,
fastQuit: options.fastQuit,
userAgent: options.userAgent,
nativefierVersion: options.nativefierVersion,
ignoreCertificate: options.ignoreCertificate,
disableGpu: options.disableGpu,
ignoreGpuBlacklist: options.ignoreGpuBlacklist,
enableEs3Apis: options.enableEs3Apis,
insecure: options.insecure,
flashPluginDir: options.flashPluginDir,
diskCacheSize: options.diskCacheSize,
fullScreen: options.fullScreen,
hideWindowFrame: options.hideWindowFrame,
maximize: options.maximize,
disableContextMenu: options.disableContextMenu,
disableDevTools: options.disableDevTools,
zoom: options.zoom,
internalUrls: options.internalUrls,
crashReporter: options.crashReporter,
singleInstance: options.singleInstance,
clearCache: options.clearCache,
appCopyright: options.appCopyright,
appVersion: options.appVersion,
buildVersion: options.buildVersion,
win32metadata: options.win32metadata,
versionString: options.versionString,
processEnvs: options.processEnvs,
fileDownloadOptions: options.fileDownloadOptions,
tray: options.tray,
basicAuthUsername: options.basicAuthUsername,
basicAuthPassword: options.basicAuthPassword,
alwaysOnTop: options.alwaysOnTop,
titleBarStyle: options.titleBarStyle,
globalShortcuts: options.globalShortcuts,
};
} | [
"function",
"selectAppArgs",
"(",
"options",
")",
"{",
"return",
"{",
"name",
":",
"options",
".",
"name",
",",
"targetUrl",
":",
"options",
".",
"targetUrl",
",",
"counter",
":",
"options",
".",
"counter",
",",
"bounce",
":",
"options",
".",
"bounce",
",",
"width",
":",
"options",
".",
"width",
",",
"height",
":",
"options",
".",
"height",
",",
"minWidth",
":",
"options",
".",
"minWidth",
",",
"minHeight",
":",
"options",
".",
"minHeight",
",",
"maxWidth",
":",
"options",
".",
"maxWidth",
",",
"maxHeight",
":",
"options",
".",
"maxHeight",
",",
"x",
":",
"options",
".",
"x",
",",
"y",
":",
"options",
".",
"y",
",",
"showMenuBar",
":",
"options",
".",
"showMenuBar",
",",
"fastQuit",
":",
"options",
".",
"fastQuit",
",",
"userAgent",
":",
"options",
".",
"userAgent",
",",
"nativefierVersion",
":",
"options",
".",
"nativefierVersion",
",",
"ignoreCertificate",
":",
"options",
".",
"ignoreCertificate",
",",
"disableGpu",
":",
"options",
".",
"disableGpu",
",",
"ignoreGpuBlacklist",
":",
"options",
".",
"ignoreGpuBlacklist",
",",
"enableEs3Apis",
":",
"options",
".",
"enableEs3Apis",
",",
"insecure",
":",
"options",
".",
"insecure",
",",
"flashPluginDir",
":",
"options",
".",
"flashPluginDir",
",",
"diskCacheSize",
":",
"options",
".",
"diskCacheSize",
",",
"fullScreen",
":",
"options",
".",
"fullScreen",
",",
"hideWindowFrame",
":",
"options",
".",
"hideWindowFrame",
",",
"maximize",
":",
"options",
".",
"maximize",
",",
"disableContextMenu",
":",
"options",
".",
"disableContextMenu",
",",
"disableDevTools",
":",
"options",
".",
"disableDevTools",
",",
"zoom",
":",
"options",
".",
"zoom",
",",
"internalUrls",
":",
"options",
".",
"internalUrls",
",",
"crashReporter",
":",
"options",
".",
"crashReporter",
",",
"singleInstance",
":",
"options",
".",
"singleInstance",
",",
"clearCache",
":",
"options",
".",
"clearCache",
",",
"appCopyright",
":",
"options",
".",
"appCopyright",
",",
"appVersion",
":",
"options",
".",
"appVersion",
",",
"buildVersion",
":",
"options",
".",
"buildVersion",
",",
"win32metadata",
":",
"options",
".",
"win32metadata",
",",
"versionString",
":",
"options",
".",
"versionString",
",",
"processEnvs",
":",
"options",
".",
"processEnvs",
",",
"fileDownloadOptions",
":",
"options",
".",
"fileDownloadOptions",
",",
"tray",
":",
"options",
".",
"tray",
",",
"basicAuthUsername",
":",
"options",
".",
"basicAuthUsername",
",",
"basicAuthPassword",
":",
"options",
".",
"basicAuthPassword",
",",
"alwaysOnTop",
":",
"options",
".",
"alwaysOnTop",
",",
"titleBarStyle",
":",
"options",
".",
"titleBarStyle",
",",
"globalShortcuts",
":",
"options",
".",
"globalShortcuts",
",",
"}",
";",
"}"
] | Only picks certain app args to pass to nativefier.json
@param options | [
"Only",
"picks",
"certain",
"app",
"args",
"to",
"pass",
"to",
"nativefier",
".",
"json"
] | b959956a38ce51a9dd95d42308f0a6c66489b624 | https://github.com/jiahaog/nativefier/blob/b959956a38ce51a9dd95d42308f0a6c66489b624/src/build/buildApp.js#L13-L62 |
1,009 | jiahaog/nativefier | src/helpers/convertToIcns.js | convertToIcnsTmp | function convertToIcnsTmp(pngSrc, callback) {
const tempIconDirObj = tmp.dirSync({ unsafeCleanup: true });
const tempIconDirPath = tempIconDirObj.name;
convertToIcns(pngSrc, `${tempIconDirPath}/icon.icns`, callback);
} | javascript | function convertToIcnsTmp(pngSrc, callback) {
const tempIconDirObj = tmp.dirSync({ unsafeCleanup: true });
const tempIconDirPath = tempIconDirObj.name;
convertToIcns(pngSrc, `${tempIconDirPath}/icon.icns`, callback);
} | [
"function",
"convertToIcnsTmp",
"(",
"pngSrc",
",",
"callback",
")",
"{",
"const",
"tempIconDirObj",
"=",
"tmp",
".",
"dirSync",
"(",
"{",
"unsafeCleanup",
":",
"true",
"}",
")",
";",
"const",
"tempIconDirPath",
"=",
"tempIconDirObj",
".",
"name",
";",
"convertToIcns",
"(",
"pngSrc",
",",
"`",
"${",
"tempIconDirPath",
"}",
"`",
",",
"callback",
")",
";",
"}"
] | Converts the png to a temporary directory which will be cleaned up on process exit
@param {string} pngSrc
@param {pngToIcnsCallback} callback | [
"Converts",
"the",
"png",
"to",
"a",
"temporary",
"directory",
"which",
"will",
"be",
"cleaned",
"up",
"on",
"process",
"exit"
] | b959956a38ce51a9dd95d42308f0a6c66489b624 | https://github.com/jiahaog/nativefier/blob/b959956a38ce51a9dd95d42308f0a6c66489b624/src/helpers/convertToIcns.js#L59-L63 |
1,010 | jiahaog/nativefier | app/src/helpers/helpers.js | debugLog | function debugLog(browserWindow, message) {
// need the timeout as it takes time for the preload javascript to be loaded in the window
setTimeout(() => {
browserWindow.webContents.send('debug', message);
}, 3000);
log.info(message);
} | javascript | function debugLog(browserWindow, message) {
// need the timeout as it takes time for the preload javascript to be loaded in the window
setTimeout(() => {
browserWindow.webContents.send('debug', message);
}, 3000);
log.info(message);
} | [
"function",
"debugLog",
"(",
"browserWindow",
",",
"message",
")",
"{",
"// need the timeout as it takes time for the preload javascript to be loaded in the window",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"browserWindow",
".",
"webContents",
".",
"send",
"(",
"'debug'",
",",
"message",
")",
";",
"}",
",",
"3000",
")",
";",
"log",
".",
"info",
"(",
"message",
")",
";",
"}"
] | Helper method to print debug messages from the main process in the browser window
@param {BrowserWindow} browserWindow
@param message | [
"Helper",
"method",
"to",
"print",
"debug",
"messages",
"from",
"the",
"main",
"process",
"in",
"the",
"browser",
"window"
] | b959956a38ce51a9dd95d42308f0a6c66489b624 | https://github.com/jiahaog/nativefier/blob/b959956a38ce51a9dd95d42308f0a6c66489b624/app/src/helpers/helpers.js#L54-L60 |
1,011 | codemirror/CodeMirror | src/display/update_display.js | patchDisplay | function patchDisplay(cm, updateNumbersFrom, dims) {
let display = cm.display, lineNumbers = cm.options.lineNumbers
let container = display.lineDiv, cur = container.firstChild
function rm(node) {
let next = node.nextSibling
// Works around a throw-scroll bug in OS X Webkit
if (webkit && mac && cm.display.currentWheelTarget == node)
node.style.display = "none"
else
node.parentNode.removeChild(node)
return next
}
let view = display.view, lineN = display.viewFrom
// Loop over the elements in the view, syncing cur (the DOM nodes
// in display.lineDiv) with the view as we go.
for (let i = 0; i < view.length; i++) {
let lineView = view[i]
if (lineView.hidden) {
} else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
let node = buildLineElement(cm, lineView, lineN, dims)
container.insertBefore(node, cur)
} else { // Already drawn
while (cur != lineView.node) cur = rm(cur)
let updateNumber = lineNumbers && updateNumbersFrom != null &&
updateNumbersFrom <= lineN && lineView.lineNumber
if (lineView.changes) {
if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false
updateLineForChanges(cm, lineView, lineN, dims)
}
if (updateNumber) {
removeChildren(lineView.lineNumber)
lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)))
}
cur = lineView.node.nextSibling
}
lineN += lineView.size
}
while (cur) cur = rm(cur)
} | javascript | function patchDisplay(cm, updateNumbersFrom, dims) {
let display = cm.display, lineNumbers = cm.options.lineNumbers
let container = display.lineDiv, cur = container.firstChild
function rm(node) {
let next = node.nextSibling
// Works around a throw-scroll bug in OS X Webkit
if (webkit && mac && cm.display.currentWheelTarget == node)
node.style.display = "none"
else
node.parentNode.removeChild(node)
return next
}
let view = display.view, lineN = display.viewFrom
// Loop over the elements in the view, syncing cur (the DOM nodes
// in display.lineDiv) with the view as we go.
for (let i = 0; i < view.length; i++) {
let lineView = view[i]
if (lineView.hidden) {
} else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
let node = buildLineElement(cm, lineView, lineN, dims)
container.insertBefore(node, cur)
} else { // Already drawn
while (cur != lineView.node) cur = rm(cur)
let updateNumber = lineNumbers && updateNumbersFrom != null &&
updateNumbersFrom <= lineN && lineView.lineNumber
if (lineView.changes) {
if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false
updateLineForChanges(cm, lineView, lineN, dims)
}
if (updateNumber) {
removeChildren(lineView.lineNumber)
lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)))
}
cur = lineView.node.nextSibling
}
lineN += lineView.size
}
while (cur) cur = rm(cur)
} | [
"function",
"patchDisplay",
"(",
"cm",
",",
"updateNumbersFrom",
",",
"dims",
")",
"{",
"let",
"display",
"=",
"cm",
".",
"display",
",",
"lineNumbers",
"=",
"cm",
".",
"options",
".",
"lineNumbers",
"let",
"container",
"=",
"display",
".",
"lineDiv",
",",
"cur",
"=",
"container",
".",
"firstChild",
"function",
"rm",
"(",
"node",
")",
"{",
"let",
"next",
"=",
"node",
".",
"nextSibling",
"// Works around a throw-scroll bug in OS X Webkit",
"if",
"(",
"webkit",
"&&",
"mac",
"&&",
"cm",
".",
"display",
".",
"currentWheelTarget",
"==",
"node",
")",
"node",
".",
"style",
".",
"display",
"=",
"\"none\"",
"else",
"node",
".",
"parentNode",
".",
"removeChild",
"(",
"node",
")",
"return",
"next",
"}",
"let",
"view",
"=",
"display",
".",
"view",
",",
"lineN",
"=",
"display",
".",
"viewFrom",
"// Loop over the elements in the view, syncing cur (the DOM nodes",
"// in display.lineDiv) with the view as we go.",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"view",
".",
"length",
";",
"i",
"++",
")",
"{",
"let",
"lineView",
"=",
"view",
"[",
"i",
"]",
"if",
"(",
"lineView",
".",
"hidden",
")",
"{",
"}",
"else",
"if",
"(",
"!",
"lineView",
".",
"node",
"||",
"lineView",
".",
"node",
".",
"parentNode",
"!=",
"container",
")",
"{",
"// Not drawn yet",
"let",
"node",
"=",
"buildLineElement",
"(",
"cm",
",",
"lineView",
",",
"lineN",
",",
"dims",
")",
"container",
".",
"insertBefore",
"(",
"node",
",",
"cur",
")",
"}",
"else",
"{",
"// Already drawn",
"while",
"(",
"cur",
"!=",
"lineView",
".",
"node",
")",
"cur",
"=",
"rm",
"(",
"cur",
")",
"let",
"updateNumber",
"=",
"lineNumbers",
"&&",
"updateNumbersFrom",
"!=",
"null",
"&&",
"updateNumbersFrom",
"<=",
"lineN",
"&&",
"lineView",
".",
"lineNumber",
"if",
"(",
"lineView",
".",
"changes",
")",
"{",
"if",
"(",
"indexOf",
"(",
"lineView",
".",
"changes",
",",
"\"gutter\"",
")",
">",
"-",
"1",
")",
"updateNumber",
"=",
"false",
"updateLineForChanges",
"(",
"cm",
",",
"lineView",
",",
"lineN",
",",
"dims",
")",
"}",
"if",
"(",
"updateNumber",
")",
"{",
"removeChildren",
"(",
"lineView",
".",
"lineNumber",
")",
"lineView",
".",
"lineNumber",
".",
"appendChild",
"(",
"document",
".",
"createTextNode",
"(",
"lineNumberFor",
"(",
"cm",
".",
"options",
",",
"lineN",
")",
")",
")",
"}",
"cur",
"=",
"lineView",
".",
"node",
".",
"nextSibling",
"}",
"lineN",
"+=",
"lineView",
".",
"size",
"}",
"while",
"(",
"cur",
")",
"cur",
"=",
"rm",
"(",
"cur",
")",
"}"
] | Sync the actual display DOM structure with display.view, removing nodes for lines that are no longer in view, and creating the ones that are not there yet, and updating the ones that are out of date. | [
"Sync",
"the",
"actual",
"display",
"DOM",
"structure",
"with",
"display",
".",
"view",
"removing",
"nodes",
"for",
"lines",
"that",
"are",
"no",
"longer",
"in",
"view",
"and",
"creating",
"the",
"ones",
"that",
"are",
"not",
"there",
"yet",
"and",
"updating",
"the",
"ones",
"that",
"are",
"out",
"of",
"date",
"."
] | dab6f676107c10ba8d16c654a42f66cae3f27db1 | https://github.com/codemirror/CodeMirror/blob/dab6f676107c10ba8d16c654a42f66cae3f27db1/src/display/update_display.js#L209-L249 |
1,012 | codemirror/CodeMirror | src/model/selection_updates.js | skipAtomicInSelection | function skipAtomicInSelection(doc, sel, bias, mayClear) {
let out
for (let i = 0; i < sel.ranges.length; i++) {
let range = sel.ranges[i]
let old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i]
let newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear)
let newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear)
if (out || newAnchor != range.anchor || newHead != range.head) {
if (!out) out = sel.ranges.slice(0, i)
out[i] = new Range(newAnchor, newHead)
}
}
return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel
} | javascript | function skipAtomicInSelection(doc, sel, bias, mayClear) {
let out
for (let i = 0; i < sel.ranges.length; i++) {
let range = sel.ranges[i]
let old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i]
let newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear)
let newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear)
if (out || newAnchor != range.anchor || newHead != range.head) {
if (!out) out = sel.ranges.slice(0, i)
out[i] = new Range(newAnchor, newHead)
}
}
return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel
} | [
"function",
"skipAtomicInSelection",
"(",
"doc",
",",
"sel",
",",
"bias",
",",
"mayClear",
")",
"{",
"let",
"out",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"sel",
".",
"ranges",
".",
"length",
";",
"i",
"++",
")",
"{",
"let",
"range",
"=",
"sel",
".",
"ranges",
"[",
"i",
"]",
"let",
"old",
"=",
"sel",
".",
"ranges",
".",
"length",
"==",
"doc",
".",
"sel",
".",
"ranges",
".",
"length",
"&&",
"doc",
".",
"sel",
".",
"ranges",
"[",
"i",
"]",
"let",
"newAnchor",
"=",
"skipAtomic",
"(",
"doc",
",",
"range",
".",
"anchor",
",",
"old",
"&&",
"old",
".",
"anchor",
",",
"bias",
",",
"mayClear",
")",
"let",
"newHead",
"=",
"skipAtomic",
"(",
"doc",
",",
"range",
".",
"head",
",",
"old",
"&&",
"old",
".",
"head",
",",
"bias",
",",
"mayClear",
")",
"if",
"(",
"out",
"||",
"newAnchor",
"!=",
"range",
".",
"anchor",
"||",
"newHead",
"!=",
"range",
".",
"head",
")",
"{",
"if",
"(",
"!",
"out",
")",
"out",
"=",
"sel",
".",
"ranges",
".",
"slice",
"(",
"0",
",",
"i",
")",
"out",
"[",
"i",
"]",
"=",
"new",
"Range",
"(",
"newAnchor",
",",
"newHead",
")",
"}",
"}",
"return",
"out",
"?",
"normalizeSelection",
"(",
"doc",
".",
"cm",
",",
"out",
",",
"sel",
".",
"primIndex",
")",
":",
"sel",
"}"
] | Return a selection that does not partially select any atomic ranges. | [
"Return",
"a",
"selection",
"that",
"does",
"not",
"partially",
"select",
"any",
"atomic",
"ranges",
"."
] | dab6f676107c10ba8d16c654a42f66cae3f27db1 | https://github.com/codemirror/CodeMirror/blob/dab6f676107c10ba8d16c654a42f66cae3f27db1/src/model/selection_updates.js#L134-L147 |
1,013 | codemirror/CodeMirror | src/model/history.js | lastChangeEvent | function lastChangeEvent(hist, force) {
if (force) {
clearSelectionEvents(hist.done)
return lst(hist.done)
} else if (hist.done.length && !lst(hist.done).ranges) {
return lst(hist.done)
} else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
hist.done.pop()
return lst(hist.done)
}
} | javascript | function lastChangeEvent(hist, force) {
if (force) {
clearSelectionEvents(hist.done)
return lst(hist.done)
} else if (hist.done.length && !lst(hist.done).ranges) {
return lst(hist.done)
} else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
hist.done.pop()
return lst(hist.done)
}
} | [
"function",
"lastChangeEvent",
"(",
"hist",
",",
"force",
")",
"{",
"if",
"(",
"force",
")",
"{",
"clearSelectionEvents",
"(",
"hist",
".",
"done",
")",
"return",
"lst",
"(",
"hist",
".",
"done",
")",
"}",
"else",
"if",
"(",
"hist",
".",
"done",
".",
"length",
"&&",
"!",
"lst",
"(",
"hist",
".",
"done",
")",
".",
"ranges",
")",
"{",
"return",
"lst",
"(",
"hist",
".",
"done",
")",
"}",
"else",
"if",
"(",
"hist",
".",
"done",
".",
"length",
">",
"1",
"&&",
"!",
"hist",
".",
"done",
"[",
"hist",
".",
"done",
".",
"length",
"-",
"2",
"]",
".",
"ranges",
")",
"{",
"hist",
".",
"done",
".",
"pop",
"(",
")",
"return",
"lst",
"(",
"hist",
".",
"done",
")",
"}",
"}"
] | Find the top change event in the history. Pop off selection events that are in the way. | [
"Find",
"the",
"top",
"change",
"event",
"in",
"the",
"history",
".",
"Pop",
"off",
"selection",
"events",
"that",
"are",
"in",
"the",
"way",
"."
] | dab6f676107c10ba8d16c654a42f66cae3f27db1 | https://github.com/codemirror/CodeMirror/blob/dab6f676107c10ba8d16c654a42f66cae3f27db1/src/model/history.js#L47-L57 |
1,014 | codemirror/CodeMirror | src/model/history.js | getOldSpans | function getOldSpans(doc, change) {
let found = change["spans_" + doc.id]
if (!found) return null
let nw = []
for (let i = 0; i < change.text.length; ++i)
nw.push(removeClearedSpans(found[i]))
return nw
} | javascript | function getOldSpans(doc, change) {
let found = change["spans_" + doc.id]
if (!found) return null
let nw = []
for (let i = 0; i < change.text.length; ++i)
nw.push(removeClearedSpans(found[i]))
return nw
} | [
"function",
"getOldSpans",
"(",
"doc",
",",
"change",
")",
"{",
"let",
"found",
"=",
"change",
"[",
"\"spans_\"",
"+",
"doc",
".",
"id",
"]",
"if",
"(",
"!",
"found",
")",
"return",
"null",
"let",
"nw",
"=",
"[",
"]",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"change",
".",
"text",
".",
"length",
";",
"++",
"i",
")",
"nw",
".",
"push",
"(",
"removeClearedSpans",
"(",
"found",
"[",
"i",
"]",
")",
")",
"return",
"nw",
"}"
] | Retrieve and filter the old marked spans stored in a change event. | [
"Retrieve",
"and",
"filter",
"the",
"old",
"marked",
"spans",
"stored",
"in",
"a",
"change",
"event",
"."
] | dab6f676107c10ba8d16c654a42f66cae3f27db1 | https://github.com/codemirror/CodeMirror/blob/dab6f676107c10ba8d16c654a42f66cae3f27db1/src/model/history.js#L169-L176 |
1,015 | codemirror/CodeMirror | src/edit/key_events.js | handleKeyBinding | function handleKeyBinding(cm, e) {
let name = keyName(e, true)
if (!name) return false
if (e.shiftKey && !cm.state.keySeq) {
// First try to resolve full name (including 'Shift-'). Failing
// that, see if there is a cursor-motion command (starting with
// 'go') bound to the keyname without 'Shift-'.
return dispatchKey(cm, "Shift-" + name, e, b => doHandleBinding(cm, b, true))
|| dispatchKey(cm, name, e, b => {
if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
return doHandleBinding(cm, b)
})
} else {
return dispatchKey(cm, name, e, b => doHandleBinding(cm, b))
}
} | javascript | function handleKeyBinding(cm, e) {
let name = keyName(e, true)
if (!name) return false
if (e.shiftKey && !cm.state.keySeq) {
// First try to resolve full name (including 'Shift-'). Failing
// that, see if there is a cursor-motion command (starting with
// 'go') bound to the keyname without 'Shift-'.
return dispatchKey(cm, "Shift-" + name, e, b => doHandleBinding(cm, b, true))
|| dispatchKey(cm, name, e, b => {
if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
return doHandleBinding(cm, b)
})
} else {
return dispatchKey(cm, name, e, b => doHandleBinding(cm, b))
}
} | [
"function",
"handleKeyBinding",
"(",
"cm",
",",
"e",
")",
"{",
"let",
"name",
"=",
"keyName",
"(",
"e",
",",
"true",
")",
"if",
"(",
"!",
"name",
")",
"return",
"false",
"if",
"(",
"e",
".",
"shiftKey",
"&&",
"!",
"cm",
".",
"state",
".",
"keySeq",
")",
"{",
"// First try to resolve full name (including 'Shift-'). Failing",
"// that, see if there is a cursor-motion command (starting with",
"// 'go') bound to the keyname without 'Shift-'.",
"return",
"dispatchKey",
"(",
"cm",
",",
"\"Shift-\"",
"+",
"name",
",",
"e",
",",
"b",
"=>",
"doHandleBinding",
"(",
"cm",
",",
"b",
",",
"true",
")",
")",
"||",
"dispatchKey",
"(",
"cm",
",",
"name",
",",
"e",
",",
"b",
"=>",
"{",
"if",
"(",
"typeof",
"b",
"==",
"\"string\"",
"?",
"/",
"^go[A-Z]",
"/",
".",
"test",
"(",
"b",
")",
":",
"b",
".",
"motion",
")",
"return",
"doHandleBinding",
"(",
"cm",
",",
"b",
")",
"}",
")",
"}",
"else",
"{",
"return",
"dispatchKey",
"(",
"cm",
",",
"name",
",",
"e",
",",
"b",
"=>",
"doHandleBinding",
"(",
"cm",
",",
"b",
")",
")",
"}",
"}"
] | Handle a key from the keydown event. | [
"Handle",
"a",
"key",
"from",
"the",
"keydown",
"event",
"."
] | dab6f676107c10ba8d16c654a42f66cae3f27db1 | https://github.com/codemirror/CodeMirror/blob/dab6f676107c10ba8d16c654a42f66cae3f27db1/src/edit/key_events.js#L83-L99 |
1,016 | codemirror/CodeMirror | src/edit/key_events.js | handleCharBinding | function handleCharBinding(cm, e, ch) {
return dispatchKey(cm, "'" + ch + "'", e, b => doHandleBinding(cm, b, true))
} | javascript | function handleCharBinding(cm, e, ch) {
return dispatchKey(cm, "'" + ch + "'", e, b => doHandleBinding(cm, b, true))
} | [
"function",
"handleCharBinding",
"(",
"cm",
",",
"e",
",",
"ch",
")",
"{",
"return",
"dispatchKey",
"(",
"cm",
",",
"\"'\"",
"+",
"ch",
"+",
"\"'\"",
",",
"e",
",",
"b",
"=>",
"doHandleBinding",
"(",
"cm",
",",
"b",
",",
"true",
")",
")",
"}"
] | Handle a key from the keypress event | [
"Handle",
"a",
"key",
"from",
"the",
"keypress",
"event"
] | dab6f676107c10ba8d16c654a42f66cae3f27db1 | https://github.com/codemirror/CodeMirror/blob/dab6f676107c10ba8d16c654a42f66cae3f27db1/src/edit/key_events.js#L102-L104 |
1,017 | codemirror/CodeMirror | src/measurement/position_measurement.js | boxIsAfter | function boxIsAfter(box, x, y, left) {
return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
} | javascript | function boxIsAfter(box, x, y, left) {
return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
} | [
"function",
"boxIsAfter",
"(",
"box",
",",
"x",
",",
"y",
",",
"left",
")",
"{",
"return",
"box",
".",
"bottom",
"<=",
"y",
"?",
"false",
":",
"box",
".",
"top",
">",
"y",
"?",
"true",
":",
"(",
"left",
"?",
"box",
".",
"left",
":",
"box",
".",
"right",
")",
">",
"x",
"}"
] | Returns true if the given side of a box is after the given coordinates, in top-to-bottom, left-to-right order. | [
"Returns",
"true",
"if",
"the",
"given",
"side",
"of",
"a",
"box",
"is",
"after",
"the",
"given",
"coordinates",
"in",
"top",
"-",
"to",
"-",
"bottom",
"left",
"-",
"to",
"-",
"right",
"order",
"."
] | dab6f676107c10ba8d16c654a42f66cae3f27db1 | https://github.com/codemirror/CodeMirror/blob/dab6f676107c10ba8d16c654a42f66cae3f27db1/src/measurement/position_measurement.js#L457-L459 |
1,018 | codemirror/CodeMirror | src/line/highlight.js | runMode | function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
let flattenSpans = mode.flattenSpans
if (flattenSpans == null) flattenSpans = cm.options.flattenSpans
let curStart = 0, curStyle = null
let stream = new StringStream(text, cm.options.tabSize, context), style
let inner = cm.options.addModeClass && [null]
if (text == "") extractLineClasses(callBlankLine(mode, context.state), lineClasses)
while (!stream.eol()) {
if (stream.pos > cm.options.maxHighlightLength) {
flattenSpans = false
if (forceToEnd) processLine(cm, text, context, stream.pos)
stream.pos = text.length
style = null
} else {
style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses)
}
if (inner) {
let mName = inner[0].name
if (mName) style = "m-" + (style ? mName + " " + style : mName)
}
if (!flattenSpans || curStyle != style) {
while (curStart < stream.start) {
curStart = Math.min(stream.start, curStart + 5000)
f(curStart, curStyle)
}
curStyle = style
}
stream.start = stream.pos
}
while (curStart < stream.pos) {
// Webkit seems to refuse to render text nodes longer than 57444
// characters, and returns inaccurate measurements in nodes
// starting around 5000 chars.
let pos = Math.min(stream.pos, curStart + 5000)
f(pos, curStyle)
curStart = pos
}
} | javascript | function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
let flattenSpans = mode.flattenSpans
if (flattenSpans == null) flattenSpans = cm.options.flattenSpans
let curStart = 0, curStyle = null
let stream = new StringStream(text, cm.options.tabSize, context), style
let inner = cm.options.addModeClass && [null]
if (text == "") extractLineClasses(callBlankLine(mode, context.state), lineClasses)
while (!stream.eol()) {
if (stream.pos > cm.options.maxHighlightLength) {
flattenSpans = false
if (forceToEnd) processLine(cm, text, context, stream.pos)
stream.pos = text.length
style = null
} else {
style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses)
}
if (inner) {
let mName = inner[0].name
if (mName) style = "m-" + (style ? mName + " " + style : mName)
}
if (!flattenSpans || curStyle != style) {
while (curStart < stream.start) {
curStart = Math.min(stream.start, curStart + 5000)
f(curStart, curStyle)
}
curStyle = style
}
stream.start = stream.pos
}
while (curStart < stream.pos) {
// Webkit seems to refuse to render text nodes longer than 57444
// characters, and returns inaccurate measurements in nodes
// starting around 5000 chars.
let pos = Math.min(stream.pos, curStart + 5000)
f(pos, curStyle)
curStart = pos
}
} | [
"function",
"runMode",
"(",
"cm",
",",
"text",
",",
"mode",
",",
"context",
",",
"f",
",",
"lineClasses",
",",
"forceToEnd",
")",
"{",
"let",
"flattenSpans",
"=",
"mode",
".",
"flattenSpans",
"if",
"(",
"flattenSpans",
"==",
"null",
")",
"flattenSpans",
"=",
"cm",
".",
"options",
".",
"flattenSpans",
"let",
"curStart",
"=",
"0",
",",
"curStyle",
"=",
"null",
"let",
"stream",
"=",
"new",
"StringStream",
"(",
"text",
",",
"cm",
".",
"options",
".",
"tabSize",
",",
"context",
")",
",",
"style",
"let",
"inner",
"=",
"cm",
".",
"options",
".",
"addModeClass",
"&&",
"[",
"null",
"]",
"if",
"(",
"text",
"==",
"\"\"",
")",
"extractLineClasses",
"(",
"callBlankLine",
"(",
"mode",
",",
"context",
".",
"state",
")",
",",
"lineClasses",
")",
"while",
"(",
"!",
"stream",
".",
"eol",
"(",
")",
")",
"{",
"if",
"(",
"stream",
".",
"pos",
">",
"cm",
".",
"options",
".",
"maxHighlightLength",
")",
"{",
"flattenSpans",
"=",
"false",
"if",
"(",
"forceToEnd",
")",
"processLine",
"(",
"cm",
",",
"text",
",",
"context",
",",
"stream",
".",
"pos",
")",
"stream",
".",
"pos",
"=",
"text",
".",
"length",
"style",
"=",
"null",
"}",
"else",
"{",
"style",
"=",
"extractLineClasses",
"(",
"readToken",
"(",
"mode",
",",
"stream",
",",
"context",
".",
"state",
",",
"inner",
")",
",",
"lineClasses",
")",
"}",
"if",
"(",
"inner",
")",
"{",
"let",
"mName",
"=",
"inner",
"[",
"0",
"]",
".",
"name",
"if",
"(",
"mName",
")",
"style",
"=",
"\"m-\"",
"+",
"(",
"style",
"?",
"mName",
"+",
"\" \"",
"+",
"style",
":",
"mName",
")",
"}",
"if",
"(",
"!",
"flattenSpans",
"||",
"curStyle",
"!=",
"style",
")",
"{",
"while",
"(",
"curStart",
"<",
"stream",
".",
"start",
")",
"{",
"curStart",
"=",
"Math",
".",
"min",
"(",
"stream",
".",
"start",
",",
"curStart",
"+",
"5000",
")",
"f",
"(",
"curStart",
",",
"curStyle",
")",
"}",
"curStyle",
"=",
"style",
"}",
"stream",
".",
"start",
"=",
"stream",
".",
"pos",
"}",
"while",
"(",
"curStart",
"<",
"stream",
".",
"pos",
")",
"{",
"// Webkit seems to refuse to render text nodes longer than 57444",
"// characters, and returns inaccurate measurements in nodes",
"// starting around 5000 chars.",
"let",
"pos",
"=",
"Math",
".",
"min",
"(",
"stream",
".",
"pos",
",",
"curStart",
"+",
"5000",
")",
"f",
"(",
"pos",
",",
"curStyle",
")",
"curStart",
"=",
"pos",
"}",
"}"
] | Run the given mode's parser over a line, calling f for each token. | [
"Run",
"the",
"given",
"mode",
"s",
"parser",
"over",
"a",
"line",
"calling",
"f",
"for",
"each",
"token",
"."
] | dab6f676107c10ba8d16c654a42f66cae3f27db1 | https://github.com/codemirror/CodeMirror/blob/dab6f676107c10ba8d16c654a42f66cae3f27db1/src/line/highlight.js#L208-L245 |
1,019 | codemirror/CodeMirror | src/edit/global_events.js | onResize | function onResize(cm) {
let d = cm.display
// Might be a text scaling operation, clear size caches.
d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null
d.scrollbarsClipped = false
cm.setSize()
} | javascript | function onResize(cm) {
let d = cm.display
// Might be a text scaling operation, clear size caches.
d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null
d.scrollbarsClipped = false
cm.setSize()
} | [
"function",
"onResize",
"(",
"cm",
")",
"{",
"let",
"d",
"=",
"cm",
".",
"display",
"// Might be a text scaling operation, clear size caches.",
"d",
".",
"cachedCharWidth",
"=",
"d",
".",
"cachedTextHeight",
"=",
"d",
".",
"cachedPaddingH",
"=",
"null",
"d",
".",
"scrollbarsClipped",
"=",
"false",
"cm",
".",
"setSize",
"(",
")",
"}"
] | Called when the window resizes | [
"Called",
"when",
"the",
"window",
"resizes"
] | dab6f676107c10ba8d16c654a42f66cae3f27db1 | https://github.com/codemirror/CodeMirror/blob/dab6f676107c10ba8d16c654a42f66cae3f27db1/src/edit/global_events.js#L39-L45 |
1,020 | codemirror/CodeMirror | src/model/changes.js | makeChangeSingleDocInEditor | function makeChangeSingleDocInEditor(cm, change, spans) {
let doc = cm.doc, display = cm.display, from = change.from, to = change.to
let recomputeMaxLength = false, checkWidthStart = from.line
if (!cm.options.lineWrapping) {
checkWidthStart = lineNo(visualLine(getLine(doc, from.line)))
doc.iter(checkWidthStart, to.line + 1, line => {
if (line == display.maxLine) {
recomputeMaxLength = true
return true
}
})
}
if (doc.sel.contains(change.from, change.to) > -1)
signalCursorActivity(cm)
updateDoc(doc, change, spans, estimateHeight(cm))
if (!cm.options.lineWrapping) {
doc.iter(checkWidthStart, from.line + change.text.length, line => {
let len = lineLength(line)
if (len > display.maxLineLength) {
display.maxLine = line
display.maxLineLength = len
display.maxLineChanged = true
recomputeMaxLength = false
}
})
if (recomputeMaxLength) cm.curOp.updateMaxLine = true
}
retreatFrontier(doc, from.line)
startWorker(cm, 400)
let lendiff = change.text.length - (to.line - from.line) - 1
// Remember that these lines changed, for updating the display
if (change.full)
regChange(cm)
else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
regLineChange(cm, from.line, "text")
else
regChange(cm, from.line, to.line + 1, lendiff)
let changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change")
if (changeHandler || changesHandler) {
let obj = {
from: from, to: to,
text: change.text,
removed: change.removed,
origin: change.origin
}
if (changeHandler) signalLater(cm, "change", cm, obj)
if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj)
}
cm.display.selForContextMenu = null
} | javascript | function makeChangeSingleDocInEditor(cm, change, spans) {
let doc = cm.doc, display = cm.display, from = change.from, to = change.to
let recomputeMaxLength = false, checkWidthStart = from.line
if (!cm.options.lineWrapping) {
checkWidthStart = lineNo(visualLine(getLine(doc, from.line)))
doc.iter(checkWidthStart, to.line + 1, line => {
if (line == display.maxLine) {
recomputeMaxLength = true
return true
}
})
}
if (doc.sel.contains(change.from, change.to) > -1)
signalCursorActivity(cm)
updateDoc(doc, change, spans, estimateHeight(cm))
if (!cm.options.lineWrapping) {
doc.iter(checkWidthStart, from.line + change.text.length, line => {
let len = lineLength(line)
if (len > display.maxLineLength) {
display.maxLine = line
display.maxLineLength = len
display.maxLineChanged = true
recomputeMaxLength = false
}
})
if (recomputeMaxLength) cm.curOp.updateMaxLine = true
}
retreatFrontier(doc, from.line)
startWorker(cm, 400)
let lendiff = change.text.length - (to.line - from.line) - 1
// Remember that these lines changed, for updating the display
if (change.full)
regChange(cm)
else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
regLineChange(cm, from.line, "text")
else
regChange(cm, from.line, to.line + 1, lendiff)
let changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change")
if (changeHandler || changesHandler) {
let obj = {
from: from, to: to,
text: change.text,
removed: change.removed,
origin: change.origin
}
if (changeHandler) signalLater(cm, "change", cm, obj)
if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj)
}
cm.display.selForContextMenu = null
} | [
"function",
"makeChangeSingleDocInEditor",
"(",
"cm",
",",
"change",
",",
"spans",
")",
"{",
"let",
"doc",
"=",
"cm",
".",
"doc",
",",
"display",
"=",
"cm",
".",
"display",
",",
"from",
"=",
"change",
".",
"from",
",",
"to",
"=",
"change",
".",
"to",
"let",
"recomputeMaxLength",
"=",
"false",
",",
"checkWidthStart",
"=",
"from",
".",
"line",
"if",
"(",
"!",
"cm",
".",
"options",
".",
"lineWrapping",
")",
"{",
"checkWidthStart",
"=",
"lineNo",
"(",
"visualLine",
"(",
"getLine",
"(",
"doc",
",",
"from",
".",
"line",
")",
")",
")",
"doc",
".",
"iter",
"(",
"checkWidthStart",
",",
"to",
".",
"line",
"+",
"1",
",",
"line",
"=>",
"{",
"if",
"(",
"line",
"==",
"display",
".",
"maxLine",
")",
"{",
"recomputeMaxLength",
"=",
"true",
"return",
"true",
"}",
"}",
")",
"}",
"if",
"(",
"doc",
".",
"sel",
".",
"contains",
"(",
"change",
".",
"from",
",",
"change",
".",
"to",
")",
">",
"-",
"1",
")",
"signalCursorActivity",
"(",
"cm",
")",
"updateDoc",
"(",
"doc",
",",
"change",
",",
"spans",
",",
"estimateHeight",
"(",
"cm",
")",
")",
"if",
"(",
"!",
"cm",
".",
"options",
".",
"lineWrapping",
")",
"{",
"doc",
".",
"iter",
"(",
"checkWidthStart",
",",
"from",
".",
"line",
"+",
"change",
".",
"text",
".",
"length",
",",
"line",
"=>",
"{",
"let",
"len",
"=",
"lineLength",
"(",
"line",
")",
"if",
"(",
"len",
">",
"display",
".",
"maxLineLength",
")",
"{",
"display",
".",
"maxLine",
"=",
"line",
"display",
".",
"maxLineLength",
"=",
"len",
"display",
".",
"maxLineChanged",
"=",
"true",
"recomputeMaxLength",
"=",
"false",
"}",
"}",
")",
"if",
"(",
"recomputeMaxLength",
")",
"cm",
".",
"curOp",
".",
"updateMaxLine",
"=",
"true",
"}",
"retreatFrontier",
"(",
"doc",
",",
"from",
".",
"line",
")",
"startWorker",
"(",
"cm",
",",
"400",
")",
"let",
"lendiff",
"=",
"change",
".",
"text",
".",
"length",
"-",
"(",
"to",
".",
"line",
"-",
"from",
".",
"line",
")",
"-",
"1",
"// Remember that these lines changed, for updating the display",
"if",
"(",
"change",
".",
"full",
")",
"regChange",
"(",
"cm",
")",
"else",
"if",
"(",
"from",
".",
"line",
"==",
"to",
".",
"line",
"&&",
"change",
".",
"text",
".",
"length",
"==",
"1",
"&&",
"!",
"isWholeLineUpdate",
"(",
"cm",
".",
"doc",
",",
"change",
")",
")",
"regLineChange",
"(",
"cm",
",",
"from",
".",
"line",
",",
"\"text\"",
")",
"else",
"regChange",
"(",
"cm",
",",
"from",
".",
"line",
",",
"to",
".",
"line",
"+",
"1",
",",
"lendiff",
")",
"let",
"changesHandler",
"=",
"hasHandler",
"(",
"cm",
",",
"\"changes\"",
")",
",",
"changeHandler",
"=",
"hasHandler",
"(",
"cm",
",",
"\"change\"",
")",
"if",
"(",
"changeHandler",
"||",
"changesHandler",
")",
"{",
"let",
"obj",
"=",
"{",
"from",
":",
"from",
",",
"to",
":",
"to",
",",
"text",
":",
"change",
".",
"text",
",",
"removed",
":",
"change",
".",
"removed",
",",
"origin",
":",
"change",
".",
"origin",
"}",
"if",
"(",
"changeHandler",
")",
"signalLater",
"(",
"cm",
",",
"\"change\"",
",",
"cm",
",",
"obj",
")",
"if",
"(",
"changesHandler",
")",
"(",
"cm",
".",
"curOp",
".",
"changeObjs",
"||",
"(",
"cm",
".",
"curOp",
".",
"changeObjs",
"=",
"[",
"]",
")",
")",
".",
"push",
"(",
"obj",
")",
"}",
"cm",
".",
"display",
".",
"selForContextMenu",
"=",
"null",
"}"
] | Handle the interaction of a change to a document with the editor that this document is part of. | [
"Handle",
"the",
"interaction",
"of",
"a",
"change",
"to",
"a",
"document",
"with",
"the",
"editor",
"that",
"this",
"document",
"is",
"part",
"of",
"."
] | dab6f676107c10ba8d16c654a42f66cae3f27db1 | https://github.com/codemirror/CodeMirror/blob/dab6f676107c10ba8d16c654a42f66cae3f27db1/src/model/changes.js#L209-L265 |
1,021 | testing-library/react-testing-library | src/act-compat.js | actPolyfill | function actPolyfill(cb) {
ReactDOM.unstable_batchedUpdates(cb)
ReactDOM.render(<div />, document.createElement('div'))
} | javascript | function actPolyfill(cb) {
ReactDOM.unstable_batchedUpdates(cb)
ReactDOM.render(<div />, document.createElement('div'))
} | [
"function",
"actPolyfill",
"(",
"cb",
")",
"{",
"ReactDOM",
".",
"unstable_batchedUpdates",
"(",
"cb",
")",
"ReactDOM",
".",
"render",
"(",
"<",
"div",
"/",
">",
",",
"document",
".",
"createElement",
"(",
"'div'",
")",
")",
"}"
] | act is supported react-dom@16.8.0 so for versions that don't have act from test utils we do this little polyfill. No warnings, but it's better than nothing. | [
"act",
"is",
"supported",
"react",
"-",
"dom"
] | 960451b00196352fc3085a3d1bb233b5b85f454b | https://github.com/testing-library/react-testing-library/blob/960451b00196352fc3085a3d1bb233b5b85f454b/src/act-compat.js#L33-L36 |
1,022 | testing-library/react-testing-library | src/act-compat.js | asyncActPolyfill | async function asyncActPolyfill(cb) {
// istanbul-ignore-next
if (
!youHaveBeenWarned &&
actSupported &&
reactDomSixteenPointNineIsReleased
) {
// if act is supported and async act isn't and they're trying to use async
// act, then they need to upgrade from 16.8 to 16.9.
// This is a seemless upgrade, so we'll add a warning
console.error(
`It looks like you're using a version of react-dom that supports the "act" function, but not an awaitable version of "act" which you will need. Please upgrade to at least react-dom@16.9.0 to remove this warning.`,
)
youHaveBeenWarned = true
}
await cb()
// make all effects resolve after
act(() => {})
} | javascript | async function asyncActPolyfill(cb) {
// istanbul-ignore-next
if (
!youHaveBeenWarned &&
actSupported &&
reactDomSixteenPointNineIsReleased
) {
// if act is supported and async act isn't and they're trying to use async
// act, then they need to upgrade from 16.8 to 16.9.
// This is a seemless upgrade, so we'll add a warning
console.error(
`It looks like you're using a version of react-dom that supports the "act" function, but not an awaitable version of "act" which you will need. Please upgrade to at least react-dom@16.9.0 to remove this warning.`,
)
youHaveBeenWarned = true
}
await cb()
// make all effects resolve after
act(() => {})
} | [
"async",
"function",
"asyncActPolyfill",
"(",
"cb",
")",
"{",
"// istanbul-ignore-next",
"if",
"(",
"!",
"youHaveBeenWarned",
"&&",
"actSupported",
"&&",
"reactDomSixteenPointNineIsReleased",
")",
"{",
"// if act is supported and async act isn't and they're trying to use async",
"// act, then they need to upgrade from 16.8 to 16.9.",
"// This is a seemless upgrade, so we'll add a warning",
"console",
".",
"error",
"(",
"`",
"`",
",",
")",
"youHaveBeenWarned",
"=",
"true",
"}",
"await",
"cb",
"(",
")",
"// make all effects resolve after",
"act",
"(",
"(",
")",
"=>",
"{",
"}",
")",
"}"
] | this will not avoid warnings that react-dom 16.8.0 logs for triggering state updates asynchronously, but at least we can tell people they need to upgrade to avoid the warnings. | [
"this",
"will",
"not",
"avoid",
"warnings",
"that",
"react",
"-",
"dom",
"16",
".",
"8",
".",
"0",
"logs",
"for",
"triggering",
"state",
"updates",
"asynchronously",
"but",
"at",
"least",
"we",
"can",
"tell",
"people",
"they",
"need",
"to",
"upgrade",
"to",
"avoid",
"the",
"warnings",
"."
] | 960451b00196352fc3085a3d1bb233b5b85f454b | https://github.com/testing-library/react-testing-library/blob/960451b00196352fc3085a3d1bb233b5b85f454b/src/act-compat.js#L44-L62 |
1,023 | emberjs/ember.js | broccoli/build-info.js | readPackageVersion | function readPackageVersion(root) {
let pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
// use _originalVersion if present if we've already mutated it
return pkg._originalVersion || pkg.version;
} | javascript | function readPackageVersion(root) {
let pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
// use _originalVersion if present if we've already mutated it
return pkg._originalVersion || pkg.version;
} | [
"function",
"readPackageVersion",
"(",
"root",
")",
"{",
"let",
"pkg",
"=",
"JSON",
".",
"parse",
"(",
"fs",
".",
"readFileSync",
"(",
"path",
".",
"join",
"(",
"root",
",",
"'package.json'",
")",
",",
"'utf8'",
")",
")",
";",
"// use _originalVersion if present if we've already mutated it",
"return",
"pkg",
".",
"_originalVersion",
"||",
"pkg",
".",
"version",
";",
"}"
] | Read package version.
@param {string} root
@returns {string} | [
"Read",
"package",
"version",
"."
] | 7ef1d08b7fe44000cf97b3c43566d20337b0683d | https://github.com/emberjs/ember.js/blob/7ef1d08b7fe44000cf97b3c43566d20337b0683d/broccoli/build-info.js#L126-L130 |
1,024 | askmike/gekko | plugins/pushbullet.js | getNumStr | function getNumStr(num, fixed = 4) {
let numStr = '';
if (typeof num != "number") {
num = Number(num);
if (isNaN(num)) {
// console.log("Pushbullet Plugin: Number Conversion Failed");
return "Conversion Failure";
}
}
if (Number.isInteger(num)) {
numStr = num.toString();
} else {
//Create modNum Max - Must be a better way...
let modNumMax = '1';
for (let i = 1; i < fixed; i++) {
modNumMax = modNumMax + '0';
}
modNumMax = Number(modNumMax);
let i = 0;
if (num < 1) {
let modNum = num - Math.floor(num);
while (modNum < modNumMax && i < 8) {
modNum *= 10;
i += 1;
}
} else {
i = fixed;
}
numStr = num.toFixed(i);
//Remove any excess zeros
while (numStr.charAt(numStr.length - 1) === '0') {
numStr = numStr.substring(0, numStr.length - 1);
}
//If last char remaining is a decimal point, remove it
if (numStr.charAt(numStr.length - 1) === '.') {
numStr = numStr.substring(0, numStr.length - 1);
}
}
//Add commas for thousands etc
let dp = numStr.indexOf('.'); //find deciaml point
if (dp < 0) { //no dp found
dp = numStr.length;
}
let insPos = dp - 3;
insCount = 0;
while (insPos > 0) {
insCount++;
numStr = numStr.slice(0, insPos) + ',' + numStr.slice(insPos);
insPos -= 3;
}
return (numStr);
} | javascript | function getNumStr(num, fixed = 4) {
let numStr = '';
if (typeof num != "number") {
num = Number(num);
if (isNaN(num)) {
// console.log("Pushbullet Plugin: Number Conversion Failed");
return "Conversion Failure";
}
}
if (Number.isInteger(num)) {
numStr = num.toString();
} else {
//Create modNum Max - Must be a better way...
let modNumMax = '1';
for (let i = 1; i < fixed; i++) {
modNumMax = modNumMax + '0';
}
modNumMax = Number(modNumMax);
let i = 0;
if (num < 1) {
let modNum = num - Math.floor(num);
while (modNum < modNumMax && i < 8) {
modNum *= 10;
i += 1;
}
} else {
i = fixed;
}
numStr = num.toFixed(i);
//Remove any excess zeros
while (numStr.charAt(numStr.length - 1) === '0') {
numStr = numStr.substring(0, numStr.length - 1);
}
//If last char remaining is a decimal point, remove it
if (numStr.charAt(numStr.length - 1) === '.') {
numStr = numStr.substring(0, numStr.length - 1);
}
}
//Add commas for thousands etc
let dp = numStr.indexOf('.'); //find deciaml point
if (dp < 0) { //no dp found
dp = numStr.length;
}
let insPos = dp - 3;
insCount = 0;
while (insPos > 0) {
insCount++;
numStr = numStr.slice(0, insPos) + ',' + numStr.slice(insPos);
insPos -= 3;
}
return (numStr);
} | [
"function",
"getNumStr",
"(",
"num",
",",
"fixed",
"=",
"4",
")",
"{",
"let",
"numStr",
"=",
"''",
";",
"if",
"(",
"typeof",
"num",
"!=",
"\"number\"",
")",
"{",
"num",
"=",
"Number",
"(",
"num",
")",
";",
"if",
"(",
"isNaN",
"(",
"num",
")",
")",
"{",
"// console.log(\"Pushbullet Plugin: Number Conversion Failed\");",
"return",
"\"Conversion Failure\"",
";",
"}",
"}",
"if",
"(",
"Number",
".",
"isInteger",
"(",
"num",
")",
")",
"{",
"numStr",
"=",
"num",
".",
"toString",
"(",
")",
";",
"}",
"else",
"{",
"//Create modNum Max - Must be a better way...",
"let",
"modNumMax",
"=",
"'1'",
";",
"for",
"(",
"let",
"i",
"=",
"1",
";",
"i",
"<",
"fixed",
";",
"i",
"++",
")",
"{",
"modNumMax",
"=",
"modNumMax",
"+",
"'0'",
";",
"}",
"modNumMax",
"=",
"Number",
"(",
"modNumMax",
")",
";",
"let",
"i",
"=",
"0",
";",
"if",
"(",
"num",
"<",
"1",
")",
"{",
"let",
"modNum",
"=",
"num",
"-",
"Math",
".",
"floor",
"(",
"num",
")",
";",
"while",
"(",
"modNum",
"<",
"modNumMax",
"&&",
"i",
"<",
"8",
")",
"{",
"modNum",
"*=",
"10",
";",
"i",
"+=",
"1",
";",
"}",
"}",
"else",
"{",
"i",
"=",
"fixed",
";",
"}",
"numStr",
"=",
"num",
".",
"toFixed",
"(",
"i",
")",
";",
"//Remove any excess zeros",
"while",
"(",
"numStr",
".",
"charAt",
"(",
"numStr",
".",
"length",
"-",
"1",
")",
"===",
"'0'",
")",
"{",
"numStr",
"=",
"numStr",
".",
"substring",
"(",
"0",
",",
"numStr",
".",
"length",
"-",
"1",
")",
";",
"}",
"//If last char remaining is a decimal point, remove it",
"if",
"(",
"numStr",
".",
"charAt",
"(",
"numStr",
".",
"length",
"-",
"1",
")",
"===",
"'.'",
")",
"{",
"numStr",
"=",
"numStr",
".",
"substring",
"(",
"0",
",",
"numStr",
".",
"length",
"-",
"1",
")",
";",
"}",
"}",
"//Add commas for thousands etc",
"let",
"dp",
"=",
"numStr",
".",
"indexOf",
"(",
"'.'",
")",
";",
"//find deciaml point",
"if",
"(",
"dp",
"<",
"0",
")",
"{",
"//no dp found",
"dp",
"=",
"numStr",
".",
"length",
";",
"}",
"let",
"insPos",
"=",
"dp",
"-",
"3",
";",
"insCount",
"=",
"0",
";",
"while",
"(",
"insPos",
">",
"0",
")",
"{",
"insCount",
"++",
";",
"numStr",
"=",
"numStr",
".",
"slice",
"(",
"0",
",",
"insPos",
")",
"+",
"','",
"+",
"numStr",
".",
"slice",
"(",
"insPos",
")",
";",
"insPos",
"-=",
"3",
";",
"}",
"return",
"(",
"numStr",
")",
";",
"}"
] | A long winded function to make sure numbers aren't displayed with too many decimal places and are a little humanized | [
"A",
"long",
"winded",
"function",
"to",
"make",
"sure",
"numbers",
"aren",
"t",
"displayed",
"with",
"too",
"many",
"decimal",
"places",
"and",
"are",
"a",
"little",
"humanized"
] | 0ce9ddd577fa8a22812c02331a494086758dfadf | https://github.com/askmike/gekko/blob/0ce9ddd577fa8a22812c02331a494086758dfadf/plugins/pushbullet.js#L215-L277 |
1,025 | askmike/gekko | web/vue/public/vendor/humanize-duration.js | humanizer | function humanizer (passedOptions) {
var result = function humanizer (ms, humanizerOptions) {
var options = extend({}, result, humanizerOptions || {})
return doHumanization(ms, options)
}
return extend(result, {
language: 'en',
delimiter: ', ',
spacer: ' ',
conjunction: '',
serialComma: true,
units: ['y', 'mo', 'w', 'd', 'h', 'm', 's'],
languages: {},
round: false,
unitMeasures: {
y: 31557600000,
mo: 2629800000,
w: 604800000,
d: 86400000,
h: 3600000,
m: 60000,
s: 1000,
ms: 1
}
}, passedOptions)
} | javascript | function humanizer (passedOptions) {
var result = function humanizer (ms, humanizerOptions) {
var options = extend({}, result, humanizerOptions || {})
return doHumanization(ms, options)
}
return extend(result, {
language: 'en',
delimiter: ', ',
spacer: ' ',
conjunction: '',
serialComma: true,
units: ['y', 'mo', 'w', 'd', 'h', 'm', 's'],
languages: {},
round: false,
unitMeasures: {
y: 31557600000,
mo: 2629800000,
w: 604800000,
d: 86400000,
h: 3600000,
m: 60000,
s: 1000,
ms: 1
}
}, passedOptions)
} | [
"function",
"humanizer",
"(",
"passedOptions",
")",
"{",
"var",
"result",
"=",
"function",
"humanizer",
"(",
"ms",
",",
"humanizerOptions",
")",
"{",
"var",
"options",
"=",
"extend",
"(",
"{",
"}",
",",
"result",
",",
"humanizerOptions",
"||",
"{",
"}",
")",
"return",
"doHumanization",
"(",
"ms",
",",
"options",
")",
"}",
"return",
"extend",
"(",
"result",
",",
"{",
"language",
":",
"'en'",
",",
"delimiter",
":",
"', '",
",",
"spacer",
":",
"' '",
",",
"conjunction",
":",
"''",
",",
"serialComma",
":",
"true",
",",
"units",
":",
"[",
"'y'",
",",
"'mo'",
",",
"'w'",
",",
"'d'",
",",
"'h'",
",",
"'m'",
",",
"'s'",
"]",
",",
"languages",
":",
"{",
"}",
",",
"round",
":",
"false",
",",
"unitMeasures",
":",
"{",
"y",
":",
"31557600000",
",",
"mo",
":",
"2629800000",
",",
"w",
":",
"604800000",
",",
"d",
":",
"86400000",
",",
"h",
":",
"3600000",
",",
"m",
":",
"60000",
",",
"s",
":",
"1000",
",",
"ms",
":",
"1",
"}",
"}",
",",
"passedOptions",
")",
"}"
] | You can create a humanizer, which returns a function with default parameters. | [
"You",
"can",
"create",
"a",
"humanizer",
"which",
"returns",
"a",
"function",
"with",
"default",
"parameters",
"."
] | 0ce9ddd577fa8a22812c02331a494086758dfadf | https://github.com/askmike/gekko/blob/0ce9ddd577fa8a22812c02331a494086758dfadf/web/vue/public/vendor/humanize-duration.js#L20-L46 |
1,026 | askmike/gekko | core/prepareDateRange.js | function(from, to) {
config.backtest.daterange = {
from: moment.unix(from).utc().format(),
to: moment.unix(to).utc().format(),
};
util.setConfig(config);
} | javascript | function(from, to) {
config.backtest.daterange = {
from: moment.unix(from).utc().format(),
to: moment.unix(to).utc().format(),
};
util.setConfig(config);
} | [
"function",
"(",
"from",
",",
"to",
")",
"{",
"config",
".",
"backtest",
".",
"daterange",
"=",
"{",
"from",
":",
"moment",
".",
"unix",
"(",
"from",
")",
".",
"utc",
"(",
")",
".",
"format",
"(",
")",
",",
"to",
":",
"moment",
".",
"unix",
"(",
"to",
")",
".",
"utc",
"(",
")",
".",
"format",
"(",
")",
",",
"}",
";",
"util",
".",
"setConfig",
"(",
"config",
")",
";",
"}"
] | helper to store the evenutally detected daterange. | [
"helper",
"to",
"store",
"the",
"evenutally",
"detected",
"daterange",
"."
] | 0ce9ddd577fa8a22812c02331a494086758dfadf | https://github.com/askmike/gekko/blob/0ce9ddd577fa8a22812c02331a494086758dfadf/core/prepareDateRange.js#L14-L20 |
|
1,027 | askmike/gekko | plugins/postgresql/util.js | function (name) {
if (useSingleDatabase()) {
name = watch.exchange.replace(/\-/g,'') + '_' + name;
}
var fullName = [name, settings.pair.join('_')].join('_');
return useLowerCaseTableNames() ? fullName.toLowerCase() : fullName;
} | javascript | function (name) {
if (useSingleDatabase()) {
name = watch.exchange.replace(/\-/g,'') + '_' + name;
}
var fullName = [name, settings.pair.join('_')].join('_');
return useLowerCaseTableNames() ? fullName.toLowerCase() : fullName;
} | [
"function",
"(",
"name",
")",
"{",
"if",
"(",
"useSingleDatabase",
"(",
")",
")",
"{",
"name",
"=",
"watch",
".",
"exchange",
".",
"replace",
"(",
"/",
"\\-",
"/",
"g",
",",
"''",
")",
"+",
"'_'",
"+",
"name",
";",
"}",
"var",
"fullName",
"=",
"[",
"name",
",",
"settings",
".",
"pair",
".",
"join",
"(",
"'_'",
")",
"]",
".",
"join",
"(",
"'_'",
")",
";",
"return",
"useLowerCaseTableNames",
"(",
")",
"?",
"fullName",
".",
"toLowerCase",
"(",
")",
":",
"fullName",
";",
"}"
] | returns table name which can be different if we use single or multiple db setup. | [
"returns",
"table",
"name",
"which",
"can",
"be",
"different",
"if",
"we",
"use",
"single",
"or",
"multiple",
"db",
"setup",
"."
] | 0ce9ddd577fa8a22812c02331a494086758dfadf | https://github.com/askmike/gekko/blob/0ce9ddd577fa8a22812c02331a494086758dfadf/plugins/postgresql/util.js#L46-L52 |
|
1,028 | graphql/graphql-js | src/jsutils/suggestionList.js | lexicalDistance | function lexicalDistance(aStr, bStr) {
if (aStr === bStr) {
return 0;
}
let i;
let j;
const d = [];
const a = aStr.toLowerCase();
const b = bStr.toLowerCase();
const aLength = a.length;
const bLength = b.length;
// Any case change counts as a single edit
if (a === b) {
return 1;
}
for (i = 0; i <= aLength; i++) {
d[i] = [i];
}
for (j = 1; j <= bLength; j++) {
d[0][j] = j;
}
for (i = 1; i <= aLength; i++) {
for (j = 1; j <= bLength; j++) {
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
d[i][j] = Math.min(
d[i - 1][j] + 1,
d[i][j - 1] + 1,
d[i - 1][j - 1] + cost,
);
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost);
}
}
}
return d[aLength][bLength];
} | javascript | function lexicalDistance(aStr, bStr) {
if (aStr === bStr) {
return 0;
}
let i;
let j;
const d = [];
const a = aStr.toLowerCase();
const b = bStr.toLowerCase();
const aLength = a.length;
const bLength = b.length;
// Any case change counts as a single edit
if (a === b) {
return 1;
}
for (i = 0; i <= aLength; i++) {
d[i] = [i];
}
for (j = 1; j <= bLength; j++) {
d[0][j] = j;
}
for (i = 1; i <= aLength; i++) {
for (j = 1; j <= bLength; j++) {
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
d[i][j] = Math.min(
d[i - 1][j] + 1,
d[i][j - 1] + 1,
d[i - 1][j - 1] + cost,
);
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost);
}
}
}
return d[aLength][bLength];
} | [
"function",
"lexicalDistance",
"(",
"aStr",
",",
"bStr",
")",
"{",
"if",
"(",
"aStr",
"===",
"bStr",
")",
"{",
"return",
"0",
";",
"}",
"let",
"i",
";",
"let",
"j",
";",
"const",
"d",
"=",
"[",
"]",
";",
"const",
"a",
"=",
"aStr",
".",
"toLowerCase",
"(",
")",
";",
"const",
"b",
"=",
"bStr",
".",
"toLowerCase",
"(",
")",
";",
"const",
"aLength",
"=",
"a",
".",
"length",
";",
"const",
"bLength",
"=",
"b",
".",
"length",
";",
"// Any case change counts as a single edit",
"if",
"(",
"a",
"===",
"b",
")",
"{",
"return",
"1",
";",
"}",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<=",
"aLength",
";",
"i",
"++",
")",
"{",
"d",
"[",
"i",
"]",
"=",
"[",
"i",
"]",
";",
"}",
"for",
"(",
"j",
"=",
"1",
";",
"j",
"<=",
"bLength",
";",
"j",
"++",
")",
"{",
"d",
"[",
"0",
"]",
"[",
"j",
"]",
"=",
"j",
";",
"}",
"for",
"(",
"i",
"=",
"1",
";",
"i",
"<=",
"aLength",
";",
"i",
"++",
")",
"{",
"for",
"(",
"j",
"=",
"1",
";",
"j",
"<=",
"bLength",
";",
"j",
"++",
")",
"{",
"const",
"cost",
"=",
"a",
"[",
"i",
"-",
"1",
"]",
"===",
"b",
"[",
"j",
"-",
"1",
"]",
"?",
"0",
":",
"1",
";",
"d",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"Math",
".",
"min",
"(",
"d",
"[",
"i",
"-",
"1",
"]",
"[",
"j",
"]",
"+",
"1",
",",
"d",
"[",
"i",
"]",
"[",
"j",
"-",
"1",
"]",
"+",
"1",
",",
"d",
"[",
"i",
"-",
"1",
"]",
"[",
"j",
"-",
"1",
"]",
"+",
"cost",
",",
")",
";",
"if",
"(",
"i",
">",
"1",
"&&",
"j",
">",
"1",
"&&",
"a",
"[",
"i",
"-",
"1",
"]",
"===",
"b",
"[",
"j",
"-",
"2",
"]",
"&&",
"a",
"[",
"i",
"-",
"2",
"]",
"===",
"b",
"[",
"j",
"-",
"1",
"]",
")",
"{",
"d",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"Math",
".",
"min",
"(",
"d",
"[",
"i",
"]",
"[",
"j",
"]",
",",
"d",
"[",
"i",
"-",
"2",
"]",
"[",
"j",
"-",
"2",
"]",
"+",
"cost",
")",
";",
"}",
"}",
"}",
"return",
"d",
"[",
"aLength",
"]",
"[",
"bLength",
"]",
";",
"}"
] | Computes the lexical distance between strings A and B.
The "distance" between two strings is given by counting the minimum number
of edits needed to transform string A into string B. An edit can be an
insertion, deletion, or substitution of a single character, or a swap of two
adjacent characters.
Includes a custom alteration from Damerau-Levenshtein to treat case changes
as a single edit which helps identify mis-cased values with an edit distance
of 1.
This distance can be useful for detecting typos in input or sorting
@param {string} a
@param {string} b
@return {int} distance in number of edits | [
"Computes",
"the",
"lexical",
"distance",
"between",
"strings",
"A",
"and",
"B",
"."
] | b65ff6db8893c1c68f0f236c4b2d663e6c55f5ef | https://github.com/graphql/graphql-js/blob/b65ff6db8893c1c68f0f236c4b2d663e6c55f5ef/src/jsutils/suggestionList.js#L51-L94 |
1,029 | graphql/graphql-js | resources/benchmark.js | hashForRevision | function hashForRevision(revision) {
const out = execSync(`git rev-parse "${revision}"`, { encoding: 'utf8' });
const match = /[0-9a-f]{8,40}/.exec(out);
if (!match) {
throw new Error(`Bad results for revision ${revision}: ${out}`);
}
return match[0];
} | javascript | function hashForRevision(revision) {
const out = execSync(`git rev-parse "${revision}"`, { encoding: 'utf8' });
const match = /[0-9a-f]{8,40}/.exec(out);
if (!match) {
throw new Error(`Bad results for revision ${revision}: ${out}`);
}
return match[0];
} | [
"function",
"hashForRevision",
"(",
"revision",
")",
"{",
"const",
"out",
"=",
"execSync",
"(",
"`",
"${",
"revision",
"}",
"`",
",",
"{",
"encoding",
":",
"'utf8'",
"}",
")",
";",
"const",
"match",
"=",
"/",
"[0-9a-f]{8,40}",
"/",
".",
"exec",
"(",
"out",
")",
";",
"if",
"(",
"!",
"match",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"revision",
"}",
"${",
"out",
"}",
"`",
")",
";",
"}",
"return",
"match",
"[",
"0",
"]",
";",
"}"
] | Returns the complete git hash for a given git revision reference. | [
"Returns",
"the",
"complete",
"git",
"hash",
"for",
"a",
"given",
"git",
"revision",
"reference",
"."
] | b65ff6db8893c1c68f0f236c4b2d663e6c55f5ef | https://github.com/graphql/graphql-js/blob/b65ff6db8893c1c68f0f236c4b2d663e6c55f5ef/resources/benchmark.js#L37-L44 |
1,030 | graphql/graphql-js | resources/benchmark.js | prepareAndRunBenchmarks | function prepareAndRunBenchmarks(benchmarkPatterns, revisions) {
// Find all benchmark tests to be run.
let benchmarks = findFiles(LOCAL_DIR('src'), '*/__tests__/*-benchmark.js');
if (benchmarkPatterns.length !== 0) {
benchmarks = benchmarks.filter(benchmark =>
benchmarkPatterns.some(pattern =>
path.join('src', benchmark).includes(pattern)
)
);
}
if (benchmarks.length === 0) {
console.warn(
'No benchmarks matching: ' +
`\u001b[1m${benchmarkPatterns.join('\u001b[0m or \u001b[1m')}\u001b[0m`
);
return;
}
const environments = revisions.map(revision => ({
revision,
distPath: prepareRevision(revision),
}));
benchmarks.forEach(benchmark => runBenchmark(benchmark, environments));
} | javascript | function prepareAndRunBenchmarks(benchmarkPatterns, revisions) {
// Find all benchmark tests to be run.
let benchmarks = findFiles(LOCAL_DIR('src'), '*/__tests__/*-benchmark.js');
if (benchmarkPatterns.length !== 0) {
benchmarks = benchmarks.filter(benchmark =>
benchmarkPatterns.some(pattern =>
path.join('src', benchmark).includes(pattern)
)
);
}
if (benchmarks.length === 0) {
console.warn(
'No benchmarks matching: ' +
`\u001b[1m${benchmarkPatterns.join('\u001b[0m or \u001b[1m')}\u001b[0m`
);
return;
}
const environments = revisions.map(revision => ({
revision,
distPath: prepareRevision(revision),
}));
benchmarks.forEach(benchmark => runBenchmark(benchmark, environments));
} | [
"function",
"prepareAndRunBenchmarks",
"(",
"benchmarkPatterns",
",",
"revisions",
")",
"{",
"// Find all benchmark tests to be run.",
"let",
"benchmarks",
"=",
"findFiles",
"(",
"LOCAL_DIR",
"(",
"'src'",
")",
",",
"'*/__tests__/*-benchmark.js'",
")",
";",
"if",
"(",
"benchmarkPatterns",
".",
"length",
"!==",
"0",
")",
"{",
"benchmarks",
"=",
"benchmarks",
".",
"filter",
"(",
"benchmark",
"=>",
"benchmarkPatterns",
".",
"some",
"(",
"pattern",
"=>",
"path",
".",
"join",
"(",
"'src'",
",",
"benchmark",
")",
".",
"includes",
"(",
"pattern",
")",
")",
")",
";",
"}",
"if",
"(",
"benchmarks",
".",
"length",
"===",
"0",
")",
"{",
"console",
".",
"warn",
"(",
"'No benchmarks matching: '",
"+",
"`",
"\\u001b",
"${",
"benchmarkPatterns",
".",
"join",
"(",
"'\\u001b[0m or \\u001b[1m'",
")",
"}",
"\\u001b",
"`",
")",
";",
"return",
";",
"}",
"const",
"environments",
"=",
"revisions",
".",
"map",
"(",
"revision",
"=>",
"(",
"{",
"revision",
",",
"distPath",
":",
"prepareRevision",
"(",
"revision",
")",
",",
"}",
")",
")",
";",
"benchmarks",
".",
"forEach",
"(",
"benchmark",
"=>",
"runBenchmark",
"(",
"benchmark",
",",
"environments",
")",
")",
";",
"}"
] | Prepare all revisions and run benchmarks matching a pattern against them. | [
"Prepare",
"all",
"revisions",
"and",
"run",
"benchmarks",
"matching",
"a",
"pattern",
"against",
"them",
"."
] | b65ff6db8893c1c68f0f236c4b2d663e6c55f5ef | https://github.com/graphql/graphql-js/blob/b65ff6db8893c1c68f0f236c4b2d663e6c55f5ef/resources/benchmark.js#L187-L211 |
1,031 | GitbookIO/gitbook | lib/modifiers/summary/moveArticle.js | moveArticle | function moveArticle(summary, origin, target) {
// Coerce to level
var originLevel = is.string(origin)? origin : origin.getLevel();
var targetLevel = is.string(target)? target : target.getLevel();
var article = summary.getByLevel(originLevel);
// Remove first
var removed = removeArticle(summary, originLevel);
return insertArticle(removed, article, targetLevel);
} | javascript | function moveArticle(summary, origin, target) {
// Coerce to level
var originLevel = is.string(origin)? origin : origin.getLevel();
var targetLevel = is.string(target)? target : target.getLevel();
var article = summary.getByLevel(originLevel);
// Remove first
var removed = removeArticle(summary, originLevel);
return insertArticle(removed, article, targetLevel);
} | [
"function",
"moveArticle",
"(",
"summary",
",",
"origin",
",",
"target",
")",
"{",
"// Coerce to level",
"var",
"originLevel",
"=",
"is",
".",
"string",
"(",
"origin",
")",
"?",
"origin",
":",
"origin",
".",
"getLevel",
"(",
")",
";",
"var",
"targetLevel",
"=",
"is",
".",
"string",
"(",
"target",
")",
"?",
"target",
":",
"target",
".",
"getLevel",
"(",
")",
";",
"var",
"article",
"=",
"summary",
".",
"getByLevel",
"(",
"originLevel",
")",
";",
"// Remove first",
"var",
"removed",
"=",
"removeArticle",
"(",
"summary",
",",
"originLevel",
")",
";",
"return",
"insertArticle",
"(",
"removed",
",",
"article",
",",
"targetLevel",
")",
";",
"}"
] | Returns a new summary, with the given article removed from its
origin level, and placed at the given target level.
@param {Summary} summary
@param {String|SummaryArticle} origin: level to remove
@param {String|SummaryArticle} target: the level where the article will be found
@return {Summary} | [
"Returns",
"a",
"new",
"summary",
"with",
"the",
"given",
"article",
"removed",
"from",
"its",
"origin",
"level",
"and",
"placed",
"at",
"the",
"given",
"target",
"level",
"."
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/modifiers/summary/moveArticle.js#L14-L23 |
1,032 | GitbookIO/gitbook | lib/modifiers/config/hasPlugin.js | hasPlugin | function hasPlugin(deps, pluginName, version) {
return !!deps.find(function(dep) {
return dep.getName() === pluginName && (!version || dep.getVersion() === version);
});
} | javascript | function hasPlugin(deps, pluginName, version) {
return !!deps.find(function(dep) {
return dep.getName() === pluginName && (!version || dep.getVersion() === version);
});
} | [
"function",
"hasPlugin",
"(",
"deps",
",",
"pluginName",
",",
"version",
")",
"{",
"return",
"!",
"!",
"deps",
".",
"find",
"(",
"function",
"(",
"dep",
")",
"{",
"return",
"dep",
".",
"getName",
"(",
")",
"===",
"pluginName",
"&&",
"(",
"!",
"version",
"||",
"dep",
".",
"getVersion",
"(",
")",
"===",
"version",
")",
";",
"}",
")",
";",
"}"
] | Test if a plugin is listed
@param { {List<PluginDependency}} deps
@param {String} plugin
@param {String} version
@return {Boolean} | [
"Test",
"if",
"a",
"plugin",
"is",
"listed"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/modifiers/config/hasPlugin.js#L9-L13 |
1,033 | GitbookIO/gitbook | lib/output/ebook/onPage.js | onPage | function onPage(output, page) {
var options = output.getOptions();
// Inline assets
return Modifiers.modifyHTML(page, [
Modifiers.inlineAssets(options.get('root'), page.getFile().getPath())
])
// Write page using website generator
.then(function(resultPage) {
return WebsiteGenerator.onPage(output, resultPage);
});
} | javascript | function onPage(output, page) {
var options = output.getOptions();
// Inline assets
return Modifiers.modifyHTML(page, [
Modifiers.inlineAssets(options.get('root'), page.getFile().getPath())
])
// Write page using website generator
.then(function(resultPage) {
return WebsiteGenerator.onPage(output, resultPage);
});
} | [
"function",
"onPage",
"(",
"output",
",",
"page",
")",
"{",
"var",
"options",
"=",
"output",
".",
"getOptions",
"(",
")",
";",
"// Inline assets",
"return",
"Modifiers",
".",
"modifyHTML",
"(",
"page",
",",
"[",
"Modifiers",
".",
"inlineAssets",
"(",
"options",
".",
"get",
"(",
"'root'",
")",
",",
"page",
".",
"getFile",
"(",
")",
".",
"getPath",
"(",
")",
")",
"]",
")",
"// Write page using website generator",
".",
"then",
"(",
"function",
"(",
"resultPage",
")",
"{",
"return",
"WebsiteGenerator",
".",
"onPage",
"(",
"output",
",",
"resultPage",
")",
";",
"}",
")",
";",
"}"
] | Write a page for ebook output
@param {Output} output
@param {Output} | [
"Write",
"a",
"page",
"for",
"ebook",
"output"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/ebook/onPage.js#L10-L22 |
1,034 | GitbookIO/gitbook | lib/plugins/sortDependencies.js | pluginType | function pluginType(plugin) {
var name = plugin.getName();
return (name && name.indexOf(THEME_PREFIX) === 0) ? TYPE_THEME : TYPE_PLUGIN;
} | javascript | function pluginType(plugin) {
var name = plugin.getName();
return (name && name.indexOf(THEME_PREFIX) === 0) ? TYPE_THEME : TYPE_PLUGIN;
} | [
"function",
"pluginType",
"(",
"plugin",
")",
"{",
"var",
"name",
"=",
"plugin",
".",
"getName",
"(",
")",
";",
"return",
"(",
"name",
"&&",
"name",
".",
"indexOf",
"(",
"THEME_PREFIX",
")",
"===",
"0",
")",
"?",
"TYPE_THEME",
":",
"TYPE_PLUGIN",
";",
"}"
] | Returns the type of a plugin given its name
@param {Plugin} plugin
@return {String} | [
"Returns",
"the",
"type",
"of",
"a",
"plugin",
"given",
"its",
"name"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/plugins/sortDependencies.js#L14-L17 |
1,035 | GitbookIO/gitbook | lib/plugins/sortDependencies.js | sortDependencies | function sortDependencies(plugins) {
var byTypes = plugins.groupBy(pluginType);
return byTypes.get(TYPE_PLUGIN, Immutable.List())
.concat(byTypes.get(TYPE_THEME, Immutable.List()));
} | javascript | function sortDependencies(plugins) {
var byTypes = plugins.groupBy(pluginType);
return byTypes.get(TYPE_PLUGIN, Immutable.List())
.concat(byTypes.get(TYPE_THEME, Immutable.List()));
} | [
"function",
"sortDependencies",
"(",
"plugins",
")",
"{",
"var",
"byTypes",
"=",
"plugins",
".",
"groupBy",
"(",
"pluginType",
")",
";",
"return",
"byTypes",
".",
"get",
"(",
"TYPE_PLUGIN",
",",
"Immutable",
".",
"List",
"(",
")",
")",
".",
"concat",
"(",
"byTypes",
".",
"get",
"(",
"TYPE_THEME",
",",
"Immutable",
".",
"List",
"(",
")",
")",
")",
";",
"}"
] | Sort the list of dependencies to match list in book.json
The themes should always be loaded after the plugins
@param {List<PluginDependency>} deps
@return {List<PluginDependency>} | [
"Sort",
"the",
"list",
"of",
"dependencies",
"to",
"match",
"list",
"in",
"book",
".",
"json",
"The",
"themes",
"should",
"always",
"be",
"loaded",
"after",
"the",
"plugins"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/plugins/sortDependencies.js#L27-L32 |
1,036 | GitbookIO/gitbook | lib/plugins/listDependencies.js | listDependencies | function listDependencies(deps) {
// Extract list of plugins to disable (starting with -)
var toRemove = deps
.filter(function(plugin) {
return !plugin.isEnabled();
})
.map(function(plugin) {
return plugin.getName();
});
// Concat with default plugins
deps = deps.concat(DEFAULT_PLUGINS);
// Remove plugins
deps = deps.filterNot(function(plugin) {
return toRemove.includes(plugin.getName());
});
// Sort
return sortDependencies(deps);
} | javascript | function listDependencies(deps) {
// Extract list of plugins to disable (starting with -)
var toRemove = deps
.filter(function(plugin) {
return !plugin.isEnabled();
})
.map(function(plugin) {
return plugin.getName();
});
// Concat with default plugins
deps = deps.concat(DEFAULT_PLUGINS);
// Remove plugins
deps = deps.filterNot(function(plugin) {
return toRemove.includes(plugin.getName());
});
// Sort
return sortDependencies(deps);
} | [
"function",
"listDependencies",
"(",
"deps",
")",
"{",
"// Extract list of plugins to disable (starting with -)",
"var",
"toRemove",
"=",
"deps",
".",
"filter",
"(",
"function",
"(",
"plugin",
")",
"{",
"return",
"!",
"plugin",
".",
"isEnabled",
"(",
")",
";",
"}",
")",
".",
"map",
"(",
"function",
"(",
"plugin",
")",
"{",
"return",
"plugin",
".",
"getName",
"(",
")",
";",
"}",
")",
";",
"// Concat with default plugins",
"deps",
"=",
"deps",
".",
"concat",
"(",
"DEFAULT_PLUGINS",
")",
";",
"// Remove plugins",
"deps",
"=",
"deps",
".",
"filterNot",
"(",
"function",
"(",
"plugin",
")",
"{",
"return",
"toRemove",
".",
"includes",
"(",
"plugin",
".",
"getName",
"(",
")",
")",
";",
"}",
")",
";",
"// Sort",
"return",
"sortDependencies",
"(",
"deps",
")",
";",
"}"
] | List all dependencies for a book, including default plugins.
It returns a concat with default plugins and remove disabled ones.
@param {List<PluginDependency>} deps
@return {List<PluginDependency>} | [
"List",
"all",
"dependencies",
"for",
"a",
"book",
"including",
"default",
"plugins",
".",
"It",
"returns",
"a",
"concat",
"with",
"default",
"plugins",
"and",
"remove",
"disabled",
"ones",
"."
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/plugins/listDependencies.js#L11-L31 |
1,037 | GitbookIO/gitbook | lib/output/ebook/onFinish.js | writeSummary | function writeSummary(output) {
var options = output.getOptions();
var prefix = options.get('prefix');
var filePath = SUMMARY_FILE;
var engine = WebsiteGenerator.createTemplateEngine(output, filePath);
var context = JSONUtils.encodeOutput(output);
// Render the theme
return Templating.renderFile(engine, prefix + '/summary.html', context)
// Write it to the disk
.then(function(tplOut) {
return writeFile(output, filePath, tplOut.getContent());
});
} | javascript | function writeSummary(output) {
var options = output.getOptions();
var prefix = options.get('prefix');
var filePath = SUMMARY_FILE;
var engine = WebsiteGenerator.createTemplateEngine(output, filePath);
var context = JSONUtils.encodeOutput(output);
// Render the theme
return Templating.renderFile(engine, prefix + '/summary.html', context)
// Write it to the disk
.then(function(tplOut) {
return writeFile(output, filePath, tplOut.getContent());
});
} | [
"function",
"writeSummary",
"(",
"output",
")",
"{",
"var",
"options",
"=",
"output",
".",
"getOptions",
"(",
")",
";",
"var",
"prefix",
"=",
"options",
".",
"get",
"(",
"'prefix'",
")",
";",
"var",
"filePath",
"=",
"SUMMARY_FILE",
";",
"var",
"engine",
"=",
"WebsiteGenerator",
".",
"createTemplateEngine",
"(",
"output",
",",
"filePath",
")",
";",
"var",
"context",
"=",
"JSONUtils",
".",
"encodeOutput",
"(",
"output",
")",
";",
"// Render the theme",
"return",
"Templating",
".",
"renderFile",
"(",
"engine",
",",
"prefix",
"+",
"'/summary.html'",
",",
"context",
")",
"// Write it to the disk",
".",
"then",
"(",
"function",
"(",
"tplOut",
")",
"{",
"return",
"writeFile",
"(",
"output",
",",
"filePath",
",",
"tplOut",
".",
"getContent",
"(",
")",
")",
";",
"}",
")",
";",
"}"
] | Write the SUMMARY.html
@param {Output}
@return {Output} | [
"Write",
"the",
"SUMMARY",
".",
"html"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/ebook/onFinish.js#L20-L35 |
1,038 | GitbookIO/gitbook | lib/output/ebook/onFinish.js | runEbookConvert | function runEbookConvert(output) {
var logger = output.getLogger();
var options = output.getOptions();
var format = options.get('format');
var outputFolder = output.getRoot();
if (!format) {
return Promise(output);
}
return getConvertOptions(output)
.then(function(options) {
var cmd = [
'ebook-convert',
path.resolve(outputFolder, SUMMARY_FILE),
path.resolve(outputFolder, 'index.' + format),
command.optionsToShellArgs(options)
].join(' ');
return command.exec(cmd)
.progress(function(data) {
logger.debug(data);
})
.fail(function(err) {
if (err.code == 127) {
throw error.RequireInstallError({
cmd: 'ebook-convert',
install: 'Install it from Calibre: https://calibre-ebook.com'
});
}
throw error.EbookError(err);
});
})
.thenResolve(output);
} | javascript | function runEbookConvert(output) {
var logger = output.getLogger();
var options = output.getOptions();
var format = options.get('format');
var outputFolder = output.getRoot();
if (!format) {
return Promise(output);
}
return getConvertOptions(output)
.then(function(options) {
var cmd = [
'ebook-convert',
path.resolve(outputFolder, SUMMARY_FILE),
path.resolve(outputFolder, 'index.' + format),
command.optionsToShellArgs(options)
].join(' ');
return command.exec(cmd)
.progress(function(data) {
logger.debug(data);
})
.fail(function(err) {
if (err.code == 127) {
throw error.RequireInstallError({
cmd: 'ebook-convert',
install: 'Install it from Calibre: https://calibre-ebook.com'
});
}
throw error.EbookError(err);
});
})
.thenResolve(output);
} | [
"function",
"runEbookConvert",
"(",
"output",
")",
"{",
"var",
"logger",
"=",
"output",
".",
"getLogger",
"(",
")",
";",
"var",
"options",
"=",
"output",
".",
"getOptions",
"(",
")",
";",
"var",
"format",
"=",
"options",
".",
"get",
"(",
"'format'",
")",
";",
"var",
"outputFolder",
"=",
"output",
".",
"getRoot",
"(",
")",
";",
"if",
"(",
"!",
"format",
")",
"{",
"return",
"Promise",
"(",
"output",
")",
";",
"}",
"return",
"getConvertOptions",
"(",
"output",
")",
".",
"then",
"(",
"function",
"(",
"options",
")",
"{",
"var",
"cmd",
"=",
"[",
"'ebook-convert'",
",",
"path",
".",
"resolve",
"(",
"outputFolder",
",",
"SUMMARY_FILE",
")",
",",
"path",
".",
"resolve",
"(",
"outputFolder",
",",
"'index.'",
"+",
"format",
")",
",",
"command",
".",
"optionsToShellArgs",
"(",
"options",
")",
"]",
".",
"join",
"(",
"' '",
")",
";",
"return",
"command",
".",
"exec",
"(",
"cmd",
")",
".",
"progress",
"(",
"function",
"(",
"data",
")",
"{",
"logger",
".",
"debug",
"(",
"data",
")",
";",
"}",
")",
".",
"fail",
"(",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
".",
"code",
"==",
"127",
")",
"{",
"throw",
"error",
".",
"RequireInstallError",
"(",
"{",
"cmd",
":",
"'ebook-convert'",
",",
"install",
":",
"'Install it from Calibre: https://calibre-ebook.com'",
"}",
")",
";",
"}",
"throw",
"error",
".",
"EbookError",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
")",
".",
"thenResolve",
"(",
"output",
")",
";",
"}"
] | Generate the ebook file as "index.pdf"
@param {Output}
@return {Output} | [
"Generate",
"the",
"ebook",
"file",
"as",
"index",
".",
"pdf"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/ebook/onFinish.js#L43-L78 |
1,039 | GitbookIO/gitbook | lib/plugins/validatePlugin.js | validatePlugin | function validatePlugin(plugin) {
var packageInfos = plugin.getPackage();
var isValid = (
plugin.isLoaded() &&
packageInfos &&
packageInfos.get('name') &&
packageInfos.get('engines') &&
packageInfos.get('engines').get('gitbook')
);
if (!isValid) {
return Promise.reject(new Error('Error loading plugin "' + plugin.getName() + '" at "' + plugin.getPath() + '"'));
}
var engine = packageInfos.get('engines').get('gitbook');
if (!gitbook.satisfies(engine)) {
return Promise.reject(new Error('GitBook doesn\'t satisfy the requirements of this plugin: ' + engine));
}
return Promise(plugin);
} | javascript | function validatePlugin(plugin) {
var packageInfos = plugin.getPackage();
var isValid = (
plugin.isLoaded() &&
packageInfos &&
packageInfos.get('name') &&
packageInfos.get('engines') &&
packageInfos.get('engines').get('gitbook')
);
if (!isValid) {
return Promise.reject(new Error('Error loading plugin "' + plugin.getName() + '" at "' + plugin.getPath() + '"'));
}
var engine = packageInfos.get('engines').get('gitbook');
if (!gitbook.satisfies(engine)) {
return Promise.reject(new Error('GitBook doesn\'t satisfy the requirements of this plugin: ' + engine));
}
return Promise(plugin);
} | [
"function",
"validatePlugin",
"(",
"plugin",
")",
"{",
"var",
"packageInfos",
"=",
"plugin",
".",
"getPackage",
"(",
")",
";",
"var",
"isValid",
"=",
"(",
"plugin",
".",
"isLoaded",
"(",
")",
"&&",
"packageInfos",
"&&",
"packageInfos",
".",
"get",
"(",
"'name'",
")",
"&&",
"packageInfos",
".",
"get",
"(",
"'engines'",
")",
"&&",
"packageInfos",
".",
"get",
"(",
"'engines'",
")",
".",
"get",
"(",
"'gitbook'",
")",
")",
";",
"if",
"(",
"!",
"isValid",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"Error",
"(",
"'Error loading plugin \"'",
"+",
"plugin",
".",
"getName",
"(",
")",
"+",
"'\" at \"'",
"+",
"plugin",
".",
"getPath",
"(",
")",
"+",
"'\"'",
")",
")",
";",
"}",
"var",
"engine",
"=",
"packageInfos",
".",
"get",
"(",
"'engines'",
")",
".",
"get",
"(",
"'gitbook'",
")",
";",
"if",
"(",
"!",
"gitbook",
".",
"satisfies",
"(",
"engine",
")",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"Error",
"(",
"'GitBook doesn\\'t satisfy the requirements of this plugin: '",
"+",
"engine",
")",
")",
";",
"}",
"return",
"Promise",
"(",
"plugin",
")",
";",
"}"
] | Validate a plugin
@param {Plugin}
@return {Promise<Plugin>} | [
"Validate",
"a",
"plugin"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/plugins/validatePlugin.js#L11-L32 |
1,040 | GitbookIO/gitbook | lib/templating/replaceShortcuts.js | applyShortcut | function applyShortcut(content, shortcut) {
var start = shortcut.getStart();
var end = shortcut.getEnd();
var tagStart = shortcut.getStartTag();
var tagEnd = shortcut.getEndTag();
var regex = new RegExp(
escapeStringRegexp(start) + '([\\s\\S]*?[^\\$])' + escapeStringRegexp(end),
'g'
);
return content.replace(regex, function(all, match) {
return '{% ' + tagStart + ' %}' + match + '{% ' + tagEnd + ' %}';
});
} | javascript | function applyShortcut(content, shortcut) {
var start = shortcut.getStart();
var end = shortcut.getEnd();
var tagStart = shortcut.getStartTag();
var tagEnd = shortcut.getEndTag();
var regex = new RegExp(
escapeStringRegexp(start) + '([\\s\\S]*?[^\\$])' + escapeStringRegexp(end),
'g'
);
return content.replace(regex, function(all, match) {
return '{% ' + tagStart + ' %}' + match + '{% ' + tagEnd + ' %}';
});
} | [
"function",
"applyShortcut",
"(",
"content",
",",
"shortcut",
")",
"{",
"var",
"start",
"=",
"shortcut",
".",
"getStart",
"(",
")",
";",
"var",
"end",
"=",
"shortcut",
".",
"getEnd",
"(",
")",
";",
"var",
"tagStart",
"=",
"shortcut",
".",
"getStartTag",
"(",
")",
";",
"var",
"tagEnd",
"=",
"shortcut",
".",
"getEndTag",
"(",
")",
";",
"var",
"regex",
"=",
"new",
"RegExp",
"(",
"escapeStringRegexp",
"(",
"start",
")",
"+",
"'([\\\\s\\\\S]*?[^\\\\$])'",
"+",
"escapeStringRegexp",
"(",
"end",
")",
",",
"'g'",
")",
";",
"return",
"content",
".",
"replace",
"(",
"regex",
",",
"function",
"(",
"all",
",",
"match",
")",
"{",
"return",
"'{% '",
"+",
"tagStart",
"+",
"' %}'",
"+",
"match",
"+",
"'{% '",
"+",
"tagEnd",
"+",
"' %}'",
";",
"}",
")",
";",
"}"
] | Apply a shortcut of block to a template
@param {String} content
@param {Shortcut} shortcut
@return {String} | [
"Apply",
"a",
"shortcut",
"of",
"block",
"to",
"a",
"template"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/templating/replaceShortcuts.js#L10-L24 |
1,041 | GitbookIO/gitbook | lib/templating/replaceShortcuts.js | replaceShortcuts | function replaceShortcuts(blocks, filePath, content) {
var shortcuts = listShortcuts(blocks, filePath);
return shortcuts.reduce(applyShortcut, content);
} | javascript | function replaceShortcuts(blocks, filePath, content) {
var shortcuts = listShortcuts(blocks, filePath);
return shortcuts.reduce(applyShortcut, content);
} | [
"function",
"replaceShortcuts",
"(",
"blocks",
",",
"filePath",
",",
"content",
")",
"{",
"var",
"shortcuts",
"=",
"listShortcuts",
"(",
"blocks",
",",
"filePath",
")",
";",
"return",
"shortcuts",
".",
"reduce",
"(",
"applyShortcut",
",",
"content",
")",
";",
"}"
] | Replace shortcuts from blocks in a string
@param {List<TemplateBlock>} engine
@param {String} filePath
@param {String} content
@return {String} | [
"Replace",
"shortcuts",
"from",
"blocks",
"in",
"a",
"string"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/templating/replaceShortcuts.js#L34-L37 |
1,042 | GitbookIO/gitbook | lib/plugins/validateConfig.js | validatePluginConfig | function validatePluginConfig(book, plugin) {
var config = book.getConfig();
var packageInfos = plugin.getPackage();
var configKey = [
'pluginsConfig',
plugin.getName()
].join('.');
var pluginConfig = config.getValue(configKey, {}).toJS();
var schema = (packageInfos.get('gitbook') || Immutable.Map()).toJS();
if (!schema) return book;
// Normalize schema
schema.id = '/' + configKey;
schema.type = 'object';
// Validate and throw if invalid
var v = new jsonschema.Validator();
var result = v.validate(pluginConfig, schema, {
propertyName: configKey
});
// Throw error
if (result.errors.length > 0) {
throw new error.ConfigurationError(new Error(result.errors[0].stack));
}
// Insert default values
var defaults = jsonSchemaDefaults(schema);
pluginConfig = mergeDefaults(pluginConfig, defaults);
// Update configuration
config = config.setValue(configKey, pluginConfig);
// Return new book
return book.set('config', config);
} | javascript | function validatePluginConfig(book, plugin) {
var config = book.getConfig();
var packageInfos = plugin.getPackage();
var configKey = [
'pluginsConfig',
plugin.getName()
].join('.');
var pluginConfig = config.getValue(configKey, {}).toJS();
var schema = (packageInfos.get('gitbook') || Immutable.Map()).toJS();
if (!schema) return book;
// Normalize schema
schema.id = '/' + configKey;
schema.type = 'object';
// Validate and throw if invalid
var v = new jsonschema.Validator();
var result = v.validate(pluginConfig, schema, {
propertyName: configKey
});
// Throw error
if (result.errors.length > 0) {
throw new error.ConfigurationError(new Error(result.errors[0].stack));
}
// Insert default values
var defaults = jsonSchemaDefaults(schema);
pluginConfig = mergeDefaults(pluginConfig, defaults);
// Update configuration
config = config.setValue(configKey, pluginConfig);
// Return new book
return book.set('config', config);
} | [
"function",
"validatePluginConfig",
"(",
"book",
",",
"plugin",
")",
"{",
"var",
"config",
"=",
"book",
".",
"getConfig",
"(",
")",
";",
"var",
"packageInfos",
"=",
"plugin",
".",
"getPackage",
"(",
")",
";",
"var",
"configKey",
"=",
"[",
"'pluginsConfig'",
",",
"plugin",
".",
"getName",
"(",
")",
"]",
".",
"join",
"(",
"'.'",
")",
";",
"var",
"pluginConfig",
"=",
"config",
".",
"getValue",
"(",
"configKey",
",",
"{",
"}",
")",
".",
"toJS",
"(",
")",
";",
"var",
"schema",
"=",
"(",
"packageInfos",
".",
"get",
"(",
"'gitbook'",
")",
"||",
"Immutable",
".",
"Map",
"(",
")",
")",
".",
"toJS",
"(",
")",
";",
"if",
"(",
"!",
"schema",
")",
"return",
"book",
";",
"// Normalize schema",
"schema",
".",
"id",
"=",
"'/'",
"+",
"configKey",
";",
"schema",
".",
"type",
"=",
"'object'",
";",
"// Validate and throw if invalid",
"var",
"v",
"=",
"new",
"jsonschema",
".",
"Validator",
"(",
")",
";",
"var",
"result",
"=",
"v",
".",
"validate",
"(",
"pluginConfig",
",",
"schema",
",",
"{",
"propertyName",
":",
"configKey",
"}",
")",
";",
"// Throw error",
"if",
"(",
"result",
".",
"errors",
".",
"length",
">",
"0",
")",
"{",
"throw",
"new",
"error",
".",
"ConfigurationError",
"(",
"new",
"Error",
"(",
"result",
".",
"errors",
"[",
"0",
"]",
".",
"stack",
")",
")",
";",
"}",
"// Insert default values",
"var",
"defaults",
"=",
"jsonSchemaDefaults",
"(",
"schema",
")",
";",
"pluginConfig",
"=",
"mergeDefaults",
"(",
"pluginConfig",
",",
"defaults",
")",
";",
"// Update configuration",
"config",
"=",
"config",
".",
"setValue",
"(",
"configKey",
",",
"pluginConfig",
")",
";",
"// Return new book",
"return",
"book",
".",
"set",
"(",
"'config'",
",",
"config",
")",
";",
"}"
] | Validate one plugin for a book and update book's confiration
@param {Book}
@param {Plugin}
@return {Book} | [
"Validate",
"one",
"plugin",
"for",
"a",
"book",
"and",
"update",
"book",
"s",
"confiration"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/plugins/validateConfig.js#L16-L55 |
1,043 | GitbookIO/gitbook | lib/plugins/validateConfig.js | validateConfig | function validateConfig(book, plugins) {
return Promise.reduce(plugins, function(newBook, plugin) {
return validatePluginConfig(newBook, plugin);
}, book);
} | javascript | function validateConfig(book, plugins) {
return Promise.reduce(plugins, function(newBook, plugin) {
return validatePluginConfig(newBook, plugin);
}, book);
} | [
"function",
"validateConfig",
"(",
"book",
",",
"plugins",
")",
"{",
"return",
"Promise",
".",
"reduce",
"(",
"plugins",
",",
"function",
"(",
"newBook",
",",
"plugin",
")",
"{",
"return",
"validatePluginConfig",
"(",
"newBook",
",",
"plugin",
")",
";",
"}",
",",
"book",
")",
";",
"}"
] | Validate a book configuration for plugins and
returns an update configuration with default values.
@param {Book}
@param {OrderedMap<String:Plugin>}
@return {Promise<Book>} | [
"Validate",
"a",
"book",
"configuration",
"for",
"plugins",
"and",
"returns",
"an",
"update",
"configuration",
"with",
"default",
"values",
"."
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/plugins/validateConfig.js#L65-L69 |
1,044 | GitbookIO/gitbook | lib/modifiers/summary/insertArticle.js | insertArticle | function insertArticle(summary, article, level) {
article = SummaryArticle(article);
level = is.string(level)? level : level.getLevel();
var parent = summary.getParent(level);
if (!parent) {
return summary;
}
// Find the index to insert at
var articles = parent.getArticles();
var index = getLeafIndex(level);
// Insert the article at the right index
articles = articles.insert(index, article);
// Reindex the level from here
parent = parent.set('articles', articles);
parent = indexArticleLevels(parent);
return mergeAtLevel(summary, parent.getLevel(), parent);
} | javascript | function insertArticle(summary, article, level) {
article = SummaryArticle(article);
level = is.string(level)? level : level.getLevel();
var parent = summary.getParent(level);
if (!parent) {
return summary;
}
// Find the index to insert at
var articles = parent.getArticles();
var index = getLeafIndex(level);
// Insert the article at the right index
articles = articles.insert(index, article);
// Reindex the level from here
parent = parent.set('articles', articles);
parent = indexArticleLevels(parent);
return mergeAtLevel(summary, parent.getLevel(), parent);
} | [
"function",
"insertArticle",
"(",
"summary",
",",
"article",
",",
"level",
")",
"{",
"article",
"=",
"SummaryArticle",
"(",
"article",
")",
";",
"level",
"=",
"is",
".",
"string",
"(",
"level",
")",
"?",
"level",
":",
"level",
".",
"getLevel",
"(",
")",
";",
"var",
"parent",
"=",
"summary",
".",
"getParent",
"(",
"level",
")",
";",
"if",
"(",
"!",
"parent",
")",
"{",
"return",
"summary",
";",
"}",
"// Find the index to insert at",
"var",
"articles",
"=",
"parent",
".",
"getArticles",
"(",
")",
";",
"var",
"index",
"=",
"getLeafIndex",
"(",
"level",
")",
";",
"// Insert the article at the right index",
"articles",
"=",
"articles",
".",
"insert",
"(",
"index",
",",
"article",
")",
";",
"// Reindex the level from here",
"parent",
"=",
"parent",
".",
"set",
"(",
"'articles'",
",",
"articles",
")",
";",
"parent",
"=",
"indexArticleLevels",
"(",
"parent",
")",
";",
"return",
"mergeAtLevel",
"(",
"summary",
",",
"parent",
".",
"getLevel",
"(",
")",
",",
"parent",
")",
";",
"}"
] | Returns a new Summary with the article at the given level, with
subsequent article shifted.
@param {Summary} summary
@param {Article} article
@param {String|Article} level: level to insert at
@return {Summary} | [
"Returns",
"a",
"new",
"Summary",
"with",
"the",
"article",
"at",
"the",
"given",
"level",
"with",
"subsequent",
"article",
"shifted",
"."
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/modifiers/summary/insertArticle.js#L15-L36 |
1,045 | GitbookIO/gitbook | lib/plugins/listBlocks.js | listBlocks | function listBlocks(plugins) {
return plugins
.reverse()
.reduce(function(result, plugin) {
var blocks = plugin.getBlocks();
return result.merge(blocks);
}, Immutable.Map());
} | javascript | function listBlocks(plugins) {
return plugins
.reverse()
.reduce(function(result, plugin) {
var blocks = plugin.getBlocks();
return result.merge(blocks);
}, Immutable.Map());
} | [
"function",
"listBlocks",
"(",
"plugins",
")",
"{",
"return",
"plugins",
".",
"reverse",
"(",
")",
".",
"reduce",
"(",
"function",
"(",
"result",
",",
"plugin",
")",
"{",
"var",
"blocks",
"=",
"plugin",
".",
"getBlocks",
"(",
")",
";",
"return",
"result",
".",
"merge",
"(",
"blocks",
")",
";",
"}",
",",
"Immutable",
".",
"Map",
"(",
")",
")",
";",
"}"
] | List blocks from a list of plugins
@param {OrderedMap<String:Plugin>}
@return {Map<String:TemplateBlock>} | [
"List",
"blocks",
"from",
"a",
"list",
"of",
"plugins"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/plugins/listBlocks.js#L9-L16 |
1,046 | GitbookIO/gitbook | lib/parse/parseConfig.js | parseConfig | function parseConfig(book) {
var fs = book.getFS();
var config = book.getConfig();
return Promise.some(CONFIG_FILES, function(filename) {
// Is this file ignored?
if (book.isFileIgnored(filename)) {
return;
}
// Try loading it
return fs.loadAsObject(filename)
.then(function(cfg) {
return fs.statFile(filename)
.then(function(file) {
return {
file: file,
values: cfg
};
});
})
.fail(function(err) {
if (err.code != 'MODULE_NOT_FOUND') throw(err);
else return Promise(false);
});
})
.then(function(result) {
var values = result? result.values : {};
values = validateConfig(values);
// Set the file
if (result.file) {
config = config.setFile(result.file);
}
// Merge with old values
config = config.mergeValues(values);
return book.setConfig(config);
});
} | javascript | function parseConfig(book) {
var fs = book.getFS();
var config = book.getConfig();
return Promise.some(CONFIG_FILES, function(filename) {
// Is this file ignored?
if (book.isFileIgnored(filename)) {
return;
}
// Try loading it
return fs.loadAsObject(filename)
.then(function(cfg) {
return fs.statFile(filename)
.then(function(file) {
return {
file: file,
values: cfg
};
});
})
.fail(function(err) {
if (err.code != 'MODULE_NOT_FOUND') throw(err);
else return Promise(false);
});
})
.then(function(result) {
var values = result? result.values : {};
values = validateConfig(values);
// Set the file
if (result.file) {
config = config.setFile(result.file);
}
// Merge with old values
config = config.mergeValues(values);
return book.setConfig(config);
});
} | [
"function",
"parseConfig",
"(",
"book",
")",
"{",
"var",
"fs",
"=",
"book",
".",
"getFS",
"(",
")",
";",
"var",
"config",
"=",
"book",
".",
"getConfig",
"(",
")",
";",
"return",
"Promise",
".",
"some",
"(",
"CONFIG_FILES",
",",
"function",
"(",
"filename",
")",
"{",
"// Is this file ignored?",
"if",
"(",
"book",
".",
"isFileIgnored",
"(",
"filename",
")",
")",
"{",
"return",
";",
"}",
"// Try loading it",
"return",
"fs",
".",
"loadAsObject",
"(",
"filename",
")",
".",
"then",
"(",
"function",
"(",
"cfg",
")",
"{",
"return",
"fs",
".",
"statFile",
"(",
"filename",
")",
".",
"then",
"(",
"function",
"(",
"file",
")",
"{",
"return",
"{",
"file",
":",
"file",
",",
"values",
":",
"cfg",
"}",
";",
"}",
")",
";",
"}",
")",
".",
"fail",
"(",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
".",
"code",
"!=",
"'MODULE_NOT_FOUND'",
")",
"throw",
"(",
"err",
")",
";",
"else",
"return",
"Promise",
"(",
"false",
")",
";",
"}",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"var",
"values",
"=",
"result",
"?",
"result",
".",
"values",
":",
"{",
"}",
";",
"values",
"=",
"validateConfig",
"(",
"values",
")",
";",
"// Set the file",
"if",
"(",
"result",
".",
"file",
")",
"{",
"config",
"=",
"config",
".",
"setFile",
"(",
"result",
".",
"file",
")",
";",
"}",
"// Merge with old values",
"config",
"=",
"config",
".",
"mergeValues",
"(",
"values",
")",
";",
"return",
"book",
".",
"setConfig",
"(",
"config",
")",
";",
"}",
")",
";",
"}"
] | Parse configuration from "book.json" or "book.js"
@param {Book} book
@return {Promise<Book>} | [
"Parse",
"configuration",
"from",
"book",
".",
"json",
"or",
"book",
".",
"js"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/parse/parseConfig.js#L12-L53 |
1,047 | GitbookIO/gitbook | lib/parse/parsePagesList.js | parseFilePage | function parseFilePage(book, filePath) {
var fs = book.getContentFS();
return fs.statFile(filePath)
.then(
function(file) {
var page = Page.createForFile(file);
return parsePage(book, page);
},
function(err) {
// file doesn't exist
return null;
}
)
.fail(function(err) {
var logger = book.getLogger();
logger.error.ln('error while parsing page "' + filePath + '":');
throw err;
});
} | javascript | function parseFilePage(book, filePath) {
var fs = book.getContentFS();
return fs.statFile(filePath)
.then(
function(file) {
var page = Page.createForFile(file);
return parsePage(book, page);
},
function(err) {
// file doesn't exist
return null;
}
)
.fail(function(err) {
var logger = book.getLogger();
logger.error.ln('error while parsing page "' + filePath + '":');
throw err;
});
} | [
"function",
"parseFilePage",
"(",
"book",
",",
"filePath",
")",
"{",
"var",
"fs",
"=",
"book",
".",
"getContentFS",
"(",
")",
";",
"return",
"fs",
".",
"statFile",
"(",
"filePath",
")",
".",
"then",
"(",
"function",
"(",
"file",
")",
"{",
"var",
"page",
"=",
"Page",
".",
"createForFile",
"(",
"file",
")",
";",
"return",
"parsePage",
"(",
"book",
",",
"page",
")",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"// file doesn't exist",
"return",
"null",
";",
"}",
")",
".",
"fail",
"(",
"function",
"(",
"err",
")",
"{",
"var",
"logger",
"=",
"book",
".",
"getLogger",
"(",
")",
";",
"logger",
".",
"error",
".",
"ln",
"(",
"'error while parsing page \"'",
"+",
"filePath",
"+",
"'\":'",
")",
";",
"throw",
"err",
";",
"}",
")",
";",
"}"
] | Parse a page from a path
@param {Book} book
@param {String} filePath
@return {Page?} | [
"Parse",
"a",
"page",
"from",
"a",
"path"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/parse/parsePagesList.js#L16-L35 |
1,048 | GitbookIO/gitbook | lib/parse/parsePagesList.js | parsePagesList | function parsePagesList(book) {
var summary = book.getSummary();
var glossary = book.getGlossary();
var map = Immutable.OrderedMap();
// Parse pages from summary
return timing.measure(
'parse.listPages',
walkSummary(summary, function(article) {
if (!article.isPage()) return;
var filepath = article.getPath();
// Is the page ignored?
if (book.isContentFileIgnored(filepath)) return;
return parseFilePage(book, filepath)
.then(function(page) {
// file doesn't exist
if (!page) {
return;
}
map = map.set(filepath, page);
});
})
)
// Parse glossary
.then(function() {
var file = glossary.getFile();
if (!file.exists()) {
return;
}
return parseFilePage(book, file.getPath())
.then(function(page) {
// file doesn't exist
if (!page) {
return;
}
map = map.set(file.getPath(), page);
});
})
.then(function() {
return map;
});
} | javascript | function parsePagesList(book) {
var summary = book.getSummary();
var glossary = book.getGlossary();
var map = Immutable.OrderedMap();
// Parse pages from summary
return timing.measure(
'parse.listPages',
walkSummary(summary, function(article) {
if (!article.isPage()) return;
var filepath = article.getPath();
// Is the page ignored?
if (book.isContentFileIgnored(filepath)) return;
return parseFilePage(book, filepath)
.then(function(page) {
// file doesn't exist
if (!page) {
return;
}
map = map.set(filepath, page);
});
})
)
// Parse glossary
.then(function() {
var file = glossary.getFile();
if (!file.exists()) {
return;
}
return parseFilePage(book, file.getPath())
.then(function(page) {
// file doesn't exist
if (!page) {
return;
}
map = map.set(file.getPath(), page);
});
})
.then(function() {
return map;
});
} | [
"function",
"parsePagesList",
"(",
"book",
")",
"{",
"var",
"summary",
"=",
"book",
".",
"getSummary",
"(",
")",
";",
"var",
"glossary",
"=",
"book",
".",
"getGlossary",
"(",
")",
";",
"var",
"map",
"=",
"Immutable",
".",
"OrderedMap",
"(",
")",
";",
"// Parse pages from summary",
"return",
"timing",
".",
"measure",
"(",
"'parse.listPages'",
",",
"walkSummary",
"(",
"summary",
",",
"function",
"(",
"article",
")",
"{",
"if",
"(",
"!",
"article",
".",
"isPage",
"(",
")",
")",
"return",
";",
"var",
"filepath",
"=",
"article",
".",
"getPath",
"(",
")",
";",
"// Is the page ignored?",
"if",
"(",
"book",
".",
"isContentFileIgnored",
"(",
"filepath",
")",
")",
"return",
";",
"return",
"parseFilePage",
"(",
"book",
",",
"filepath",
")",
".",
"then",
"(",
"function",
"(",
"page",
")",
"{",
"// file doesn't exist",
"if",
"(",
"!",
"page",
")",
"{",
"return",
";",
"}",
"map",
"=",
"map",
".",
"set",
"(",
"filepath",
",",
"page",
")",
";",
"}",
")",
";",
"}",
")",
")",
"// Parse glossary",
".",
"then",
"(",
"function",
"(",
")",
"{",
"var",
"file",
"=",
"glossary",
".",
"getFile",
"(",
")",
";",
"if",
"(",
"!",
"file",
".",
"exists",
"(",
")",
")",
"{",
"return",
";",
"}",
"return",
"parseFilePage",
"(",
"book",
",",
"file",
".",
"getPath",
"(",
")",
")",
".",
"then",
"(",
"function",
"(",
"page",
")",
"{",
"// file doesn't exist",
"if",
"(",
"!",
"page",
")",
"{",
"return",
";",
"}",
"map",
"=",
"map",
".",
"set",
"(",
"file",
".",
"getPath",
"(",
")",
",",
"page",
")",
";",
"}",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"map",
";",
"}",
")",
";",
"}"
] | Parse all pages from a book as an OrderedMap
@param {Book} book
@return {Promise<OrderedMap<Page>>} | [
"Parse",
"all",
"pages",
"from",
"a",
"book",
"as",
"an",
"OrderedMap"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/parse/parsePagesList.js#L44-L94 |
1,049 | GitbookIO/gitbook | lib/parse/walkSummary.js | walkArticles | function walkArticles(articles, fn) {
return Promise.forEach(articles, function(article) {
return Promise(fn(article))
.then(function() {
return walkArticles(article.getArticles(), fn);
});
});
} | javascript | function walkArticles(articles, fn) {
return Promise.forEach(articles, function(article) {
return Promise(fn(article))
.then(function() {
return walkArticles(article.getArticles(), fn);
});
});
} | [
"function",
"walkArticles",
"(",
"articles",
",",
"fn",
")",
"{",
"return",
"Promise",
".",
"forEach",
"(",
"articles",
",",
"function",
"(",
"article",
")",
"{",
"return",
"Promise",
"(",
"fn",
"(",
"article",
")",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"walkArticles",
"(",
"article",
".",
"getArticles",
"(",
")",
",",
"fn",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Walk over a list of articles
@param {List<Article>} articles
@param {Function(article)}
@return {Promise} | [
"Walk",
"over",
"a",
"list",
"of",
"articles"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/parse/walkSummary.js#L10-L17 |
1,050 | GitbookIO/gitbook | lib/parse/walkSummary.js | walkSummary | function walkSummary(summary, fn) {
var parts = summary.getParts();
return Promise.forEach(parts, function(part) {
return walkArticles(part.getArticles(), fn);
});
} | javascript | function walkSummary(summary, fn) {
var parts = summary.getParts();
return Promise.forEach(parts, function(part) {
return walkArticles(part.getArticles(), fn);
});
} | [
"function",
"walkSummary",
"(",
"summary",
",",
"fn",
")",
"{",
"var",
"parts",
"=",
"summary",
".",
"getParts",
"(",
")",
";",
"return",
"Promise",
".",
"forEach",
"(",
"parts",
",",
"function",
"(",
"part",
")",
"{",
"return",
"walkArticles",
"(",
"part",
".",
"getArticles",
"(",
")",
",",
"fn",
")",
";",
"}",
")",
";",
"}"
] | Walk over summary and execute "fn" on each article
@param {Summary} summary
@param {Function(article)}
@return {Promise} | [
"Walk",
"over",
"summary",
"and",
"execute",
"fn",
"on",
"each",
"article"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/parse/walkSummary.js#L26-L32 |
1,051 | GitbookIO/gitbook | lib/modifiers/summary/insertPart.js | insertPart | function insertPart(summary, part, index) {
part = SummaryPart(part);
var parts = summary.getParts().insert(index, part);
return indexLevels(summary.set('parts', parts));
} | javascript | function insertPart(summary, part, index) {
part = SummaryPart(part);
var parts = summary.getParts().insert(index, part);
return indexLevels(summary.set('parts', parts));
} | [
"function",
"insertPart",
"(",
"summary",
",",
"part",
",",
"index",
")",
"{",
"part",
"=",
"SummaryPart",
"(",
"part",
")",
";",
"var",
"parts",
"=",
"summary",
".",
"getParts",
"(",
")",
".",
"insert",
"(",
"index",
",",
"part",
")",
";",
"return",
"indexLevels",
"(",
"summary",
".",
"set",
"(",
"'parts'",
",",
"parts",
")",
")",
";",
"}"
] | Returns a new Summary with a part inserted at given index
@param {Summary} summary
@param {Part} part
@param {Number} index
@return {Summary} | [
"Returns",
"a",
"new",
"Summary",
"with",
"a",
"part",
"inserted",
"at",
"given",
"index"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/modifiers/summary/insertPart.js#L12-L17 |
1,052 | GitbookIO/gitbook | lib/output/website/prepareI18n.js | prepareI18n | function prepareI18n(output) {
var state = output.getState();
var i18n = state.getI18n();
var searchPaths = listSearchPaths(output);
searchPaths
.reverse()
.forEach(function(searchPath) {
var i18nRoot = path.resolve(searchPath, '_i18n');
if (!fs.existsSync(i18nRoot)) return;
i18n.load(i18nRoot);
});
return Promise(output);
} | javascript | function prepareI18n(output) {
var state = output.getState();
var i18n = state.getI18n();
var searchPaths = listSearchPaths(output);
searchPaths
.reverse()
.forEach(function(searchPath) {
var i18nRoot = path.resolve(searchPath, '_i18n');
if (!fs.existsSync(i18nRoot)) return;
i18n.load(i18nRoot);
});
return Promise(output);
} | [
"function",
"prepareI18n",
"(",
"output",
")",
"{",
"var",
"state",
"=",
"output",
".",
"getState",
"(",
")",
";",
"var",
"i18n",
"=",
"state",
".",
"getI18n",
"(",
")",
";",
"var",
"searchPaths",
"=",
"listSearchPaths",
"(",
"output",
")",
";",
"searchPaths",
".",
"reverse",
"(",
")",
".",
"forEach",
"(",
"function",
"(",
"searchPath",
")",
"{",
"var",
"i18nRoot",
"=",
"path",
".",
"resolve",
"(",
"searchPath",
",",
"'_i18n'",
")",
";",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"i18nRoot",
")",
")",
"return",
";",
"i18n",
".",
"load",
"(",
"i18nRoot",
")",
";",
"}",
")",
";",
"return",
"Promise",
"(",
"output",
")",
";",
"}"
] | Prepare i18n, load translations from plugins and book
@param {Output}
@return {Promise<Output>} | [
"Prepare",
"i18n",
"load",
"translations",
"from",
"plugins",
"and",
"book"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/website/prepareI18n.js#L13-L28 |
1,053 | GitbookIO/gitbook | lib/utils/promise.js | reduce | function reduce(arr, iter, base) {
arr = Immutable.Iterable.isIterable(arr)? arr : Immutable.List(arr);
return arr.reduce(function(prev, elem, key) {
return prev
.then(function(val) {
return iter(val, elem, key);
});
}, Q(base));
} | javascript | function reduce(arr, iter, base) {
arr = Immutable.Iterable.isIterable(arr)? arr : Immutable.List(arr);
return arr.reduce(function(prev, elem, key) {
return prev
.then(function(val) {
return iter(val, elem, key);
});
}, Q(base));
} | [
"function",
"reduce",
"(",
"arr",
",",
"iter",
",",
"base",
")",
"{",
"arr",
"=",
"Immutable",
".",
"Iterable",
".",
"isIterable",
"(",
"arr",
")",
"?",
"arr",
":",
"Immutable",
".",
"List",
"(",
"arr",
")",
";",
"return",
"arr",
".",
"reduce",
"(",
"function",
"(",
"prev",
",",
"elem",
",",
"key",
")",
"{",
"return",
"prev",
".",
"then",
"(",
"function",
"(",
"val",
")",
"{",
"return",
"iter",
"(",
"val",
",",
"elem",
",",
"key",
")",
";",
"}",
")",
";",
"}",
",",
"Q",
"(",
"base",
")",
")",
";",
"}"
] | Reduce an array to a promise
@param {Array|List} arr
@param {Function(value, element, index)}
@return {Promise<Mixed>} | [
"Reduce",
"an",
"array",
"to",
"a",
"promise"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/utils/promise.js#L16-L25 |
1,054 | GitbookIO/gitbook | lib/utils/promise.js | forEach | function forEach(arr, iter) {
return reduce(arr, function(val, el, key) {
return iter(el, key);
});
} | javascript | function forEach(arr, iter) {
return reduce(arr, function(val, el, key) {
return iter(el, key);
});
} | [
"function",
"forEach",
"(",
"arr",
",",
"iter",
")",
"{",
"return",
"reduce",
"(",
"arr",
",",
"function",
"(",
"val",
",",
"el",
",",
"key",
")",
"{",
"return",
"iter",
"(",
"el",
",",
"key",
")",
";",
"}",
")",
";",
"}"
] | Iterate over an array using an async iter
@param {Array|List} arr
@param {Function(value, element, index)}
@return {Promise} | [
"Iterate",
"over",
"an",
"array",
"using",
"an",
"async",
"iter"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/utils/promise.js#L34-L38 |
1,055 | GitbookIO/gitbook | lib/utils/promise.js | serie | function serie(arr, iter, base) {
return reduce(arr, function(before, item, key) {
return Q(iter(item, key))
.then(function(r) {
before.push(r);
return before;
});
}, []);
} | javascript | function serie(arr, iter, base) {
return reduce(arr, function(before, item, key) {
return Q(iter(item, key))
.then(function(r) {
before.push(r);
return before;
});
}, []);
} | [
"function",
"serie",
"(",
"arr",
",",
"iter",
",",
"base",
")",
"{",
"return",
"reduce",
"(",
"arr",
",",
"function",
"(",
"before",
",",
"item",
",",
"key",
")",
"{",
"return",
"Q",
"(",
"iter",
"(",
"item",
",",
"key",
")",
")",
".",
"then",
"(",
"function",
"(",
"r",
")",
"{",
"before",
".",
"push",
"(",
"r",
")",
";",
"return",
"before",
";",
"}",
")",
";",
"}",
",",
"[",
"]",
")",
";",
"}"
] | Transform an array
@param {Array|List} arr
@param {Function(value, element, index)}
@return {Promise} | [
"Transform",
"an",
"array"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/utils/promise.js#L47-L55 |
1,056 | GitbookIO/gitbook | lib/utils/promise.js | map | function map(arr, iter) {
if (Immutable.Map.isMap(arr)) {
var type = 'Map';
if (Immutable.OrderedMap.isOrderedMap(arr)) {
type = 'OrderedMap';
}
return mapAsList(arr, function(value, key) {
return Q(iter(value, key))
.then(function(result) {
return [key, result];
});
})
.then(function(result) {
return Immutable[type](result);
});
} else {
return mapAsList(arr, iter)
.then(function(result) {
return Immutable.List(result);
});
}
} | javascript | function map(arr, iter) {
if (Immutable.Map.isMap(arr)) {
var type = 'Map';
if (Immutable.OrderedMap.isOrderedMap(arr)) {
type = 'OrderedMap';
}
return mapAsList(arr, function(value, key) {
return Q(iter(value, key))
.then(function(result) {
return [key, result];
});
})
.then(function(result) {
return Immutable[type](result);
});
} else {
return mapAsList(arr, iter)
.then(function(result) {
return Immutable.List(result);
});
}
} | [
"function",
"map",
"(",
"arr",
",",
"iter",
")",
"{",
"if",
"(",
"Immutable",
".",
"Map",
".",
"isMap",
"(",
"arr",
")",
")",
"{",
"var",
"type",
"=",
"'Map'",
";",
"if",
"(",
"Immutable",
".",
"OrderedMap",
".",
"isOrderedMap",
"(",
"arr",
")",
")",
"{",
"type",
"=",
"'OrderedMap'",
";",
"}",
"return",
"mapAsList",
"(",
"arr",
",",
"function",
"(",
"value",
",",
"key",
")",
"{",
"return",
"Q",
"(",
"iter",
"(",
"value",
",",
"key",
")",
")",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"return",
"[",
"key",
",",
"result",
"]",
";",
"}",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"return",
"Immutable",
"[",
"type",
"]",
"(",
"result",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"return",
"mapAsList",
"(",
"arr",
",",
"iter",
")",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"return",
"Immutable",
".",
"List",
"(",
"result",
")",
";",
"}",
")",
";",
"}",
"}"
] | Map an array or map
@param {Array|List|Map|OrderedMap} arr
@param {Function(element, key)}
@return {Promise<List|Map|OrderedMap>} | [
"Map",
"an",
"array",
"or",
"map"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/utils/promise.js#L100-L122 |
1,057 | GitbookIO/gitbook | lib/templating/listShortcuts.js | listShortcuts | function listShortcuts(blocks, filePath) {
var parser = parsers.getForFile(filePath);
if (!parser) {
return Immutable.List();
}
return blocks
.map(function(block) {
return block.getShortcuts();
})
.filter(function(shortcuts) {
return (
shortcuts &&
shortcuts.acceptParser(parser.getName())
);
});
} | javascript | function listShortcuts(blocks, filePath) {
var parser = parsers.getForFile(filePath);
if (!parser) {
return Immutable.List();
}
return blocks
.map(function(block) {
return block.getShortcuts();
})
.filter(function(shortcuts) {
return (
shortcuts &&
shortcuts.acceptParser(parser.getName())
);
});
} | [
"function",
"listShortcuts",
"(",
"blocks",
",",
"filePath",
")",
"{",
"var",
"parser",
"=",
"parsers",
".",
"getForFile",
"(",
"filePath",
")",
";",
"if",
"(",
"!",
"parser",
")",
"{",
"return",
"Immutable",
".",
"List",
"(",
")",
";",
"}",
"return",
"blocks",
".",
"map",
"(",
"function",
"(",
"block",
")",
"{",
"return",
"block",
".",
"getShortcuts",
"(",
")",
";",
"}",
")",
".",
"filter",
"(",
"function",
"(",
"shortcuts",
")",
"{",
"return",
"(",
"shortcuts",
"&&",
"shortcuts",
".",
"acceptParser",
"(",
"parser",
".",
"getName",
"(",
")",
")",
")",
";",
"}",
")",
";",
"}"
] | Return a list of all shortcuts that can apply
to a file for a TemplatEngine
@param {List<TemplateBlock>} engine
@param {String} filePath
@return {List<TemplateShortcut>} | [
"Return",
"a",
"list",
"of",
"all",
"shortcuts",
"that",
"can",
"apply",
"to",
"a",
"file",
"for",
"a",
"TemplatEngine"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/templating/listShortcuts.js#L12-L29 |
1,058 | GitbookIO/gitbook | lib/output/modifiers/svgToImg.js | renderDOM | function renderDOM($, dom, options) {
if (!dom && $._root && $._root.children) {
dom = $._root.children;
}
options = options|| dom.options || $._options;
return domSerializer(dom, options);
} | javascript | function renderDOM($, dom, options) {
if (!dom && $._root && $._root.children) {
dom = $._root.children;
}
options = options|| dom.options || $._options;
return domSerializer(dom, options);
} | [
"function",
"renderDOM",
"(",
"$",
",",
"dom",
",",
"options",
")",
"{",
"if",
"(",
"!",
"dom",
"&&",
"$",
".",
"_root",
"&&",
"$",
".",
"_root",
".",
"children",
")",
"{",
"dom",
"=",
"$",
".",
"_root",
".",
"children",
";",
"}",
"options",
"=",
"options",
"||",
"dom",
".",
"options",
"||",
"$",
".",
"_options",
";",
"return",
"domSerializer",
"(",
"dom",
",",
"options",
")",
";",
"}"
] | Render a cheerio DOM as html
@param {HTMLDom} $
@param {HTMLElement} dom
@param {Object}
@return {String} | [
"Render",
"a",
"cheerio",
"DOM",
"as",
"html"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/modifiers/svgToImg.js#L17-L23 |
1,059 | GitbookIO/gitbook | lib/output/modifiers/svgToImg.js | svgToImg | function svgToImg(baseFolder, currentFile, $) {
var currentDirectory = path.dirname(currentFile);
return editHTMLElement($, 'svg', function($svg) {
var content = '<?xml version="1.0" encoding="UTF-8"?>' +
renderDOM($, $svg);
// We avoid generating twice the same PNG
var hash = crc.crc32(content).toString(16);
var fileName = hash + '.svg';
var filePath = path.join(baseFolder, fileName);
// Write the svg to the file
return fs.assertFile(filePath, function() {
return fs.writeFile(filePath, content, 'utf8');
})
// Return as image
.then(function() {
var src = LocationUtils.relative(currentDirectory, fileName);
$svg.replaceWith('<img src="' + src + '" />');
});
});
} | javascript | function svgToImg(baseFolder, currentFile, $) {
var currentDirectory = path.dirname(currentFile);
return editHTMLElement($, 'svg', function($svg) {
var content = '<?xml version="1.0" encoding="UTF-8"?>' +
renderDOM($, $svg);
// We avoid generating twice the same PNG
var hash = crc.crc32(content).toString(16);
var fileName = hash + '.svg';
var filePath = path.join(baseFolder, fileName);
// Write the svg to the file
return fs.assertFile(filePath, function() {
return fs.writeFile(filePath, content, 'utf8');
})
// Return as image
.then(function() {
var src = LocationUtils.relative(currentDirectory, fileName);
$svg.replaceWith('<img src="' + src + '" />');
});
});
} | [
"function",
"svgToImg",
"(",
"baseFolder",
",",
"currentFile",
",",
"$",
")",
"{",
"var",
"currentDirectory",
"=",
"path",
".",
"dirname",
"(",
"currentFile",
")",
";",
"return",
"editHTMLElement",
"(",
"$",
",",
"'svg'",
",",
"function",
"(",
"$svg",
")",
"{",
"var",
"content",
"=",
"'<?xml version=\"1.0\" encoding=\"UTF-8\"?>'",
"+",
"renderDOM",
"(",
"$",
",",
"$svg",
")",
";",
"// We avoid generating twice the same PNG",
"var",
"hash",
"=",
"crc",
".",
"crc32",
"(",
"content",
")",
".",
"toString",
"(",
"16",
")",
";",
"var",
"fileName",
"=",
"hash",
"+",
"'.svg'",
";",
"var",
"filePath",
"=",
"path",
".",
"join",
"(",
"baseFolder",
",",
"fileName",
")",
";",
"// Write the svg to the file",
"return",
"fs",
".",
"assertFile",
"(",
"filePath",
",",
"function",
"(",
")",
"{",
"return",
"fs",
".",
"writeFile",
"(",
"filePath",
",",
"content",
",",
"'utf8'",
")",
";",
"}",
")",
"// Return as image",
".",
"then",
"(",
"function",
"(",
")",
"{",
"var",
"src",
"=",
"LocationUtils",
".",
"relative",
"(",
"currentDirectory",
",",
"fileName",
")",
";",
"$svg",
".",
"replaceWith",
"(",
"'<img src=\"'",
"+",
"src",
"+",
"'\" />'",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Replace SVG tag by IMG
@param {String} baseFolder
@param {HTMLDom} $ | [
"Replace",
"SVG",
"tag",
"by",
"IMG"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/modifiers/svgToImg.js#L31-L54 |
1,060 | GitbookIO/gitbook | lib/output/modifiers/highlightCode.js | getLanguageForClass | function getLanguageForClass(classNames) {
return Immutable.List(classNames)
.map(function(cl) {
// Markdown
if (cl.search('lang-') === 0) {
return cl.slice('lang-'.length);
}
// Asciidoc
if (cl.search('language-') === 0) {
return cl.slice('language-'.length);
}
return null;
})
.find(function(cl) {
return Boolean(cl);
});
} | javascript | function getLanguageForClass(classNames) {
return Immutable.List(classNames)
.map(function(cl) {
// Markdown
if (cl.search('lang-') === 0) {
return cl.slice('lang-'.length);
}
// Asciidoc
if (cl.search('language-') === 0) {
return cl.slice('language-'.length);
}
return null;
})
.find(function(cl) {
return Boolean(cl);
});
} | [
"function",
"getLanguageForClass",
"(",
"classNames",
")",
"{",
"return",
"Immutable",
".",
"List",
"(",
"classNames",
")",
".",
"map",
"(",
"function",
"(",
"cl",
")",
"{",
"// Markdown",
"if",
"(",
"cl",
".",
"search",
"(",
"'lang-'",
")",
"===",
"0",
")",
"{",
"return",
"cl",
".",
"slice",
"(",
"'lang-'",
".",
"length",
")",
";",
"}",
"// Asciidoc",
"if",
"(",
"cl",
".",
"search",
"(",
"'language-'",
")",
"===",
"0",
")",
"{",
"return",
"cl",
".",
"slice",
"(",
"'language-'",
".",
"length",
")",
";",
"}",
"return",
"null",
";",
"}",
")",
".",
"find",
"(",
"function",
"(",
"cl",
")",
"{",
"return",
"Boolean",
"(",
"cl",
")",
";",
"}",
")",
";",
"}"
] | Return language for a code blocks from a list of class names
@param {Array<String>}
@return {String} | [
"Return",
"language",
"for",
"a",
"code",
"blocks",
"from",
"a",
"list",
"of",
"class",
"names"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/modifiers/highlightCode.js#L13-L31 |
1,061 | GitbookIO/gitbook | lib/output/modifiers/highlightCode.js | highlightCode | function highlightCode(highlight, $) {
return editHTMLElement($, 'code', function($code) {
var classNames = ($code.attr('class') || '').split(' ');
var lang = getLanguageForClass(classNames);
var source = $code.text();
return Promise(highlight(lang, source))
.then(function(r) {
if (is.string(r.html)) {
$code.html(r.html);
} else {
$code.text(r.text);
}
});
});
} | javascript | function highlightCode(highlight, $) {
return editHTMLElement($, 'code', function($code) {
var classNames = ($code.attr('class') || '').split(' ');
var lang = getLanguageForClass(classNames);
var source = $code.text();
return Promise(highlight(lang, source))
.then(function(r) {
if (is.string(r.html)) {
$code.html(r.html);
} else {
$code.text(r.text);
}
});
});
} | [
"function",
"highlightCode",
"(",
"highlight",
",",
"$",
")",
"{",
"return",
"editHTMLElement",
"(",
"$",
",",
"'code'",
",",
"function",
"(",
"$code",
")",
"{",
"var",
"classNames",
"=",
"(",
"$code",
".",
"attr",
"(",
"'class'",
")",
"||",
"''",
")",
".",
"split",
"(",
"' '",
")",
";",
"var",
"lang",
"=",
"getLanguageForClass",
"(",
"classNames",
")",
";",
"var",
"source",
"=",
"$code",
".",
"text",
"(",
")",
";",
"return",
"Promise",
"(",
"highlight",
"(",
"lang",
",",
"source",
")",
")",
".",
"then",
"(",
"function",
"(",
"r",
")",
"{",
"if",
"(",
"is",
".",
"string",
"(",
"r",
".",
"html",
")",
")",
"{",
"$code",
".",
"html",
"(",
"r",
".",
"html",
")",
";",
"}",
"else",
"{",
"$code",
".",
"text",
"(",
"r",
".",
"text",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
] | Highlight all code elements
@param {Function(lang, body) -> String} highlight
@param {HTMLDom} $
@return {Promise} | [
"Highlight",
"all",
"code",
"elements"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/modifiers/highlightCode.js#L41-L56 |
1,062 | GitbookIO/gitbook | lib/output/generatePage.js | generatePage | function generatePage(output, page) {
var book = output.getBook();
var engine = createTemplateEngine(output);
return timing.measure(
'page.generate',
Promise(page)
.then(function(resultPage) {
var file = resultPage.getFile();
var filePath = file.getPath();
var parser = file.getParser();
var context = JSONUtils.encodeOutputWithPage(output, resultPage);
if (!parser) {
return Promise.reject(error.FileNotParsableError({
filename: filePath
}));
}
// Call hook "page:before"
return callPageHook('page:before', output, resultPage)
// Escape code blocks with raw tags
.then(function(currentPage) {
return parser.preparePage(currentPage.getContent());
})
// Render templating syntax
.then(function(content) {
var absoluteFilePath = path.join(book.getContentRoot(), filePath);
return Templating.render(engine, absoluteFilePath, content, context);
})
.then(function(output) {
var content = output.getContent();
return parser.parsePage(content)
.then(function(result) {
return output.setContent(result.content);
});
})
// Post processing for templating syntax
.then(function(output) {
return Templating.postRender(engine, output);
})
// Return new page
.then(function(content) {
return resultPage.set('content', content);
})
// Call final hook
.then(function(currentPage) {
return callPageHook('page', output, currentPage);
});
})
);
} | javascript | function generatePage(output, page) {
var book = output.getBook();
var engine = createTemplateEngine(output);
return timing.measure(
'page.generate',
Promise(page)
.then(function(resultPage) {
var file = resultPage.getFile();
var filePath = file.getPath();
var parser = file.getParser();
var context = JSONUtils.encodeOutputWithPage(output, resultPage);
if (!parser) {
return Promise.reject(error.FileNotParsableError({
filename: filePath
}));
}
// Call hook "page:before"
return callPageHook('page:before', output, resultPage)
// Escape code blocks with raw tags
.then(function(currentPage) {
return parser.preparePage(currentPage.getContent());
})
// Render templating syntax
.then(function(content) {
var absoluteFilePath = path.join(book.getContentRoot(), filePath);
return Templating.render(engine, absoluteFilePath, content, context);
})
.then(function(output) {
var content = output.getContent();
return parser.parsePage(content)
.then(function(result) {
return output.setContent(result.content);
});
})
// Post processing for templating syntax
.then(function(output) {
return Templating.postRender(engine, output);
})
// Return new page
.then(function(content) {
return resultPage.set('content', content);
})
// Call final hook
.then(function(currentPage) {
return callPageHook('page', output, currentPage);
});
})
);
} | [
"function",
"generatePage",
"(",
"output",
",",
"page",
")",
"{",
"var",
"book",
"=",
"output",
".",
"getBook",
"(",
")",
";",
"var",
"engine",
"=",
"createTemplateEngine",
"(",
"output",
")",
";",
"return",
"timing",
".",
"measure",
"(",
"'page.generate'",
",",
"Promise",
"(",
"page",
")",
".",
"then",
"(",
"function",
"(",
"resultPage",
")",
"{",
"var",
"file",
"=",
"resultPage",
".",
"getFile",
"(",
")",
";",
"var",
"filePath",
"=",
"file",
".",
"getPath",
"(",
")",
";",
"var",
"parser",
"=",
"file",
".",
"getParser",
"(",
")",
";",
"var",
"context",
"=",
"JSONUtils",
".",
"encodeOutputWithPage",
"(",
"output",
",",
"resultPage",
")",
";",
"if",
"(",
"!",
"parser",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"error",
".",
"FileNotParsableError",
"(",
"{",
"filename",
":",
"filePath",
"}",
")",
")",
";",
"}",
"// Call hook \"page:before\"",
"return",
"callPageHook",
"(",
"'page:before'",
",",
"output",
",",
"resultPage",
")",
"// Escape code blocks with raw tags",
".",
"then",
"(",
"function",
"(",
"currentPage",
")",
"{",
"return",
"parser",
".",
"preparePage",
"(",
"currentPage",
".",
"getContent",
"(",
")",
")",
";",
"}",
")",
"// Render templating syntax",
".",
"then",
"(",
"function",
"(",
"content",
")",
"{",
"var",
"absoluteFilePath",
"=",
"path",
".",
"join",
"(",
"book",
".",
"getContentRoot",
"(",
")",
",",
"filePath",
")",
";",
"return",
"Templating",
".",
"render",
"(",
"engine",
",",
"absoluteFilePath",
",",
"content",
",",
"context",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"output",
")",
"{",
"var",
"content",
"=",
"output",
".",
"getContent",
"(",
")",
";",
"return",
"parser",
".",
"parsePage",
"(",
"content",
")",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"return",
"output",
".",
"setContent",
"(",
"result",
".",
"content",
")",
";",
"}",
")",
";",
"}",
")",
"// Post processing for templating syntax",
".",
"then",
"(",
"function",
"(",
"output",
")",
"{",
"return",
"Templating",
".",
"postRender",
"(",
"engine",
",",
"output",
")",
";",
"}",
")",
"// Return new page",
".",
"then",
"(",
"function",
"(",
"content",
")",
"{",
"return",
"resultPage",
".",
"set",
"(",
"'content'",
",",
"content",
")",
";",
"}",
")",
"// Call final hook",
".",
"then",
"(",
"function",
"(",
"currentPage",
")",
"{",
"return",
"callPageHook",
"(",
"'page'",
",",
"output",
",",
"currentPage",
")",
";",
"}",
")",
";",
"}",
")",
")",
";",
"}"
] | Prepare and generate HTML for a page
@param {Output} output
@param {Page} page
@return {Promise<Page>} | [
"Prepare",
"and",
"generate",
"HTML",
"for",
"a",
"page"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/generatePage.js#L19-L77 |
1,063 | GitbookIO/gitbook | lib/parse/parseBook.js | parseBookContent | function parseBookContent(book) {
return Promise(book)
.then(parseReadme)
.then(parseSummary)
.then(parseGlossary);
} | javascript | function parseBookContent(book) {
return Promise(book)
.then(parseReadme)
.then(parseSummary)
.then(parseGlossary);
} | [
"function",
"parseBookContent",
"(",
"book",
")",
"{",
"return",
"Promise",
"(",
"book",
")",
".",
"then",
"(",
"parseReadme",
")",
".",
"then",
"(",
"parseSummary",
")",
".",
"then",
"(",
"parseGlossary",
")",
";",
"}"
] | Parse content of a book
@param {Book} book
@return {Promise<Book>} | [
"Parse",
"content",
"of",
"a",
"book"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/parse/parseBook.js#L18-L23 |
1,064 | GitbookIO/gitbook | lib/parse/parseBook.js | parseMultilingualBook | function parseMultilingualBook(book) {
var languages = book.getLanguages();
var langList = languages.getList();
return Promise.reduce(langList, function(currentBook, lang) {
var langID = lang.getID();
var child = Book.createFromParent(currentBook, langID);
var ignore = currentBook.getIgnore();
return Promise(child)
.then(parseConfig)
.then(parseBookContent)
.then(function(result) {
// Ignore content of this book when generating parent book
ignore = ignore.add(langID + '/**');
currentBook = currentBook.set('ignore', ignore);
return currentBook.addLanguageBook(langID, result);
});
}, book);
} | javascript | function parseMultilingualBook(book) {
var languages = book.getLanguages();
var langList = languages.getList();
return Promise.reduce(langList, function(currentBook, lang) {
var langID = lang.getID();
var child = Book.createFromParent(currentBook, langID);
var ignore = currentBook.getIgnore();
return Promise(child)
.then(parseConfig)
.then(parseBookContent)
.then(function(result) {
// Ignore content of this book when generating parent book
ignore = ignore.add(langID + '/**');
currentBook = currentBook.set('ignore', ignore);
return currentBook.addLanguageBook(langID, result);
});
}, book);
} | [
"function",
"parseMultilingualBook",
"(",
"book",
")",
"{",
"var",
"languages",
"=",
"book",
".",
"getLanguages",
"(",
")",
";",
"var",
"langList",
"=",
"languages",
".",
"getList",
"(",
")",
";",
"return",
"Promise",
".",
"reduce",
"(",
"langList",
",",
"function",
"(",
"currentBook",
",",
"lang",
")",
"{",
"var",
"langID",
"=",
"lang",
".",
"getID",
"(",
")",
";",
"var",
"child",
"=",
"Book",
".",
"createFromParent",
"(",
"currentBook",
",",
"langID",
")",
";",
"var",
"ignore",
"=",
"currentBook",
".",
"getIgnore",
"(",
")",
";",
"return",
"Promise",
"(",
"child",
")",
".",
"then",
"(",
"parseConfig",
")",
".",
"then",
"(",
"parseBookContent",
")",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"// Ignore content of this book when generating parent book",
"ignore",
"=",
"ignore",
".",
"add",
"(",
"langID",
"+",
"'/**'",
")",
";",
"currentBook",
"=",
"currentBook",
".",
"set",
"(",
"'ignore'",
",",
"ignore",
")",
";",
"return",
"currentBook",
".",
"addLanguageBook",
"(",
"langID",
",",
"result",
")",
";",
"}",
")",
";",
"}",
",",
"book",
")",
";",
"}"
] | Parse a multilingual book
@param {Book} book
@return {Promise<Book>} | [
"Parse",
"a",
"multilingual",
"book"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/parse/parseBook.js#L31-L51 |
1,065 | GitbookIO/gitbook | lib/parse/parseBook.js | parseBook | function parseBook(book) {
return timing.measure(
'parse.book',
Promise(book)
.then(parseIgnore)
.then(parseConfig)
.then(parseLanguages)
.then(function(resultBook) {
if (resultBook.isMultilingual()) {
return parseMultilingualBook(resultBook);
} else {
return parseBookContent(resultBook);
}
})
);
} | javascript | function parseBook(book) {
return timing.measure(
'parse.book',
Promise(book)
.then(parseIgnore)
.then(parseConfig)
.then(parseLanguages)
.then(function(resultBook) {
if (resultBook.isMultilingual()) {
return parseMultilingualBook(resultBook);
} else {
return parseBookContent(resultBook);
}
})
);
} | [
"function",
"parseBook",
"(",
"book",
")",
"{",
"return",
"timing",
".",
"measure",
"(",
"'parse.book'",
",",
"Promise",
"(",
"book",
")",
".",
"then",
"(",
"parseIgnore",
")",
".",
"then",
"(",
"parseConfig",
")",
".",
"then",
"(",
"parseLanguages",
")",
".",
"then",
"(",
"function",
"(",
"resultBook",
")",
"{",
"if",
"(",
"resultBook",
".",
"isMultilingual",
"(",
")",
")",
"{",
"return",
"parseMultilingualBook",
"(",
"resultBook",
")",
";",
"}",
"else",
"{",
"return",
"parseBookContent",
"(",
"resultBook",
")",
";",
"}",
"}",
")",
")",
";",
"}"
] | Parse a whole book from a filesystem
@param {Book} book
@return {Promise<Book>} | [
"Parse",
"a",
"whole",
"book",
"from",
"a",
"filesystem"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/parse/parseBook.js#L60-L75 |
1,066 | GitbookIO/gitbook | lib/output/modifiers/inlinePng.js | inlinePng | function inlinePng(rootFolder, currentFile, $) {
var currentDirectory = path.dirname(currentFile);
return editHTMLElement($, 'img', function($img) {
var src = $img.attr('src');
if (!LocationUtils.isDataURI(src)) {
return;
}
// We avoid generating twice the same PNG
var hash = crc.crc32(src).toString(16);
var fileName = hash + '.png';
// Result file path
var filePath = path.join(rootFolder, fileName);
return fs.assertFile(filePath, function() {
return imagesUtil.convertInlinePNG(src, filePath);
})
.then(function() {
// Convert filename to a relative filename
fileName = LocationUtils.relative(currentDirectory, fileName);
// Replace src
$img.attr('src', fileName);
});
});
} | javascript | function inlinePng(rootFolder, currentFile, $) {
var currentDirectory = path.dirname(currentFile);
return editHTMLElement($, 'img', function($img) {
var src = $img.attr('src');
if (!LocationUtils.isDataURI(src)) {
return;
}
// We avoid generating twice the same PNG
var hash = crc.crc32(src).toString(16);
var fileName = hash + '.png';
// Result file path
var filePath = path.join(rootFolder, fileName);
return fs.assertFile(filePath, function() {
return imagesUtil.convertInlinePNG(src, filePath);
})
.then(function() {
// Convert filename to a relative filename
fileName = LocationUtils.relative(currentDirectory, fileName);
// Replace src
$img.attr('src', fileName);
});
});
} | [
"function",
"inlinePng",
"(",
"rootFolder",
",",
"currentFile",
",",
"$",
")",
"{",
"var",
"currentDirectory",
"=",
"path",
".",
"dirname",
"(",
"currentFile",
")",
";",
"return",
"editHTMLElement",
"(",
"$",
",",
"'img'",
",",
"function",
"(",
"$img",
")",
"{",
"var",
"src",
"=",
"$img",
".",
"attr",
"(",
"'src'",
")",
";",
"if",
"(",
"!",
"LocationUtils",
".",
"isDataURI",
"(",
"src",
")",
")",
"{",
"return",
";",
"}",
"// We avoid generating twice the same PNG",
"var",
"hash",
"=",
"crc",
".",
"crc32",
"(",
"src",
")",
".",
"toString",
"(",
"16",
")",
";",
"var",
"fileName",
"=",
"hash",
"+",
"'.png'",
";",
"// Result file path",
"var",
"filePath",
"=",
"path",
".",
"join",
"(",
"rootFolder",
",",
"fileName",
")",
";",
"return",
"fs",
".",
"assertFile",
"(",
"filePath",
",",
"function",
"(",
")",
"{",
"return",
"imagesUtil",
".",
"convertInlinePNG",
"(",
"src",
",",
"filePath",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"// Convert filename to a relative filename",
"fileName",
"=",
"LocationUtils",
".",
"relative",
"(",
"currentDirectory",
",",
"fileName",
")",
";",
"// Replace src",
"$img",
".",
"attr",
"(",
"'src'",
",",
"fileName",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Convert all inline PNG images to PNG file
@param {String} rootFolder
@param {HTMLDom} $
@return {Promise} | [
"Convert",
"all",
"inline",
"PNG",
"images",
"to",
"PNG",
"file"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/modifiers/inlinePng.js#L17-L44 |
1,067 | GitbookIO/gitbook | lib/modifiers/summary/unshiftArticle.js | unshiftArticle | function unshiftArticle(summary, article) {
article = SummaryArticle(article);
var parts = summary.getParts();
var part = parts.get(0) || SummaryPart();
var articles = part.getArticles();
articles = articles.unshift(article);
part = part.set('articles', articles);
parts = parts.set(0, part);
summary = summary.set('parts', parts);
return indexLevels(summary);
} | javascript | function unshiftArticle(summary, article) {
article = SummaryArticle(article);
var parts = summary.getParts();
var part = parts.get(0) || SummaryPart();
var articles = part.getArticles();
articles = articles.unshift(article);
part = part.set('articles', articles);
parts = parts.set(0, part);
summary = summary.set('parts', parts);
return indexLevels(summary);
} | [
"function",
"unshiftArticle",
"(",
"summary",
",",
"article",
")",
"{",
"article",
"=",
"SummaryArticle",
"(",
"article",
")",
";",
"var",
"parts",
"=",
"summary",
".",
"getParts",
"(",
")",
";",
"var",
"part",
"=",
"parts",
".",
"get",
"(",
"0",
")",
"||",
"SummaryPart",
"(",
")",
";",
"var",
"articles",
"=",
"part",
".",
"getArticles",
"(",
")",
";",
"articles",
"=",
"articles",
".",
"unshift",
"(",
"article",
")",
";",
"part",
"=",
"part",
".",
"set",
"(",
"'articles'",
",",
"articles",
")",
";",
"parts",
"=",
"parts",
".",
"set",
"(",
"0",
",",
"part",
")",
";",
"summary",
"=",
"summary",
".",
"set",
"(",
"'parts'",
",",
"parts",
")",
";",
"return",
"indexLevels",
"(",
"summary",
")",
";",
"}"
] | Insert an article at the beginning of summary
@param {Summary} summary
@param {Article} article
@return {Summary} | [
"Insert",
"an",
"article",
"at",
"the",
"beginning",
"of",
"summary"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/modifiers/summary/unshiftArticle.js#L13-L27 |
1,068 | GitbookIO/gitbook | lib/json/encodeSummaryPart.js | encodeSummaryPart | function encodeSummaryPart(part) {
return {
title: part.getTitle(),
articles: part.getArticles()
.map(encodeSummaryArticle).toJS()
};
} | javascript | function encodeSummaryPart(part) {
return {
title: part.getTitle(),
articles: part.getArticles()
.map(encodeSummaryArticle).toJS()
};
} | [
"function",
"encodeSummaryPart",
"(",
"part",
")",
"{",
"return",
"{",
"title",
":",
"part",
".",
"getTitle",
"(",
")",
",",
"articles",
":",
"part",
".",
"getArticles",
"(",
")",
".",
"map",
"(",
"encodeSummaryArticle",
")",
".",
"toJS",
"(",
")",
"}",
";",
"}"
] | Encode a SummaryPart to JSON
@param {SummaryPart}
@return {Object} | [
"Encode",
"a",
"SummaryPart",
"to",
"JSON"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/json/encodeSummaryPart.js#L9-L15 |
1,069 | GitbookIO/gitbook | lib/plugins/resolveVersion.js | initNPM | function initNPM() {
if (npmIsReady) return npmIsReady;
npmIsReady = Promise.nfcall(npm.load, {
silent: true,
loglevel: 'silent'
});
return npmIsReady;
} | javascript | function initNPM() {
if (npmIsReady) return npmIsReady;
npmIsReady = Promise.nfcall(npm.load, {
silent: true,
loglevel: 'silent'
});
return npmIsReady;
} | [
"function",
"initNPM",
"(",
")",
"{",
"if",
"(",
"npmIsReady",
")",
"return",
"npmIsReady",
";",
"npmIsReady",
"=",
"Promise",
".",
"nfcall",
"(",
"npm",
".",
"load",
",",
"{",
"silent",
":",
"true",
",",
"loglevel",
":",
"'silent'",
"}",
")",
";",
"return",
"npmIsReady",
";",
"}"
] | Initialize and prepare NPM
@return {Promise} | [
"Initialize",
"and",
"prepare",
"NPM"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/plugins/resolveVersion.js#L16-L25 |
1,070 | GitbookIO/gitbook | lib/plugins/resolveVersion.js | resolveVersion | function resolveVersion(plugin) {
var npmId = Plugin.nameToNpmID(plugin.getName());
var requiredVersion = plugin.getVersion();
if (plugin.isGitDependency()) {
return Promise.resolve(requiredVersion);
}
return initNPM()
.then(function() {
return Promise.nfcall(npm.commands.view, [npmId + '@' + requiredVersion, 'engines'], true);
})
.then(function(versions) {
versions = Immutable.Map(versions).entrySeq();
var result = versions
.map(function(entry) {
return {
version: entry[0],
gitbook: (entry[1].engines || {}).gitbook
};
})
.filter(function(v) {
return v.gitbook && gitbook.satisfies(v.gitbook);
})
.sort(function(v1, v2) {
return semver.lt(v1.version, v2.version)? 1 : -1;
})
.get(0);
if (!result) {
return undefined;
} else {
return result.version;
}
});
} | javascript | function resolveVersion(plugin) {
var npmId = Plugin.nameToNpmID(plugin.getName());
var requiredVersion = plugin.getVersion();
if (plugin.isGitDependency()) {
return Promise.resolve(requiredVersion);
}
return initNPM()
.then(function() {
return Promise.nfcall(npm.commands.view, [npmId + '@' + requiredVersion, 'engines'], true);
})
.then(function(versions) {
versions = Immutable.Map(versions).entrySeq();
var result = versions
.map(function(entry) {
return {
version: entry[0],
gitbook: (entry[1].engines || {}).gitbook
};
})
.filter(function(v) {
return v.gitbook && gitbook.satisfies(v.gitbook);
})
.sort(function(v1, v2) {
return semver.lt(v1.version, v2.version)? 1 : -1;
})
.get(0);
if (!result) {
return undefined;
} else {
return result.version;
}
});
} | [
"function",
"resolveVersion",
"(",
"plugin",
")",
"{",
"var",
"npmId",
"=",
"Plugin",
".",
"nameToNpmID",
"(",
"plugin",
".",
"getName",
"(",
")",
")",
";",
"var",
"requiredVersion",
"=",
"plugin",
".",
"getVersion",
"(",
")",
";",
"if",
"(",
"plugin",
".",
"isGitDependency",
"(",
")",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
"requiredVersion",
")",
";",
"}",
"return",
"initNPM",
"(",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"Promise",
".",
"nfcall",
"(",
"npm",
".",
"commands",
".",
"view",
",",
"[",
"npmId",
"+",
"'@'",
"+",
"requiredVersion",
",",
"'engines'",
"]",
",",
"true",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"versions",
")",
"{",
"versions",
"=",
"Immutable",
".",
"Map",
"(",
"versions",
")",
".",
"entrySeq",
"(",
")",
";",
"var",
"result",
"=",
"versions",
".",
"map",
"(",
"function",
"(",
"entry",
")",
"{",
"return",
"{",
"version",
":",
"entry",
"[",
"0",
"]",
",",
"gitbook",
":",
"(",
"entry",
"[",
"1",
"]",
".",
"engines",
"||",
"{",
"}",
")",
".",
"gitbook",
"}",
";",
"}",
")",
".",
"filter",
"(",
"function",
"(",
"v",
")",
"{",
"return",
"v",
".",
"gitbook",
"&&",
"gitbook",
".",
"satisfies",
"(",
"v",
".",
"gitbook",
")",
";",
"}",
")",
".",
"sort",
"(",
"function",
"(",
"v1",
",",
"v2",
")",
"{",
"return",
"semver",
".",
"lt",
"(",
"v1",
".",
"version",
",",
"v2",
".",
"version",
")",
"?",
"1",
":",
"-",
"1",
";",
"}",
")",
".",
"get",
"(",
"0",
")",
";",
"if",
"(",
"!",
"result",
")",
"{",
"return",
"undefined",
";",
"}",
"else",
"{",
"return",
"result",
".",
"version",
";",
"}",
"}",
")",
";",
"}"
] | Resolve a plugin dependency to a version
@param {PluginDependency} plugin
@return {Promise<String>} | [
"Resolve",
"a",
"plugin",
"dependency",
"to",
"a",
"version"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/plugins/resolveVersion.js#L33-L69 |
1,071 | GitbookIO/gitbook | lib/output/website/createTemplateEngine.js | createTemplateEngine | function createTemplateEngine(output, currentFile) {
var book = output.getBook();
var state = output.getState();
var i18n = state.getI18n();
var config = book.getConfig();
var summary = book.getSummary();
var outputFolder = output.getRoot();
// Search paths for templates
var searchPaths = listSearchPaths(output);
var tplSearchPaths = searchPaths.map(templateFolder);
// Create loader
var loader = new Templating.ThemesLoader(tplSearchPaths);
// Get languages
var language = config.getValue('language');
// Create API context
var context = Api.encodeGlobal(output);
/**
* Check if a file exists
* @param {String} fileName
* @return {Boolean}
*/
function fileExists(fileName) {
if (!fileName) {
return false;
}
var filePath = PathUtils.resolveInRoot(outputFolder, fileName);
return fs.existsSync(filePath);
}
/**
* Return an article by its path
* @param {String} filePath
* @return {Object|undefined}
*/
function getArticleByPath(filePath) {
var article = summary.getByPath(filePath);
if (!article) return undefined;
return JSONUtils.encodeSummaryArticle(article);
}
/**
* Return a page by its path
* @param {String} filePath
* @return {Object|undefined}
*/
function getPageByPath(filePath) {
var page = output.getPage(filePath);
if (!page) return undefined;
return JSONUtils.encodePage(page, summary);
}
return TemplateEngine.create({
loader: loader,
context: context,
globals: {
getArticleByPath: getArticleByPath,
getPageByPath: getPageByPath,
fileExists: fileExists
},
filters: defaultFilters.merge({
/**
* Translate a sentence
*/
t: function t(s) {
return i18n.t(language, s);
},
/**
* Resolve an absolute file path into a
* relative path.
* it also resolve pages
*/
resolveFile: function(filePath) {
filePath = resolveFileToURL(output, filePath);
return LocationUtils.relativeForFile(currentFile, filePath);
},
resolveAsset: function(filePath) {
filePath = LocationUtils.toAbsolute(filePath, '', '');
filePath = path.join('gitbook', filePath);
filePath = LocationUtils.relativeForFile(currentFile, filePath);
// Use assets from parent if language book
if (book.isLanguageBook()) {
filePath = path.join('../', filePath);
}
return LocationUtils.normalize(filePath);
},
fileExists: deprecate.method(book, 'fileExists', fileExists, 'Filter "fileExists" is deprecated, use "fileExists(filename)" '),
getArticleByPath: deprecate.method(book, 'getArticleByPath', fileExists, 'Filter "getArticleByPath" is deprecated, use "getArticleByPath(filename)" '),
contentURL: function(filePath) {
return fileToURL(output, filePath);
}
}),
extensions: {
'DoExtension': new DoExtension()
}
});
} | javascript | function createTemplateEngine(output, currentFile) {
var book = output.getBook();
var state = output.getState();
var i18n = state.getI18n();
var config = book.getConfig();
var summary = book.getSummary();
var outputFolder = output.getRoot();
// Search paths for templates
var searchPaths = listSearchPaths(output);
var tplSearchPaths = searchPaths.map(templateFolder);
// Create loader
var loader = new Templating.ThemesLoader(tplSearchPaths);
// Get languages
var language = config.getValue('language');
// Create API context
var context = Api.encodeGlobal(output);
/**
* Check if a file exists
* @param {String} fileName
* @return {Boolean}
*/
function fileExists(fileName) {
if (!fileName) {
return false;
}
var filePath = PathUtils.resolveInRoot(outputFolder, fileName);
return fs.existsSync(filePath);
}
/**
* Return an article by its path
* @param {String} filePath
* @return {Object|undefined}
*/
function getArticleByPath(filePath) {
var article = summary.getByPath(filePath);
if (!article) return undefined;
return JSONUtils.encodeSummaryArticle(article);
}
/**
* Return a page by its path
* @param {String} filePath
* @return {Object|undefined}
*/
function getPageByPath(filePath) {
var page = output.getPage(filePath);
if (!page) return undefined;
return JSONUtils.encodePage(page, summary);
}
return TemplateEngine.create({
loader: loader,
context: context,
globals: {
getArticleByPath: getArticleByPath,
getPageByPath: getPageByPath,
fileExists: fileExists
},
filters: defaultFilters.merge({
/**
* Translate a sentence
*/
t: function t(s) {
return i18n.t(language, s);
},
/**
* Resolve an absolute file path into a
* relative path.
* it also resolve pages
*/
resolveFile: function(filePath) {
filePath = resolveFileToURL(output, filePath);
return LocationUtils.relativeForFile(currentFile, filePath);
},
resolveAsset: function(filePath) {
filePath = LocationUtils.toAbsolute(filePath, '', '');
filePath = path.join('gitbook', filePath);
filePath = LocationUtils.relativeForFile(currentFile, filePath);
// Use assets from parent if language book
if (book.isLanguageBook()) {
filePath = path.join('../', filePath);
}
return LocationUtils.normalize(filePath);
},
fileExists: deprecate.method(book, 'fileExists', fileExists, 'Filter "fileExists" is deprecated, use "fileExists(filename)" '),
getArticleByPath: deprecate.method(book, 'getArticleByPath', fileExists, 'Filter "getArticleByPath" is deprecated, use "getArticleByPath(filename)" '),
contentURL: function(filePath) {
return fileToURL(output, filePath);
}
}),
extensions: {
'DoExtension': new DoExtension()
}
});
} | [
"function",
"createTemplateEngine",
"(",
"output",
",",
"currentFile",
")",
"{",
"var",
"book",
"=",
"output",
".",
"getBook",
"(",
")",
";",
"var",
"state",
"=",
"output",
".",
"getState",
"(",
")",
";",
"var",
"i18n",
"=",
"state",
".",
"getI18n",
"(",
")",
";",
"var",
"config",
"=",
"book",
".",
"getConfig",
"(",
")",
";",
"var",
"summary",
"=",
"book",
".",
"getSummary",
"(",
")",
";",
"var",
"outputFolder",
"=",
"output",
".",
"getRoot",
"(",
")",
";",
"// Search paths for templates",
"var",
"searchPaths",
"=",
"listSearchPaths",
"(",
"output",
")",
";",
"var",
"tplSearchPaths",
"=",
"searchPaths",
".",
"map",
"(",
"templateFolder",
")",
";",
"// Create loader",
"var",
"loader",
"=",
"new",
"Templating",
".",
"ThemesLoader",
"(",
"tplSearchPaths",
")",
";",
"// Get languages",
"var",
"language",
"=",
"config",
".",
"getValue",
"(",
"'language'",
")",
";",
"// Create API context",
"var",
"context",
"=",
"Api",
".",
"encodeGlobal",
"(",
"output",
")",
";",
"/**\n * Check if a file exists\n * @param {String} fileName\n * @return {Boolean}\n */",
"function",
"fileExists",
"(",
"fileName",
")",
"{",
"if",
"(",
"!",
"fileName",
")",
"{",
"return",
"false",
";",
"}",
"var",
"filePath",
"=",
"PathUtils",
".",
"resolveInRoot",
"(",
"outputFolder",
",",
"fileName",
")",
";",
"return",
"fs",
".",
"existsSync",
"(",
"filePath",
")",
";",
"}",
"/**\n * Return an article by its path\n * @param {String} filePath\n * @return {Object|undefined}\n */",
"function",
"getArticleByPath",
"(",
"filePath",
")",
"{",
"var",
"article",
"=",
"summary",
".",
"getByPath",
"(",
"filePath",
")",
";",
"if",
"(",
"!",
"article",
")",
"return",
"undefined",
";",
"return",
"JSONUtils",
".",
"encodeSummaryArticle",
"(",
"article",
")",
";",
"}",
"/**\n * Return a page by its path\n * @param {String} filePath\n * @return {Object|undefined}\n */",
"function",
"getPageByPath",
"(",
"filePath",
")",
"{",
"var",
"page",
"=",
"output",
".",
"getPage",
"(",
"filePath",
")",
";",
"if",
"(",
"!",
"page",
")",
"return",
"undefined",
";",
"return",
"JSONUtils",
".",
"encodePage",
"(",
"page",
",",
"summary",
")",
";",
"}",
"return",
"TemplateEngine",
".",
"create",
"(",
"{",
"loader",
":",
"loader",
",",
"context",
":",
"context",
",",
"globals",
":",
"{",
"getArticleByPath",
":",
"getArticleByPath",
",",
"getPageByPath",
":",
"getPageByPath",
",",
"fileExists",
":",
"fileExists",
"}",
",",
"filters",
":",
"defaultFilters",
".",
"merge",
"(",
"{",
"/**\n * Translate a sentence\n */",
"t",
":",
"function",
"t",
"(",
"s",
")",
"{",
"return",
"i18n",
".",
"t",
"(",
"language",
",",
"s",
")",
";",
"}",
",",
"/**\n * Resolve an absolute file path into a\n * relative path.\n * it also resolve pages\n */",
"resolveFile",
":",
"function",
"(",
"filePath",
")",
"{",
"filePath",
"=",
"resolveFileToURL",
"(",
"output",
",",
"filePath",
")",
";",
"return",
"LocationUtils",
".",
"relativeForFile",
"(",
"currentFile",
",",
"filePath",
")",
";",
"}",
",",
"resolveAsset",
":",
"function",
"(",
"filePath",
")",
"{",
"filePath",
"=",
"LocationUtils",
".",
"toAbsolute",
"(",
"filePath",
",",
"''",
",",
"''",
")",
";",
"filePath",
"=",
"path",
".",
"join",
"(",
"'gitbook'",
",",
"filePath",
")",
";",
"filePath",
"=",
"LocationUtils",
".",
"relativeForFile",
"(",
"currentFile",
",",
"filePath",
")",
";",
"// Use assets from parent if language book",
"if",
"(",
"book",
".",
"isLanguageBook",
"(",
")",
")",
"{",
"filePath",
"=",
"path",
".",
"join",
"(",
"'../'",
",",
"filePath",
")",
";",
"}",
"return",
"LocationUtils",
".",
"normalize",
"(",
"filePath",
")",
";",
"}",
",",
"fileExists",
":",
"deprecate",
".",
"method",
"(",
"book",
",",
"'fileExists'",
",",
"fileExists",
",",
"'Filter \"fileExists\" is deprecated, use \"fileExists(filename)\" '",
")",
",",
"getArticleByPath",
":",
"deprecate",
".",
"method",
"(",
"book",
",",
"'getArticleByPath'",
",",
"fileExists",
",",
"'Filter \"getArticleByPath\" is deprecated, use \"getArticleByPath(filename)\" '",
")",
",",
"contentURL",
":",
"function",
"(",
"filePath",
")",
"{",
"return",
"fileToURL",
"(",
"output",
",",
"filePath",
")",
";",
"}",
"}",
")",
",",
"extensions",
":",
"{",
"'DoExtension'",
":",
"new",
"DoExtension",
"(",
")",
"}",
"}",
")",
";",
"}"
] | Create templating engine to render themes
@param {Output} output
@param {String} currentFile
@return {TemplateEngine} | [
"Create",
"templating",
"engine",
"to",
"render",
"themes"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/website/createTemplateEngine.js#L34-L149 |
1,072 | GitbookIO/gitbook | lib/output/website/createTemplateEngine.js | getArticleByPath | function getArticleByPath(filePath) {
var article = summary.getByPath(filePath);
if (!article) return undefined;
return JSONUtils.encodeSummaryArticle(article);
} | javascript | function getArticleByPath(filePath) {
var article = summary.getByPath(filePath);
if (!article) return undefined;
return JSONUtils.encodeSummaryArticle(article);
} | [
"function",
"getArticleByPath",
"(",
"filePath",
")",
"{",
"var",
"article",
"=",
"summary",
".",
"getByPath",
"(",
"filePath",
")",
";",
"if",
"(",
"!",
"article",
")",
"return",
"undefined",
";",
"return",
"JSONUtils",
".",
"encodeSummaryArticle",
"(",
"article",
")",
";",
"}"
] | Return an article by its path
@param {String} filePath
@return {Object|undefined} | [
"Return",
"an",
"article",
"by",
"its",
"path"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/website/createTemplateEngine.js#L75-L80 |
1,073 | GitbookIO/gitbook | lib/output/website/createTemplateEngine.js | getPageByPath | function getPageByPath(filePath) {
var page = output.getPage(filePath);
if (!page) return undefined;
return JSONUtils.encodePage(page, summary);
} | javascript | function getPageByPath(filePath) {
var page = output.getPage(filePath);
if (!page) return undefined;
return JSONUtils.encodePage(page, summary);
} | [
"function",
"getPageByPath",
"(",
"filePath",
")",
"{",
"var",
"page",
"=",
"output",
".",
"getPage",
"(",
"filePath",
")",
";",
"if",
"(",
"!",
"page",
")",
"return",
"undefined",
";",
"return",
"JSONUtils",
".",
"encodePage",
"(",
"page",
",",
"summary",
")",
";",
"}"
] | Return a page by its path
@param {String} filePath
@return {Object|undefined} | [
"Return",
"a",
"page",
"by",
"its",
"path"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/website/createTemplateEngine.js#L87-L92 |
1,074 | GitbookIO/gitbook | lib/modifiers/summary/indexPartLevels.js | indexPartLevels | function indexPartLevels(part, index) {
var baseLevel = String(index + 1);
var articles = part.getArticles();
articles = articles.map(function(inner, i) {
return indexArticleLevels(inner, baseLevel + '.' + (i + 1));
});
return part.merge({
level: baseLevel,
articles: articles
});
} | javascript | function indexPartLevels(part, index) {
var baseLevel = String(index + 1);
var articles = part.getArticles();
articles = articles.map(function(inner, i) {
return indexArticleLevels(inner, baseLevel + '.' + (i + 1));
});
return part.merge({
level: baseLevel,
articles: articles
});
} | [
"function",
"indexPartLevels",
"(",
"part",
",",
"index",
")",
"{",
"var",
"baseLevel",
"=",
"String",
"(",
"index",
"+",
"1",
")",
";",
"var",
"articles",
"=",
"part",
".",
"getArticles",
"(",
")",
";",
"articles",
"=",
"articles",
".",
"map",
"(",
"function",
"(",
"inner",
",",
"i",
")",
"{",
"return",
"indexArticleLevels",
"(",
"inner",
",",
"baseLevel",
"+",
"'.'",
"+",
"(",
"i",
"+",
"1",
")",
")",
";",
"}",
")",
";",
"return",
"part",
".",
"merge",
"(",
"{",
"level",
":",
"baseLevel",
",",
"articles",
":",
"articles",
"}",
")",
";",
"}"
] | Index levels in a part
@param {Part}
@param {Number} index
@return {Part} | [
"Index",
"levels",
"in",
"a",
"part"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/modifiers/summary/indexPartLevels.js#L10-L22 |
1,075 | GitbookIO/gitbook | lib/utils/path.js | setExtension | function setExtension(filename, ext) {
return path.join(
path.dirname(filename),
path.basename(filename, path.extname(filename)) + ext
);
} | javascript | function setExtension(filename, ext) {
return path.join(
path.dirname(filename),
path.basename(filename, path.extname(filename)) + ext
);
} | [
"function",
"setExtension",
"(",
"filename",
",",
"ext",
")",
"{",
"return",
"path",
".",
"join",
"(",
"path",
".",
"dirname",
"(",
"filename",
")",
",",
"path",
".",
"basename",
"(",
"filename",
",",
"path",
".",
"extname",
"(",
"filename",
")",
")",
"+",
"ext",
")",
";",
"}"
] | Chnage extension of a file | [
"Chnage",
"extension",
"of",
"a",
"file"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/utils/path.js#L51-L56 |
1,076 | GitbookIO/gitbook | lib/output/generateAssets.js | generateAssets | function generateAssets(generator, output) {
var assets = output.getAssets();
var logger = output.getLogger();
// Is generator ignoring assets?
if (!generator.onAsset) {
return Promise(output);
}
return Promise.reduce(assets, function(out, assetFile) {
logger.debug.ln('copy asset "' + assetFile + '"');
return generator.onAsset(out, assetFile);
}, output);
} | javascript | function generateAssets(generator, output) {
var assets = output.getAssets();
var logger = output.getLogger();
// Is generator ignoring assets?
if (!generator.onAsset) {
return Promise(output);
}
return Promise.reduce(assets, function(out, assetFile) {
logger.debug.ln('copy asset "' + assetFile + '"');
return generator.onAsset(out, assetFile);
}, output);
} | [
"function",
"generateAssets",
"(",
"generator",
",",
"output",
")",
"{",
"var",
"assets",
"=",
"output",
".",
"getAssets",
"(",
")",
";",
"var",
"logger",
"=",
"output",
".",
"getLogger",
"(",
")",
";",
"// Is generator ignoring assets?",
"if",
"(",
"!",
"generator",
".",
"onAsset",
")",
"{",
"return",
"Promise",
"(",
"output",
")",
";",
"}",
"return",
"Promise",
".",
"reduce",
"(",
"assets",
",",
"function",
"(",
"out",
",",
"assetFile",
")",
"{",
"logger",
".",
"debug",
".",
"ln",
"(",
"'copy asset \"'",
"+",
"assetFile",
"+",
"'\"'",
")",
";",
"return",
"generator",
".",
"onAsset",
"(",
"out",
",",
"assetFile",
")",
";",
"}",
",",
"output",
")",
";",
"}"
] | Output all assets using a generator
@param {Generator} generator
@param {Output} output
@return {Promise<Output>} | [
"Output",
"all",
"assets",
"using",
"a",
"generator"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/generateAssets.js#L10-L24 |
1,077 | GitbookIO/gitbook | lib/output/modifiers/fetchRemoteImages.js | fetchRemoteImages | function fetchRemoteImages(rootFolder, currentFile, $) {
var currentDirectory = path.dirname(currentFile);
return editHTMLElement($, 'img', function($img) {
var src = $img.attr('src');
var extension = path.extname(src);
if (!LocationUtils.isExternal(src)) {
return;
}
// We avoid generating twice the same PNG
var hash = crc.crc32(src).toString(16);
var fileName = hash + extension;
var filePath = path.join(rootFolder, fileName);
return fs.assertFile(filePath, function() {
return fs.download(src, filePath);
})
.then(function() {
// Convert to relative
src = LocationUtils.relative(currentDirectory, fileName);
$img.replaceWith('<img src="' + src + '" />');
});
});
} | javascript | function fetchRemoteImages(rootFolder, currentFile, $) {
var currentDirectory = path.dirname(currentFile);
return editHTMLElement($, 'img', function($img) {
var src = $img.attr('src');
var extension = path.extname(src);
if (!LocationUtils.isExternal(src)) {
return;
}
// We avoid generating twice the same PNG
var hash = crc.crc32(src).toString(16);
var fileName = hash + extension;
var filePath = path.join(rootFolder, fileName);
return fs.assertFile(filePath, function() {
return fs.download(src, filePath);
})
.then(function() {
// Convert to relative
src = LocationUtils.relative(currentDirectory, fileName);
$img.replaceWith('<img src="' + src + '" />');
});
});
} | [
"function",
"fetchRemoteImages",
"(",
"rootFolder",
",",
"currentFile",
",",
"$",
")",
"{",
"var",
"currentDirectory",
"=",
"path",
".",
"dirname",
"(",
"currentFile",
")",
";",
"return",
"editHTMLElement",
"(",
"$",
",",
"'img'",
",",
"function",
"(",
"$img",
")",
"{",
"var",
"src",
"=",
"$img",
".",
"attr",
"(",
"'src'",
")",
";",
"var",
"extension",
"=",
"path",
".",
"extname",
"(",
"src",
")",
";",
"if",
"(",
"!",
"LocationUtils",
".",
"isExternal",
"(",
"src",
")",
")",
"{",
"return",
";",
"}",
"// We avoid generating twice the same PNG",
"var",
"hash",
"=",
"crc",
".",
"crc32",
"(",
"src",
")",
".",
"toString",
"(",
"16",
")",
";",
"var",
"fileName",
"=",
"hash",
"+",
"extension",
";",
"var",
"filePath",
"=",
"path",
".",
"join",
"(",
"rootFolder",
",",
"fileName",
")",
";",
"return",
"fs",
".",
"assertFile",
"(",
"filePath",
",",
"function",
"(",
")",
"{",
"return",
"fs",
".",
"download",
"(",
"src",
",",
"filePath",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"// Convert to relative",
"src",
"=",
"LocationUtils",
".",
"relative",
"(",
"currentDirectory",
",",
"fileName",
")",
";",
"$img",
".",
"replaceWith",
"(",
"'<img src=\"'",
"+",
"src",
"+",
"'\" />'",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Fetch all remote images
@param {String} rootFolder
@param {String} currentFile
@param {HTMLDom} $
@return {Promise} | [
"Fetch",
"all",
"remote",
"images"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/modifiers/fetchRemoteImages.js#L16-L42 |
1,078 | GitbookIO/gitbook | lib/utils/images.js | convertSVGToPNG | function convertSVGToPNG(source, dest, options) {
if (!fs.existsSync(source)) return Promise.reject(new error.FileNotFoundError({ filename: source }));
return command.spawn('svgexport', [source, dest])
.fail(function(err) {
if (err.code == 'ENOENT') {
err = error.RequireInstallError({
cmd: 'svgexport',
install: 'Install it using: "npm install svgexport -g"'
});
}
throw err;
})
.then(function() {
if (fs.existsSync(dest)) return;
throw new Error('Error converting '+source+' into '+dest);
});
} | javascript | function convertSVGToPNG(source, dest, options) {
if (!fs.existsSync(source)) return Promise.reject(new error.FileNotFoundError({ filename: source }));
return command.spawn('svgexport', [source, dest])
.fail(function(err) {
if (err.code == 'ENOENT') {
err = error.RequireInstallError({
cmd: 'svgexport',
install: 'Install it using: "npm install svgexport -g"'
});
}
throw err;
})
.then(function() {
if (fs.existsSync(dest)) return;
throw new Error('Error converting '+source+' into '+dest);
});
} | [
"function",
"convertSVGToPNG",
"(",
"source",
",",
"dest",
",",
"options",
")",
"{",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"source",
")",
")",
"return",
"Promise",
".",
"reject",
"(",
"new",
"error",
".",
"FileNotFoundError",
"(",
"{",
"filename",
":",
"source",
"}",
")",
")",
";",
"return",
"command",
".",
"spawn",
"(",
"'svgexport'",
",",
"[",
"source",
",",
"dest",
"]",
")",
".",
"fail",
"(",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
".",
"code",
"==",
"'ENOENT'",
")",
"{",
"err",
"=",
"error",
".",
"RequireInstallError",
"(",
"{",
"cmd",
":",
"'svgexport'",
",",
"install",
":",
"'Install it using: \"npm install svgexport -g\"'",
"}",
")",
";",
"}",
"throw",
"err",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"dest",
")",
")",
"return",
";",
"throw",
"new",
"Error",
"(",
"'Error converting '",
"+",
"source",
"+",
"' into '",
"+",
"dest",
")",
";",
"}",
")",
";",
"}"
] | Convert a svg file to a pmg | [
"Convert",
"a",
"svg",
"file",
"to",
"a",
"pmg"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/utils/images.js#L7-L25 |
1,079 | GitbookIO/gitbook | lib/utils/images.js | convertSVGBufferToPNG | function convertSVGBufferToPNG(buf, dest) {
// Create a temporary SVG file to convert
return fs.tmpFile({
postfix: '.svg'
})
.then(function(tmpSvg) {
return fs.writeFile(tmpSvg, buf)
.then(function() {
return convertSVGToPNG(tmpSvg, dest);
});
});
} | javascript | function convertSVGBufferToPNG(buf, dest) {
// Create a temporary SVG file to convert
return fs.tmpFile({
postfix: '.svg'
})
.then(function(tmpSvg) {
return fs.writeFile(tmpSvg, buf)
.then(function() {
return convertSVGToPNG(tmpSvg, dest);
});
});
} | [
"function",
"convertSVGBufferToPNG",
"(",
"buf",
",",
"dest",
")",
"{",
"// Create a temporary SVG file to convert",
"return",
"fs",
".",
"tmpFile",
"(",
"{",
"postfix",
":",
"'.svg'",
"}",
")",
".",
"then",
"(",
"function",
"(",
"tmpSvg",
")",
"{",
"return",
"fs",
".",
"writeFile",
"(",
"tmpSvg",
",",
"buf",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"convertSVGToPNG",
"(",
"tmpSvg",
",",
"dest",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Convert a svg buffer to a png file | [
"Convert",
"a",
"svg",
"buffer",
"to",
"a",
"png",
"file"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/utils/images.js#L28-L39 |
1,080 | GitbookIO/gitbook | lib/output/website/prepareResources.js | prepareResources | function prepareResources(output) {
var plugins = output.getPlugins();
var options = output.getOptions();
var type = options.get('prefix');
var state = output.getState();
var context = Api.encodeGlobal(output);
var result = Immutable.Map();
return Promise.forEach(plugins, function(plugin) {
var pluginResources = plugin.getResources(type);
return Promise()
.then(function() {
// Apply resources if is a function
if (is.fn(pluginResources)) {
return Promise()
.then(pluginResources.bind(context));
}
else {
return pluginResources;
}
})
.then(function(resources) {
result = result.set(plugin.getName(), Immutable.Map(resources));
});
})
.then(function() {
// Set output resources
state = state.merge({
resources: result
});
output = output.merge({
state: state
});
return output;
});
} | javascript | function prepareResources(output) {
var plugins = output.getPlugins();
var options = output.getOptions();
var type = options.get('prefix');
var state = output.getState();
var context = Api.encodeGlobal(output);
var result = Immutable.Map();
return Promise.forEach(plugins, function(plugin) {
var pluginResources = plugin.getResources(type);
return Promise()
.then(function() {
// Apply resources if is a function
if (is.fn(pluginResources)) {
return Promise()
.then(pluginResources.bind(context));
}
else {
return pluginResources;
}
})
.then(function(resources) {
result = result.set(plugin.getName(), Immutable.Map(resources));
});
})
.then(function() {
// Set output resources
state = state.merge({
resources: result
});
output = output.merge({
state: state
});
return output;
});
} | [
"function",
"prepareResources",
"(",
"output",
")",
"{",
"var",
"plugins",
"=",
"output",
".",
"getPlugins",
"(",
")",
";",
"var",
"options",
"=",
"output",
".",
"getOptions",
"(",
")",
";",
"var",
"type",
"=",
"options",
".",
"get",
"(",
"'prefix'",
")",
";",
"var",
"state",
"=",
"output",
".",
"getState",
"(",
")",
";",
"var",
"context",
"=",
"Api",
".",
"encodeGlobal",
"(",
"output",
")",
";",
"var",
"result",
"=",
"Immutable",
".",
"Map",
"(",
")",
";",
"return",
"Promise",
".",
"forEach",
"(",
"plugins",
",",
"function",
"(",
"plugin",
")",
"{",
"var",
"pluginResources",
"=",
"plugin",
".",
"getResources",
"(",
"type",
")",
";",
"return",
"Promise",
"(",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"// Apply resources if is a function",
"if",
"(",
"is",
".",
"fn",
"(",
"pluginResources",
")",
")",
"{",
"return",
"Promise",
"(",
")",
".",
"then",
"(",
"pluginResources",
".",
"bind",
"(",
"context",
")",
")",
";",
"}",
"else",
"{",
"return",
"pluginResources",
";",
"}",
"}",
")",
".",
"then",
"(",
"function",
"(",
"resources",
")",
"{",
"result",
"=",
"result",
".",
"set",
"(",
"plugin",
".",
"getName",
"(",
")",
",",
"Immutable",
".",
"Map",
"(",
"resources",
")",
")",
";",
"}",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"// Set output resources",
"state",
"=",
"state",
".",
"merge",
"(",
"{",
"resources",
":",
"result",
"}",
")",
";",
"output",
"=",
"output",
".",
"merge",
"(",
"{",
"state",
":",
"state",
"}",
")",
";",
"return",
"output",
";",
"}",
")",
";",
"}"
] | Prepare plugins resources, add all output corresponding type resources
@param {Output}
@return {Promise<Output>} | [
"Prepare",
"plugins",
"resources",
"add",
"all",
"output",
"corresponding",
"type",
"resources"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/website/prepareResources.js#L13-L52 |
1,081 | GitbookIO/gitbook | lib/plugins/listDepsForBook.js | listDepsForBook | function listDepsForBook(book) {
var config = book.getConfig();
var plugins = config.getPluginDependencies();
return listDependencies(plugins);
} | javascript | function listDepsForBook(book) {
var config = book.getConfig();
var plugins = config.getPluginDependencies();
return listDependencies(plugins);
} | [
"function",
"listDepsForBook",
"(",
"book",
")",
"{",
"var",
"config",
"=",
"book",
".",
"getConfig",
"(",
")",
";",
"var",
"plugins",
"=",
"config",
".",
"getPluginDependencies",
"(",
")",
";",
"return",
"listDependencies",
"(",
"plugins",
")",
";",
"}"
] | List all plugin requirements for a book.
It can be different from the final list of plugins,
since plugins can have their own dependencies
@param {Book}
@return {List<PluginDependency>} | [
"List",
"all",
"plugin",
"requirements",
"for",
"a",
"book",
".",
"It",
"can",
"be",
"different",
"from",
"the",
"final",
"list",
"of",
"plugins",
"since",
"plugins",
"can",
"have",
"their",
"own",
"dependencies"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/plugins/listDepsForBook.js#L11-L16 |
1,082 | GitbookIO/gitbook | lib/output/getModifiers.js | getModifiers | function getModifiers(output, page) {
var book = output.getBook();
var plugins = output.getPlugins();
var glossary = book.getGlossary();
var file = page.getFile();
// Glossary entries
var entries = glossary.getEntries();
var glossaryFile = glossary.getFile();
var glossaryFilename = fileToOutput(output, glossaryFile.getPath());
// Current file path
var currentFilePath = file.getPath();
// Get TemplateBlock for highlighting
var blocks = Plugins.listBlocks(plugins);
var code = blocks.get(CODEBLOCK) || defaultBlocks.get(CODEBLOCK);
// Current context
var context = Api.encodeGlobal(output);
return [
// Normalize IDs on headings
Modifiers.addHeadingId,
// Annotate text with glossary entries
Modifiers.annotateText.bind(null, entries, glossaryFilename),
// Resolve images
Modifiers.resolveImages.bind(null, currentFilePath),
// Resolve links (.md -> .html)
Modifiers.resolveLinks.bind(null,
currentFilePath,
resolveFileToURL.bind(null, output)
),
// Highlight code blocks using "code" block
Modifiers.highlightCode.bind(null, function(lang, source) {
return Promise(code.applyBlock({
body: source,
kwargs: {
language: lang
}
}, context))
.then(function(result) {
if (result.html === false) {
return { text: result.body };
} else {
return { html: result.body };
}
});
})
];
} | javascript | function getModifiers(output, page) {
var book = output.getBook();
var plugins = output.getPlugins();
var glossary = book.getGlossary();
var file = page.getFile();
// Glossary entries
var entries = glossary.getEntries();
var glossaryFile = glossary.getFile();
var glossaryFilename = fileToOutput(output, glossaryFile.getPath());
// Current file path
var currentFilePath = file.getPath();
// Get TemplateBlock for highlighting
var blocks = Plugins.listBlocks(plugins);
var code = blocks.get(CODEBLOCK) || defaultBlocks.get(CODEBLOCK);
// Current context
var context = Api.encodeGlobal(output);
return [
// Normalize IDs on headings
Modifiers.addHeadingId,
// Annotate text with glossary entries
Modifiers.annotateText.bind(null, entries, glossaryFilename),
// Resolve images
Modifiers.resolveImages.bind(null, currentFilePath),
// Resolve links (.md -> .html)
Modifiers.resolveLinks.bind(null,
currentFilePath,
resolveFileToURL.bind(null, output)
),
// Highlight code blocks using "code" block
Modifiers.highlightCode.bind(null, function(lang, source) {
return Promise(code.applyBlock({
body: source,
kwargs: {
language: lang
}
}, context))
.then(function(result) {
if (result.html === false) {
return { text: result.body };
} else {
return { html: result.body };
}
});
})
];
} | [
"function",
"getModifiers",
"(",
"output",
",",
"page",
")",
"{",
"var",
"book",
"=",
"output",
".",
"getBook",
"(",
")",
";",
"var",
"plugins",
"=",
"output",
".",
"getPlugins",
"(",
")",
";",
"var",
"glossary",
"=",
"book",
".",
"getGlossary",
"(",
")",
";",
"var",
"file",
"=",
"page",
".",
"getFile",
"(",
")",
";",
"// Glossary entries",
"var",
"entries",
"=",
"glossary",
".",
"getEntries",
"(",
")",
";",
"var",
"glossaryFile",
"=",
"glossary",
".",
"getFile",
"(",
")",
";",
"var",
"glossaryFilename",
"=",
"fileToOutput",
"(",
"output",
",",
"glossaryFile",
".",
"getPath",
"(",
")",
")",
";",
"// Current file path",
"var",
"currentFilePath",
"=",
"file",
".",
"getPath",
"(",
")",
";",
"// Get TemplateBlock for highlighting",
"var",
"blocks",
"=",
"Plugins",
".",
"listBlocks",
"(",
"plugins",
")",
";",
"var",
"code",
"=",
"blocks",
".",
"get",
"(",
"CODEBLOCK",
")",
"||",
"defaultBlocks",
".",
"get",
"(",
"CODEBLOCK",
")",
";",
"// Current context",
"var",
"context",
"=",
"Api",
".",
"encodeGlobal",
"(",
"output",
")",
";",
"return",
"[",
"// Normalize IDs on headings",
"Modifiers",
".",
"addHeadingId",
",",
"// Annotate text with glossary entries",
"Modifiers",
".",
"annotateText",
".",
"bind",
"(",
"null",
",",
"entries",
",",
"glossaryFilename",
")",
",",
"// Resolve images",
"Modifiers",
".",
"resolveImages",
".",
"bind",
"(",
"null",
",",
"currentFilePath",
")",
",",
"// Resolve links (.md -> .html)",
"Modifiers",
".",
"resolveLinks",
".",
"bind",
"(",
"null",
",",
"currentFilePath",
",",
"resolveFileToURL",
".",
"bind",
"(",
"null",
",",
"output",
")",
")",
",",
"// Highlight code blocks using \"code\" block",
"Modifiers",
".",
"highlightCode",
".",
"bind",
"(",
"null",
",",
"function",
"(",
"lang",
",",
"source",
")",
"{",
"return",
"Promise",
"(",
"code",
".",
"applyBlock",
"(",
"{",
"body",
":",
"source",
",",
"kwargs",
":",
"{",
"language",
":",
"lang",
"}",
"}",
",",
"context",
")",
")",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"if",
"(",
"result",
".",
"html",
"===",
"false",
")",
"{",
"return",
"{",
"text",
":",
"result",
".",
"body",
"}",
";",
"}",
"else",
"{",
"return",
"{",
"html",
":",
"result",
".",
"body",
"}",
";",
"}",
"}",
")",
";",
"}",
")",
"]",
";",
"}"
] | Return default modifier to prepare a page for
rendering.
@return {Array<Modifier>} | [
"Return",
"default",
"modifier",
"to",
"prepare",
"a",
"page",
"for",
"rendering",
"."
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/getModifiers.js#L17-L71 |
1,083 | GitbookIO/gitbook | lib/modifiers/summary/removePart.js | removePart | function removePart(summary, index) {
var parts = summary.getParts().remove(index);
return indexLevels(summary.set('parts', parts));
} | javascript | function removePart(summary, index) {
var parts = summary.getParts().remove(index);
return indexLevels(summary.set('parts', parts));
} | [
"function",
"removePart",
"(",
"summary",
",",
"index",
")",
"{",
"var",
"parts",
"=",
"summary",
".",
"getParts",
"(",
")",
".",
"remove",
"(",
"index",
")",
";",
"return",
"indexLevels",
"(",
"summary",
".",
"set",
"(",
"'parts'",
",",
"parts",
")",
")",
";",
"}"
] | Remove a part at given index
@param {Summary} summary
@param {Number|} index
@return {Summary} | [
"Remove",
"a",
"part",
"at",
"given",
"index"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/modifiers/summary/removePart.js#L10-L13 |
1,084 | GitbookIO/gitbook | lib/api/encodeGlobal.js | function(filePath) {
var page = output.getPage(filePath);
if (!page) return undefined;
return encodePage(output, page);
} | javascript | function(filePath) {
var page = output.getPage(filePath);
if (!page) return undefined;
return encodePage(output, page);
} | [
"function",
"(",
"filePath",
")",
"{",
"var",
"page",
"=",
"output",
".",
"getPage",
"(",
"filePath",
")",
";",
"if",
"(",
"!",
"page",
")",
"return",
"undefined",
";",
"return",
"encodePage",
"(",
"output",
",",
"page",
")",
";",
"}"
] | Resolve a page by it path
@param {String} filePath
@return {String} | [
"Resolve",
"a",
"page",
"by",
"it",
"path"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/api/encodeGlobal.js#L92-L97 |
|
1,085 | GitbookIO/gitbook | lib/api/encodeGlobal.js | function(name, blockData) {
var block = blocks.get(name) || defaultBlocks.get(name);
return Promise(block.applyBlock(blockData, result));
} | javascript | function(name, blockData) {
var block = blocks.get(name) || defaultBlocks.get(name);
return Promise(block.applyBlock(blockData, result));
} | [
"function",
"(",
"name",
",",
"blockData",
")",
"{",
"var",
"block",
"=",
"blocks",
".",
"get",
"(",
"name",
")",
"||",
"defaultBlocks",
".",
"get",
"(",
"name",
")",
";",
"return",
"Promise",
"(",
"block",
".",
"applyBlock",
"(",
"blockData",
",",
"result",
")",
")",
";",
"}"
] | Apply a templating block and returns its result
@param {String} name
@param {Object} blockData
@return {Promise|Object} | [
"Apply",
"a",
"templating",
"block",
"and",
"returns",
"its",
"result"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/api/encodeGlobal.js#L135-L138 |
|
1,086 | GitbookIO/gitbook | lib/api/encodeGlobal.js | function(fileName, content) {
return Promise()
.then(function() {
var filePath = PathUtils.resolveInRoot(outputFolder, fileName);
return fs.exists(filePath);
});
} | javascript | function(fileName, content) {
return Promise()
.then(function() {
var filePath = PathUtils.resolveInRoot(outputFolder, fileName);
return fs.exists(filePath);
});
} | [
"function",
"(",
"fileName",
",",
"content",
")",
"{",
"return",
"Promise",
"(",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"var",
"filePath",
"=",
"PathUtils",
".",
"resolveInRoot",
"(",
"outputFolder",
",",
"fileName",
")",
";",
"return",
"fs",
".",
"exists",
"(",
"filePath",
")",
";",
"}",
")",
";",
"}"
] | Check that a file exists.
@param {String} fileName
@return {Promise} | [
"Check",
"that",
"a",
"file",
"exists",
"."
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/api/encodeGlobal.js#L180-L187 |
|
1,087 | GitbookIO/gitbook | lib/api/encodeGlobal.js | function(fileName, content) {
return Promise()
.then(function() {
var filePath = PathUtils.resolveInRoot(outputFolder, fileName);
return fs.ensureFile(filePath)
.then(function() {
return fs.writeFile(filePath, content);
});
});
} | javascript | function(fileName, content) {
return Promise()
.then(function() {
var filePath = PathUtils.resolveInRoot(outputFolder, fileName);
return fs.ensureFile(filePath)
.then(function() {
return fs.writeFile(filePath, content);
});
});
} | [
"function",
"(",
"fileName",
",",
"content",
")",
"{",
"return",
"Promise",
"(",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"var",
"filePath",
"=",
"PathUtils",
".",
"resolveInRoot",
"(",
"outputFolder",
",",
"fileName",
")",
";",
"return",
"fs",
".",
"ensureFile",
"(",
"filePath",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"fs",
".",
"writeFile",
"(",
"filePath",
",",
"content",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Write a file to the output folder,
It creates the required folder
@param {String} fileName
@param {Buffer} content
@return {Promise} | [
"Write",
"a",
"file",
"to",
"the",
"output",
"folder",
"It",
"creates",
"the",
"required",
"folder"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/api/encodeGlobal.js#L197-L207 |
|
1,088 | GitbookIO/gitbook | lib/api/encodeGlobal.js | function(inputFile, outputFile, content) {
return Promise()
.then(function() {
var outputFilePath = PathUtils.resolveInRoot(outputFolder, outputFile);
return fs.ensureFile(outputFilePath)
.then(function() {
return fs.copy(inputFile, outputFilePath);
});
});
} | javascript | function(inputFile, outputFile, content) {
return Promise()
.then(function() {
var outputFilePath = PathUtils.resolveInRoot(outputFolder, outputFile);
return fs.ensureFile(outputFilePath)
.then(function() {
return fs.copy(inputFile, outputFilePath);
});
});
} | [
"function",
"(",
"inputFile",
",",
"outputFile",
",",
"content",
")",
"{",
"return",
"Promise",
"(",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"var",
"outputFilePath",
"=",
"PathUtils",
".",
"resolveInRoot",
"(",
"outputFolder",
",",
"outputFile",
")",
";",
"return",
"fs",
".",
"ensureFile",
"(",
"outputFilePath",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"fs",
".",
"copy",
"(",
"inputFile",
",",
"outputFilePath",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Copy a file to the output folder
It creates the required folder.
@param {String} inputFile
@param {String} outputFile
@param {Buffer} content
@return {Promise} | [
"Copy",
"a",
"file",
"to",
"the",
"output",
"folder",
"It",
"creates",
"the",
"required",
"folder",
"."
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/api/encodeGlobal.js#L218-L228 |
|
1,089 | GitbookIO/gitbook | lib/output/website/onAsset.js | onAsset | function onAsset(output, asset) {
var book = output.getBook();
var options = output.getOptions();
var bookFS = book.getContentFS();
var outputFolder = options.get('root');
var outputPath = path.resolve(outputFolder, asset);
return fs.ensureFile(outputPath)
.then(function() {
return bookFS.readAsStream(asset)
.then(function(stream) {
return fs.writeStream(outputPath, stream);
});
})
.thenResolve(output);
} | javascript | function onAsset(output, asset) {
var book = output.getBook();
var options = output.getOptions();
var bookFS = book.getContentFS();
var outputFolder = options.get('root');
var outputPath = path.resolve(outputFolder, asset);
return fs.ensureFile(outputPath)
.then(function() {
return bookFS.readAsStream(asset)
.then(function(stream) {
return fs.writeStream(outputPath, stream);
});
})
.thenResolve(output);
} | [
"function",
"onAsset",
"(",
"output",
",",
"asset",
")",
"{",
"var",
"book",
"=",
"output",
".",
"getBook",
"(",
")",
";",
"var",
"options",
"=",
"output",
".",
"getOptions",
"(",
")",
";",
"var",
"bookFS",
"=",
"book",
".",
"getContentFS",
"(",
")",
";",
"var",
"outputFolder",
"=",
"options",
".",
"get",
"(",
"'root'",
")",
";",
"var",
"outputPath",
"=",
"path",
".",
"resolve",
"(",
"outputFolder",
",",
"asset",
")",
";",
"return",
"fs",
".",
"ensureFile",
"(",
"outputPath",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"bookFS",
".",
"readAsStream",
"(",
"asset",
")",
".",
"then",
"(",
"function",
"(",
"stream",
")",
"{",
"return",
"fs",
".",
"writeStream",
"(",
"outputPath",
",",
"stream",
")",
";",
"}",
")",
";",
"}",
")",
".",
"thenResolve",
"(",
"output",
")",
";",
"}"
] | Copy an asset to the output folder
@param {Output} output
@param {Page} page | [
"Copy",
"an",
"asset",
"to",
"the",
"output",
"folder"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/website/onAsset.js#L10-L26 |
1,090 | GitbookIO/gitbook | lib/plugins/listResources.js | listResources | function listResources(plugins, resources) {
return plugins.reduce(function(result, plugin) {
var npmId = plugin.getNpmID();
var pluginResources = resources.get(plugin.getName());
PLUGIN_RESOURCES.forEach(function(resourceType) {
var assets = pluginResources.get(resourceType);
if (!assets) return;
var list = result.get(resourceType) || Immutable.List();
assets = assets.map(function(assetFile) {
if (LocationUtils.isExternal(assetFile)) {
return {
url: assetFile
};
} else {
return {
path: LocationUtils.normalize(path.join(npmId, assetFile))
};
}
});
list = list.concat(assets);
result = result.set(resourceType, list);
});
return result;
}, Immutable.Map());
} | javascript | function listResources(plugins, resources) {
return plugins.reduce(function(result, plugin) {
var npmId = plugin.getNpmID();
var pluginResources = resources.get(plugin.getName());
PLUGIN_RESOURCES.forEach(function(resourceType) {
var assets = pluginResources.get(resourceType);
if (!assets) return;
var list = result.get(resourceType) || Immutable.List();
assets = assets.map(function(assetFile) {
if (LocationUtils.isExternal(assetFile)) {
return {
url: assetFile
};
} else {
return {
path: LocationUtils.normalize(path.join(npmId, assetFile))
};
}
});
list = list.concat(assets);
result = result.set(resourceType, list);
});
return result;
}, Immutable.Map());
} | [
"function",
"listResources",
"(",
"plugins",
",",
"resources",
")",
"{",
"return",
"plugins",
".",
"reduce",
"(",
"function",
"(",
"result",
",",
"plugin",
")",
"{",
"var",
"npmId",
"=",
"plugin",
".",
"getNpmID",
"(",
")",
";",
"var",
"pluginResources",
"=",
"resources",
".",
"get",
"(",
"plugin",
".",
"getName",
"(",
")",
")",
";",
"PLUGIN_RESOURCES",
".",
"forEach",
"(",
"function",
"(",
"resourceType",
")",
"{",
"var",
"assets",
"=",
"pluginResources",
".",
"get",
"(",
"resourceType",
")",
";",
"if",
"(",
"!",
"assets",
")",
"return",
";",
"var",
"list",
"=",
"result",
".",
"get",
"(",
"resourceType",
")",
"||",
"Immutable",
".",
"List",
"(",
")",
";",
"assets",
"=",
"assets",
".",
"map",
"(",
"function",
"(",
"assetFile",
")",
"{",
"if",
"(",
"LocationUtils",
".",
"isExternal",
"(",
"assetFile",
")",
")",
"{",
"return",
"{",
"url",
":",
"assetFile",
"}",
";",
"}",
"else",
"{",
"return",
"{",
"path",
":",
"LocationUtils",
".",
"normalize",
"(",
"path",
".",
"join",
"(",
"npmId",
",",
"assetFile",
")",
")",
"}",
";",
"}",
"}",
")",
";",
"list",
"=",
"list",
".",
"concat",
"(",
"assets",
")",
";",
"result",
"=",
"result",
".",
"set",
"(",
"resourceType",
",",
"list",
")",
";",
"}",
")",
";",
"return",
"result",
";",
"}",
",",
"Immutable",
".",
"Map",
"(",
")",
")",
";",
"}"
] | List all resources from a list of plugins
@param {OrderedMap<String:Plugin>}
@param {String} type
@return {Map<String:List<{url, path}>} | [
"List",
"all",
"resources",
"from",
"a",
"list",
"of",
"plugins"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/plugins/listResources.js#L14-L43 |
1,091 | GitbookIO/gitbook | lib/utils/error.js | enforce | function enforce(err) {
if (is.string(err)) err = new Error(err);
err.message = err.message.replace(/^Error: /, '');
return err;
} | javascript | function enforce(err) {
if (is.string(err)) err = new Error(err);
err.message = err.message.replace(/^Error: /, '');
return err;
} | [
"function",
"enforce",
"(",
"err",
")",
"{",
"if",
"(",
"is",
".",
"string",
"(",
"err",
")",
")",
"err",
"=",
"new",
"Error",
"(",
"err",
")",
";",
"err",
".",
"message",
"=",
"err",
".",
"message",
".",
"replace",
"(",
"/",
"^Error: ",
"/",
",",
"''",
")",
";",
"return",
"err",
";",
"}"
] | Enforce as an Error object, and cleanup message | [
"Enforce",
"as",
"an",
"Error",
"object",
"and",
"cleanup",
"message"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/utils/error.js#L8-L13 |
1,092 | GitbookIO/gitbook | lib/output/ebook/getCoverPath.js | getCoverPath | function getCoverPath(output) {
var outputRoot = output.getRoot();
var book = output.getBook();
var config = book.getConfig();
var coverName = config.getValue('cover', 'cover.jpg');
// Resolve to absolute
var cover = fs.pickFile(outputRoot, coverName);
if (cover) {
return cover;
}
// Multilingual? try parent folder
if (book.isLanguageBook()) {
cover = fs.pickFile(path.join(outputRoot, '..'), coverName);
}
return cover;
} | javascript | function getCoverPath(output) {
var outputRoot = output.getRoot();
var book = output.getBook();
var config = book.getConfig();
var coverName = config.getValue('cover', 'cover.jpg');
// Resolve to absolute
var cover = fs.pickFile(outputRoot, coverName);
if (cover) {
return cover;
}
// Multilingual? try parent folder
if (book.isLanguageBook()) {
cover = fs.pickFile(path.join(outputRoot, '..'), coverName);
}
return cover;
} | [
"function",
"getCoverPath",
"(",
"output",
")",
"{",
"var",
"outputRoot",
"=",
"output",
".",
"getRoot",
"(",
")",
";",
"var",
"book",
"=",
"output",
".",
"getBook",
"(",
")",
";",
"var",
"config",
"=",
"book",
".",
"getConfig",
"(",
")",
";",
"var",
"coverName",
"=",
"config",
".",
"getValue",
"(",
"'cover'",
",",
"'cover.jpg'",
")",
";",
"// Resolve to absolute",
"var",
"cover",
"=",
"fs",
".",
"pickFile",
"(",
"outputRoot",
",",
"coverName",
")",
";",
"if",
"(",
"cover",
")",
"{",
"return",
"cover",
";",
"}",
"// Multilingual? try parent folder",
"if",
"(",
"book",
".",
"isLanguageBook",
"(",
")",
")",
"{",
"cover",
"=",
"fs",
".",
"pickFile",
"(",
"path",
".",
"join",
"(",
"outputRoot",
",",
"'..'",
")",
",",
"coverName",
")",
";",
"}",
"return",
"cover",
";",
"}"
] | Resolve path to cover file to use
@param {Output}
@return {String} | [
"Resolve",
"path",
"to",
"cover",
"file",
"to",
"use"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/ebook/getCoverPath.js#L10-L28 |
1,093 | GitbookIO/gitbook | lib/parse/parseReadme.js | parseReadme | function parseReadme(book) {
var logger = book.getLogger();
return parseStructureFile(book, 'readme')
.spread(function(file, result) {
if (!file) {
throw new error.FileNotFoundError({ filename: 'README' });
}
logger.debug.ln('readme found at', file.getPath());
var readme = Readme.create(file, result);
return book.set('readme', readme);
});
} | javascript | function parseReadme(book) {
var logger = book.getLogger();
return parseStructureFile(book, 'readme')
.spread(function(file, result) {
if (!file) {
throw new error.FileNotFoundError({ filename: 'README' });
}
logger.debug.ln('readme found at', file.getPath());
var readme = Readme.create(file, result);
return book.set('readme', readme);
});
} | [
"function",
"parseReadme",
"(",
"book",
")",
"{",
"var",
"logger",
"=",
"book",
".",
"getLogger",
"(",
")",
";",
"return",
"parseStructureFile",
"(",
"book",
",",
"'readme'",
")",
".",
"spread",
"(",
"function",
"(",
"file",
",",
"result",
")",
"{",
"if",
"(",
"!",
"file",
")",
"{",
"throw",
"new",
"error",
".",
"FileNotFoundError",
"(",
"{",
"filename",
":",
"'README'",
"}",
")",
";",
"}",
"logger",
".",
"debug",
".",
"ln",
"(",
"'readme found at'",
",",
"file",
".",
"getPath",
"(",
")",
")",
";",
"var",
"readme",
"=",
"Readme",
".",
"create",
"(",
"file",
",",
"result",
")",
";",
"return",
"book",
".",
"set",
"(",
"'readme'",
",",
"readme",
")",
";",
"}",
")",
";",
"}"
] | Parse readme from book
@param {Book} book
@return {Promise<Book>} | [
"Parse",
"readme",
"from",
"book"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/parse/parseReadme.js#L12-L26 |
1,094 | GitbookIO/gitbook | lib/modifiers/summary/moveArticleAfter.js | moveArticleAfter | function moveArticleAfter(summary, origin, afterTarget) {
// Coerce to level
var originLevel = is.string(origin)? origin : origin.getLevel();
var afterTargetLevel = is.string(afterTarget)? afterTarget : afterTarget.getLevel();
var article = summary.getByLevel(originLevel);
var targetLevel = increment(afterTargetLevel);
if (targetLevel < origin) {
// Remove first
var removed = removeArticle(summary, originLevel);
// Insert then
return insertArticle(removed, article, targetLevel);
} else {
// Insert right after first
var inserted = insertArticle(summary, article, targetLevel);
// Remove old one
return removeArticle(inserted, originLevel);
}
} | javascript | function moveArticleAfter(summary, origin, afterTarget) {
// Coerce to level
var originLevel = is.string(origin)? origin : origin.getLevel();
var afterTargetLevel = is.string(afterTarget)? afterTarget : afterTarget.getLevel();
var article = summary.getByLevel(originLevel);
var targetLevel = increment(afterTargetLevel);
if (targetLevel < origin) {
// Remove first
var removed = removeArticle(summary, originLevel);
// Insert then
return insertArticle(removed, article, targetLevel);
} else {
// Insert right after first
var inserted = insertArticle(summary, article, targetLevel);
// Remove old one
return removeArticle(inserted, originLevel);
}
} | [
"function",
"moveArticleAfter",
"(",
"summary",
",",
"origin",
",",
"afterTarget",
")",
"{",
"// Coerce to level",
"var",
"originLevel",
"=",
"is",
".",
"string",
"(",
"origin",
")",
"?",
"origin",
":",
"origin",
".",
"getLevel",
"(",
")",
";",
"var",
"afterTargetLevel",
"=",
"is",
".",
"string",
"(",
"afterTarget",
")",
"?",
"afterTarget",
":",
"afterTarget",
".",
"getLevel",
"(",
")",
";",
"var",
"article",
"=",
"summary",
".",
"getByLevel",
"(",
"originLevel",
")",
";",
"var",
"targetLevel",
"=",
"increment",
"(",
"afterTargetLevel",
")",
";",
"if",
"(",
"targetLevel",
"<",
"origin",
")",
"{",
"// Remove first",
"var",
"removed",
"=",
"removeArticle",
"(",
"summary",
",",
"originLevel",
")",
";",
"// Insert then",
"return",
"insertArticle",
"(",
"removed",
",",
"article",
",",
"targetLevel",
")",
";",
"}",
"else",
"{",
"// Insert right after first",
"var",
"inserted",
"=",
"insertArticle",
"(",
"summary",
",",
"article",
",",
"targetLevel",
")",
";",
"// Remove old one",
"return",
"removeArticle",
"(",
"inserted",
",",
"originLevel",
")",
";",
"}",
"}"
] | Returns a new summary, with the an article moved after another
article. Unlike `moveArticle`, does not ensure that the article
will be found at the target's level plus one.
@param {Summary} summary
@param {String|SummaryArticle} origin
@param {String|SummaryArticle} afterTarget
@return {Summary} | [
"Returns",
"a",
"new",
"summary",
"with",
"the",
"an",
"article",
"moved",
"after",
"another",
"article",
".",
"Unlike",
"moveArticle",
"does",
"not",
"ensure",
"that",
"the",
"article",
"will",
"be",
"found",
"at",
"the",
"target",
"s",
"level",
"plus",
"one",
"."
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/modifiers/summary/moveArticleAfter.js#L15-L34 |
1,095 | GitbookIO/gitbook | lib/plugins/loadForBook.js | loadForBook | function loadForBook(book) {
var logger = book.getLogger();
// List the dependencies
var requirements = listDepsForBook(book);
// List all plugins installed in the book
return findForBook(book)
.then(function(installedMap) {
var missing = [];
var plugins = requirements.reduce(function(result, dep) {
var name = dep.getName();
var installed = installedMap.get(name);
if (installed) {
var deps = installedMap
.filter(function(plugin) {
return plugin.getParent() === name;
})
.toArray();
result = result.concat(deps);
result.push(installed);
} else {
missing.push(name);
}
return result;
}, []);
// Convert plugins list to a map
plugins = Immutable.List(plugins)
.map(function(plugin) {
return [
plugin.getName(),
plugin
];
});
plugins = Immutable.OrderedMap(plugins);
// Log state
logger.info.ln(installedMap.size + ' plugins are installed');
if (requirements.size != installedMap.size) {
logger.info.ln(requirements.size + ' explicitly listed');
}
// Verify that all plugins are present
if (missing.length > 0) {
throw new Error('Couldn\'t locate plugins "' + missing.join(', ') + '", Run \'gitbook install\' to install plugins from registry.');
}
return Promise.map(plugins, function(plugin) {
return loadPlugin(book, plugin);
});
});
} | javascript | function loadForBook(book) {
var logger = book.getLogger();
// List the dependencies
var requirements = listDepsForBook(book);
// List all plugins installed in the book
return findForBook(book)
.then(function(installedMap) {
var missing = [];
var plugins = requirements.reduce(function(result, dep) {
var name = dep.getName();
var installed = installedMap.get(name);
if (installed) {
var deps = installedMap
.filter(function(plugin) {
return plugin.getParent() === name;
})
.toArray();
result = result.concat(deps);
result.push(installed);
} else {
missing.push(name);
}
return result;
}, []);
// Convert plugins list to a map
plugins = Immutable.List(plugins)
.map(function(plugin) {
return [
plugin.getName(),
plugin
];
});
plugins = Immutable.OrderedMap(plugins);
// Log state
logger.info.ln(installedMap.size + ' plugins are installed');
if (requirements.size != installedMap.size) {
logger.info.ln(requirements.size + ' explicitly listed');
}
// Verify that all plugins are present
if (missing.length > 0) {
throw new Error('Couldn\'t locate plugins "' + missing.join(', ') + '", Run \'gitbook install\' to install plugins from registry.');
}
return Promise.map(plugins, function(plugin) {
return loadPlugin(book, plugin);
});
});
} | [
"function",
"loadForBook",
"(",
"book",
")",
"{",
"var",
"logger",
"=",
"book",
".",
"getLogger",
"(",
")",
";",
"// List the dependencies",
"var",
"requirements",
"=",
"listDepsForBook",
"(",
"book",
")",
";",
"// List all plugins installed in the book",
"return",
"findForBook",
"(",
"book",
")",
".",
"then",
"(",
"function",
"(",
"installedMap",
")",
"{",
"var",
"missing",
"=",
"[",
"]",
";",
"var",
"plugins",
"=",
"requirements",
".",
"reduce",
"(",
"function",
"(",
"result",
",",
"dep",
")",
"{",
"var",
"name",
"=",
"dep",
".",
"getName",
"(",
")",
";",
"var",
"installed",
"=",
"installedMap",
".",
"get",
"(",
"name",
")",
";",
"if",
"(",
"installed",
")",
"{",
"var",
"deps",
"=",
"installedMap",
".",
"filter",
"(",
"function",
"(",
"plugin",
")",
"{",
"return",
"plugin",
".",
"getParent",
"(",
")",
"===",
"name",
";",
"}",
")",
".",
"toArray",
"(",
")",
";",
"result",
"=",
"result",
".",
"concat",
"(",
"deps",
")",
";",
"result",
".",
"push",
"(",
"installed",
")",
";",
"}",
"else",
"{",
"missing",
".",
"push",
"(",
"name",
")",
";",
"}",
"return",
"result",
";",
"}",
",",
"[",
"]",
")",
";",
"// Convert plugins list to a map",
"plugins",
"=",
"Immutable",
".",
"List",
"(",
"plugins",
")",
".",
"map",
"(",
"function",
"(",
"plugin",
")",
"{",
"return",
"[",
"plugin",
".",
"getName",
"(",
")",
",",
"plugin",
"]",
";",
"}",
")",
";",
"plugins",
"=",
"Immutable",
".",
"OrderedMap",
"(",
"plugins",
")",
";",
"// Log state",
"logger",
".",
"info",
".",
"ln",
"(",
"installedMap",
".",
"size",
"+",
"' plugins are installed'",
")",
";",
"if",
"(",
"requirements",
".",
"size",
"!=",
"installedMap",
".",
"size",
")",
"{",
"logger",
".",
"info",
".",
"ln",
"(",
"requirements",
".",
"size",
"+",
"' explicitly listed'",
")",
";",
"}",
"// Verify that all plugins are present",
"if",
"(",
"missing",
".",
"length",
">",
"0",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Couldn\\'t locate plugins \"'",
"+",
"missing",
".",
"join",
"(",
"', '",
")",
"+",
"'\", Run \\'gitbook install\\' to install plugins from registry.'",
")",
";",
"}",
"return",
"Promise",
".",
"map",
"(",
"plugins",
",",
"function",
"(",
"plugin",
")",
"{",
"return",
"loadPlugin",
"(",
"book",
",",
"plugin",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Load all plugins in a book
@param {Book}
@return {Promise<Map<String:Plugin>} | [
"Load",
"all",
"plugins",
"in",
"a",
"book"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/plugins/loadForBook.js#L15-L70 |
1,096 | GitbookIO/gitbook | lib/json/encodeBook.js | encodeBookToJson | function encodeBookToJson(book) {
var config = book.getConfig();
var language = book.getLanguage();
var variables = config.getValue('variables', {});
return {
summary: encodeSummary(book.getSummary()),
glossary: encodeGlossary(book.getGlossary()),
readme: encodeReadme(book.getReadme()),
config: book.getConfig().getValues().toJS(),
languages: book.isMultilingual()? encodeLanguages(book.getLanguages()) : undefined,
gitbook: {
version: gitbook.version,
time: gitbook.START_TIME
},
book: extend({
language: language? language : undefined
}, variables.toJS())
};
} | javascript | function encodeBookToJson(book) {
var config = book.getConfig();
var language = book.getLanguage();
var variables = config.getValue('variables', {});
return {
summary: encodeSummary(book.getSummary()),
glossary: encodeGlossary(book.getGlossary()),
readme: encodeReadme(book.getReadme()),
config: book.getConfig().getValues().toJS(),
languages: book.isMultilingual()? encodeLanguages(book.getLanguages()) : undefined,
gitbook: {
version: gitbook.version,
time: gitbook.START_TIME
},
book: extend({
language: language? language : undefined
}, variables.toJS())
};
} | [
"function",
"encodeBookToJson",
"(",
"book",
")",
"{",
"var",
"config",
"=",
"book",
".",
"getConfig",
"(",
")",
";",
"var",
"language",
"=",
"book",
".",
"getLanguage",
"(",
")",
";",
"var",
"variables",
"=",
"config",
".",
"getValue",
"(",
"'variables'",
",",
"{",
"}",
")",
";",
"return",
"{",
"summary",
":",
"encodeSummary",
"(",
"book",
".",
"getSummary",
"(",
")",
")",
",",
"glossary",
":",
"encodeGlossary",
"(",
"book",
".",
"getGlossary",
"(",
")",
")",
",",
"readme",
":",
"encodeReadme",
"(",
"book",
".",
"getReadme",
"(",
")",
")",
",",
"config",
":",
"book",
".",
"getConfig",
"(",
")",
".",
"getValues",
"(",
")",
".",
"toJS",
"(",
")",
",",
"languages",
":",
"book",
".",
"isMultilingual",
"(",
")",
"?",
"encodeLanguages",
"(",
"book",
".",
"getLanguages",
"(",
")",
")",
":",
"undefined",
",",
"gitbook",
":",
"{",
"version",
":",
"gitbook",
".",
"version",
",",
"time",
":",
"gitbook",
".",
"START_TIME",
"}",
",",
"book",
":",
"extend",
"(",
"{",
"language",
":",
"language",
"?",
"language",
":",
"undefined",
"}",
",",
"variables",
".",
"toJS",
"(",
")",
")",
"}",
";",
"}"
] | Encode a book to JSON
@param {Book}
@return {Object} | [
"Encode",
"a",
"book",
"to",
"JSON"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/json/encodeBook.js#L15-L37 |
1,097 | GitbookIO/gitbook | lib/parse/parseSummary.js | parseSummary | function parseSummary(book) {
var readme = book.getReadme();
var logger = book.getLogger();
var readmeFile = readme.getFile();
return parseStructureFile(book, 'summary')
.spread(function(file, result) {
var summary;
if (!file) {
logger.warn.ln('no summary file in this book');
summary = Summary();
} else {
logger.debug.ln('summary file found at', file.getPath());
summary = Summary.createFromParts(file, result.parts);
}
// Insert readme as first entry if not in SUMMARY.md
var readmeArticle = summary.getByPath(readmeFile.getPath());
if (readmeFile.exists() && !readmeArticle) {
summary = SummaryModifier.unshiftArticle(summary, {
title: 'Introduction',
ref: readmeFile.getPath()
});
}
// Set new summary
return book.setSummary(summary);
});
} | javascript | function parseSummary(book) {
var readme = book.getReadme();
var logger = book.getLogger();
var readmeFile = readme.getFile();
return parseStructureFile(book, 'summary')
.spread(function(file, result) {
var summary;
if (!file) {
logger.warn.ln('no summary file in this book');
summary = Summary();
} else {
logger.debug.ln('summary file found at', file.getPath());
summary = Summary.createFromParts(file, result.parts);
}
// Insert readme as first entry if not in SUMMARY.md
var readmeArticle = summary.getByPath(readmeFile.getPath());
if (readmeFile.exists() && !readmeArticle) {
summary = SummaryModifier.unshiftArticle(summary, {
title: 'Introduction',
ref: readmeFile.getPath()
});
}
// Set new summary
return book.setSummary(summary);
});
} | [
"function",
"parseSummary",
"(",
"book",
")",
"{",
"var",
"readme",
"=",
"book",
".",
"getReadme",
"(",
")",
";",
"var",
"logger",
"=",
"book",
".",
"getLogger",
"(",
")",
";",
"var",
"readmeFile",
"=",
"readme",
".",
"getFile",
"(",
")",
";",
"return",
"parseStructureFile",
"(",
"book",
",",
"'summary'",
")",
".",
"spread",
"(",
"function",
"(",
"file",
",",
"result",
")",
"{",
"var",
"summary",
";",
"if",
"(",
"!",
"file",
")",
"{",
"logger",
".",
"warn",
".",
"ln",
"(",
"'no summary file in this book'",
")",
";",
"summary",
"=",
"Summary",
"(",
")",
";",
"}",
"else",
"{",
"logger",
".",
"debug",
".",
"ln",
"(",
"'summary file found at'",
",",
"file",
".",
"getPath",
"(",
")",
")",
";",
"summary",
"=",
"Summary",
".",
"createFromParts",
"(",
"file",
",",
"result",
".",
"parts",
")",
";",
"}",
"// Insert readme as first entry if not in SUMMARY.md",
"var",
"readmeArticle",
"=",
"summary",
".",
"getByPath",
"(",
"readmeFile",
".",
"getPath",
"(",
")",
")",
";",
"if",
"(",
"readmeFile",
".",
"exists",
"(",
")",
"&&",
"!",
"readmeArticle",
")",
"{",
"summary",
"=",
"SummaryModifier",
".",
"unshiftArticle",
"(",
"summary",
",",
"{",
"title",
":",
"'Introduction'",
",",
"ref",
":",
"readmeFile",
".",
"getPath",
"(",
")",
"}",
")",
";",
"}",
"// Set new summary",
"return",
"book",
".",
"setSummary",
"(",
"summary",
")",
";",
"}",
")",
";",
"}"
] | Parse summary in a book, the summary can only be parsed
if the readme as be detected before.
@param {Book} book
@return {Promise<Book>} | [
"Parse",
"summary",
"in",
"a",
"book",
"the",
"summary",
"can",
"only",
"be",
"parsed",
"if",
"the",
"readme",
"as",
"be",
"detected",
"before",
"."
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/parse/parseSummary.js#L12-L42 |
1,098 | GitbookIO/gitbook | lib/output/website/copyPluginAssets.js | copyPluginAssets | function copyPluginAssets(output) {
var book = output.getBook();
// Don't copy plugins assets for language book
// It'll be resolved to the parent folder
if (book.isLanguageBook()) {
return Promise(output);
}
var plugins = output.getPlugins()
// We reverse the order of plugins to copy
// so that first plugins can replace assets from other plugins.
.reverse();
return Promise.forEach(plugins, function(plugin) {
return copyAssets(output, plugin)
.then(function() {
return copyResources(output, plugin);
});
})
.thenResolve(output);
} | javascript | function copyPluginAssets(output) {
var book = output.getBook();
// Don't copy plugins assets for language book
// It'll be resolved to the parent folder
if (book.isLanguageBook()) {
return Promise(output);
}
var plugins = output.getPlugins()
// We reverse the order of plugins to copy
// so that first plugins can replace assets from other plugins.
.reverse();
return Promise.forEach(plugins, function(plugin) {
return copyAssets(output, plugin)
.then(function() {
return copyResources(output, plugin);
});
})
.thenResolve(output);
} | [
"function",
"copyPluginAssets",
"(",
"output",
")",
"{",
"var",
"book",
"=",
"output",
".",
"getBook",
"(",
")",
";",
"// Don't copy plugins assets for language book",
"// It'll be resolved to the parent folder",
"if",
"(",
"book",
".",
"isLanguageBook",
"(",
")",
")",
"{",
"return",
"Promise",
"(",
"output",
")",
";",
"}",
"var",
"plugins",
"=",
"output",
".",
"getPlugins",
"(",
")",
"// We reverse the order of plugins to copy",
"// so that first plugins can replace assets from other plugins.",
".",
"reverse",
"(",
")",
";",
"return",
"Promise",
".",
"forEach",
"(",
"plugins",
",",
"function",
"(",
"plugin",
")",
"{",
"return",
"copyAssets",
"(",
"output",
",",
"plugin",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"copyResources",
"(",
"output",
",",
"plugin",
")",
";",
"}",
")",
";",
"}",
")",
".",
"thenResolve",
"(",
"output",
")",
";",
"}"
] | Copy all assets from plugins.
Assets are files stored in "_assets"
nd resources declared in the plugin itself.
@param {Output}
@return {Promise} | [
"Copy",
"all",
"assets",
"from",
"plugins",
".",
"Assets",
"are",
"files",
"stored",
"in",
"_assets",
"nd",
"resources",
"declared",
"in",
"the",
"plugin",
"itself",
"."
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/website/copyPluginAssets.js#L15-L37 |
1,099 | GitbookIO/gitbook | lib/output/website/copyPluginAssets.js | copyAssets | function copyAssets(output, plugin) {
var logger = output.getLogger();
var pluginRoot = plugin.getPath();
var options = output.getOptions();
var outputRoot = options.get('root');
var assetOutputFolder = path.join(outputRoot, 'gitbook');
var prefix = options.get('prefix');
var assetFolder = path.join(pluginRoot, ASSET_FOLDER, prefix);
if (!fs.existsSync(assetFolder)) {
return Promise();
}
logger.debug.ln('copy assets from theme', assetFolder);
return fs.copyDir(
assetFolder,
assetOutputFolder,
{
deleteFirst: false,
overwrite: true,
confirm: true
}
);
} | javascript | function copyAssets(output, plugin) {
var logger = output.getLogger();
var pluginRoot = plugin.getPath();
var options = output.getOptions();
var outputRoot = options.get('root');
var assetOutputFolder = path.join(outputRoot, 'gitbook');
var prefix = options.get('prefix');
var assetFolder = path.join(pluginRoot, ASSET_FOLDER, prefix);
if (!fs.existsSync(assetFolder)) {
return Promise();
}
logger.debug.ln('copy assets from theme', assetFolder);
return fs.copyDir(
assetFolder,
assetOutputFolder,
{
deleteFirst: false,
overwrite: true,
confirm: true
}
);
} | [
"function",
"copyAssets",
"(",
"output",
",",
"plugin",
")",
"{",
"var",
"logger",
"=",
"output",
".",
"getLogger",
"(",
")",
";",
"var",
"pluginRoot",
"=",
"plugin",
".",
"getPath",
"(",
")",
";",
"var",
"options",
"=",
"output",
".",
"getOptions",
"(",
")",
";",
"var",
"outputRoot",
"=",
"options",
".",
"get",
"(",
"'root'",
")",
";",
"var",
"assetOutputFolder",
"=",
"path",
".",
"join",
"(",
"outputRoot",
",",
"'gitbook'",
")",
";",
"var",
"prefix",
"=",
"options",
".",
"get",
"(",
"'prefix'",
")",
";",
"var",
"assetFolder",
"=",
"path",
".",
"join",
"(",
"pluginRoot",
",",
"ASSET_FOLDER",
",",
"prefix",
")",
";",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"assetFolder",
")",
")",
"{",
"return",
"Promise",
"(",
")",
";",
"}",
"logger",
".",
"debug",
".",
"ln",
"(",
"'copy assets from theme'",
",",
"assetFolder",
")",
";",
"return",
"fs",
".",
"copyDir",
"(",
"assetFolder",
",",
"assetOutputFolder",
",",
"{",
"deleteFirst",
":",
"false",
",",
"overwrite",
":",
"true",
",",
"confirm",
":",
"true",
"}",
")",
";",
"}"
] | Copy assets from a plugin
@param {Plugin}
@return {Promise} | [
"Copy",
"assets",
"from",
"a",
"plugin"
] | 6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4 | https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/website/copyPluginAssets.js#L45-L70 |