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
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
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",
"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
|
train
|
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",
"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
|
train
|
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 [email protected] 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
|
train
|
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 [email protected] 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 [email protected] to remove this warning.`,
)
youHaveBeenWarned = true
}
await cb()
// make all effects resolve after
act(() => {})
}
|
[
"async",
"function",
"asyncActPolyfill",
"(",
"cb",
")",
"{",
"if",
"(",
"!",
"youHaveBeenWarned",
"&&",
"actSupported",
"&&",
"reactDomSixteenPointNineIsReleased",
")",
"{",
"console",
".",
"error",
"(",
"`",
"`",
",",
")",
"youHaveBeenWarned",
"=",
"true",
"}",
"await",
"cb",
"(",
")",
"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
|
train
|
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'",
")",
")",
";",
"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
|
train
|
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",
")",
")",
"{",
"return",
"\"Conversion Failure\"",
";",
"}",
"}",
"if",
"(",
"Number",
".",
"isInteger",
"(",
"num",
")",
")",
"{",
"numStr",
"=",
"num",
".",
"toString",
"(",
")",
";",
"}",
"else",
"{",
"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",
")",
";",
"while",
"(",
"numStr",
".",
"charAt",
"(",
"numStr",
".",
"length",
"-",
"1",
")",
"===",
"'0'",
")",
"{",
"numStr",
"=",
"numStr",
".",
"substring",
"(",
"0",
",",
"numStr",
".",
"length",
"-",
"1",
")",
";",
"}",
"if",
"(",
"numStr",
".",
"charAt",
"(",
"numStr",
".",
"length",
"-",
"1",
")",
"===",
"'.'",
")",
"{",
"numStr",
"=",
"numStr",
".",
"substring",
"(",
"0",
",",
"numStr",
".",
"length",
"-",
"1",
")",
";",
"}",
"}",
"let",
"dp",
"=",
"numStr",
".",
"indexOf",
"(",
"'.'",
")",
";",
"if",
"(",
"dp",
"<",
"0",
")",
"{",
"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
|
train
|
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
|
train
|
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
|
train
|
|
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
|
train
|
|
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",
";",
"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
|
train
|
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
|
train
|
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",
")",
"{",
"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",
"`",
")",
";",
"\\u001b",
"}",
"\\u001b",
"return",
";",
"}"
] |
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
|
train
|
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",
")",
"{",
"var",
"originLevel",
"=",
"is",
".",
"string",
"(",
"origin",
")",
"?",
"origin",
":",
"origin",
".",
"getLevel",
"(",
")",
";",
"var",
"targetLevel",
"=",
"is",
".",
"string",
"(",
"target",
")",
"?",
"target",
":",
"target",
".",
"getLevel",
"(",
")",
";",
"var",
"article",
"=",
"summary",
".",
"getByLevel",
"(",
"originLevel",
")",
";",
"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
|
train
|
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
|
train
|
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",
"(",
")",
";",
"return",
"Modifiers",
".",
"modifyHTML",
"(",
"page",
",",
"[",
"Modifiers",
".",
"inlineAssets",
"(",
"options",
".",
"get",
"(",
"'root'",
")",
",",
"page",
".",
"getFile",
"(",
")",
".",
"getPath",
"(",
")",
")",
"]",
")",
".",
"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
|
train
|
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
|
train
|
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
|
train
|
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",
")",
"{",
"var",
"toRemove",
"=",
"deps",
".",
"filter",
"(",
"function",
"(",
"plugin",
")",
"{",
"return",
"!",
"plugin",
".",
"isEnabled",
"(",
")",
";",
"}",
")",
".",
"map",
"(",
"function",
"(",
"plugin",
")",
"{",
"return",
"plugin",
".",
"getName",
"(",
")",
";",
"}",
")",
";",
"deps",
"=",
"deps",
".",
"concat",
"(",
"DEFAULT_PLUGINS",
")",
";",
"deps",
"=",
"deps",
".",
"filterNot",
"(",
"function",
"(",
"plugin",
")",
"{",
"return",
"toRemove",
".",
"includes",
"(",
"plugin",
".",
"getName",
"(",
")",
")",
";",
"}",
")",
";",
"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
|
train
|
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",
")",
";",
"return",
"Templating",
".",
"renderFile",
"(",
"engine",
",",
"prefix",
"+",
"'/summary.html'",
",",
"context",
")",
".",
"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
|
train
|
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
|
train
|
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",
"}"
] |
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
|
train
|
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]*?[^\\\\$])'",
"+",
"\\\\",
",",
"\\\\",
")",
";",
"\\\\",
"}"
] |
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
|
train
|
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
|
train
|
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",
";",
"schema",
".",
"id",
"=",
"'/'",
"+",
"configKey",
";",
"schema",
".",
"type",
"=",
"'object'",
";",
"var",
"v",
"=",
"new",
"jsonschema",
".",
"Validator",
"(",
")",
";",
"var",
"result",
"=",
"v",
".",
"validate",
"(",
"pluginConfig",
",",
"schema",
",",
"{",
"propertyName",
":",
"configKey",
"}",
")",
";",
"if",
"(",
"result",
".",
"errors",
".",
"length",
">",
"0",
")",
"{",
"throw",
"new",
"error",
".",
"ConfigurationError",
"(",
"new",
"Error",
"(",
"result",
".",
"errors",
"[",
"0",
"]",
".",
"stack",
")",
")",
";",
"}",
"var",
"defaults",
"=",
"jsonSchemaDefaults",
"(",
"schema",
")",
";",
"pluginConfig",
"=",
"mergeDefaults",
"(",
"pluginConfig",
",",
"defaults",
")",
";",
"config",
"=",
"config",
".",
"setValue",
"(",
"configKey",
",",
"pluginConfig",
")",
";",
"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
|
train
|
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
|
train
|
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",
";",
"}",
"var",
"articles",
"=",
"parent",
".",
"getArticles",
"(",
")",
";",
"var",
"index",
"=",
"getLeafIndex",
"(",
"level",
")",
";",
"articles",
"=",
"articles",
".",
"insert",
"(",
"index",
",",
"article",
")",
";",
"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
|
train
|
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
|
train
|
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",
")",
"{",
"if",
"(",
"book",
".",
"isFileIgnored",
"(",
"filename",
")",
")",
"{",
"return",
";",
"}",
"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",
")",
";",
"if",
"(",
"result",
".",
"file",
")",
"{",
"config",
"=",
"config",
".",
"setFile",
"(",
"result",
".",
"file",
")",
";",
"}",
"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
|
train
|
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",
")",
"{",
"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
|
train
|
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",
"(",
")",
";",
"return",
"timing",
".",
"measure",
"(",
"'parse.listPages'",
",",
"walkSummary",
"(",
"summary",
",",
"function",
"(",
"article",
")",
"{",
"if",
"(",
"!",
"article",
".",
"isPage",
"(",
")",
")",
"return",
";",
"var",
"filepath",
"=",
"article",
".",
"getPath",
"(",
")",
";",
"if",
"(",
"book",
".",
"isContentFileIgnored",
"(",
"filepath",
")",
")",
"return",
";",
"return",
"parseFilePage",
"(",
"book",
",",
"filepath",
")",
".",
"then",
"(",
"function",
"(",
"page",
")",
"{",
"if",
"(",
"!",
"page",
")",
"{",
"return",
";",
"}",
"map",
"=",
"map",
".",
"set",
"(",
"filepath",
",",
"page",
")",
";",
"}",
")",
";",
"}",
")",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"var",
"file",
"=",
"glossary",
".",
"getFile",
"(",
")",
";",
"if",
"(",
"!",
"file",
".",
"exists",
"(",
")",
")",
"{",
"return",
";",
"}",
"return",
"parseFilePage",
"(",
"book",
",",
"file",
".",
"getPath",
"(",
")",
")",
".",
"then",
"(",
"function",
"(",
"page",
")",
"{",
"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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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",
")",
";",
"var",
"hash",
"=",
"crc",
".",
"crc32",
"(",
"content",
")",
".",
"toString",
"(",
"16",
")",
";",
"var",
"fileName",
"=",
"hash",
"+",
"'.svg'",
";",
"var",
"filePath",
"=",
"path",
".",
"join",
"(",
"baseFolder",
",",
"fileName",
")",
";",
"return",
"fs",
".",
"assertFile",
"(",
"filePath",
",",
"function",
"(",
")",
"{",
"return",
"fs",
".",
"writeFile",
"(",
"filePath",
",",
"content",
",",
"'utf8'",
")",
";",
"}",
")",
".",
"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
|
train
|
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",
")",
"{",
"if",
"(",
"cl",
".",
"search",
"(",
"'lang-'",
")",
"===",
"0",
")",
"{",
"return",
"cl",
".",
"slice",
"(",
"'lang-'",
".",
"length",
")",
";",
"}",
"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
|
train
|
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
|
train
|
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",
"}",
")",
")",
";",
"}",
"return",
"callPageHook",
"(",
"'page:before'",
",",
"output",
",",
"resultPage",
")",
".",
"then",
"(",
"function",
"(",
"currentPage",
")",
"{",
"return",
"parser",
".",
"preparePage",
"(",
"currentPage",
".",
"getContent",
"(",
")",
")",
";",
"}",
")",
".",
"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",
")",
";",
"}",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"output",
")",
"{",
"return",
"Templating",
".",
"postRender",
"(",
"engine",
",",
"output",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"content",
")",
"{",
"return",
"resultPage",
".",
"set",
"(",
"'content'",
",",
"content",
")",
";",
"}",
")",
".",
"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
|
train
|
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
|
train
|
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",
"=",
"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
|
train
|
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
|
train
|
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",
";",
"}",
"var",
"hash",
"=",
"crc",
".",
"crc32",
"(",
"src",
")",
".",
"toString",
"(",
"16",
")",
";",
"var",
"fileName",
"=",
"hash",
"+",
"'.png'",
";",
"var",
"filePath",
"=",
"path",
".",
"join",
"(",
"rootFolder",
",",
"fileName",
")",
";",
"return",
"fs",
".",
"assertFile",
"(",
"filePath",
",",
"function",
"(",
")",
"{",
"return",
"imagesUtil",
".",
"convertInlinePNG",
"(",
"src",
",",
"filePath",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"fileName",
"=",
"LocationUtils",
".",
"relative",
"(",
"currentDirectory",
",",
"fileName",
")",
";",
"$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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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",
"(",
")",
";",
"var",
"searchPaths",
"=",
"listSearchPaths",
"(",
"output",
")",
";",
"var",
"tplSearchPaths",
"=",
"searchPaths",
".",
"map",
"(",
"templateFolder",
")",
";",
"var",
"loader",
"=",
"new",
"Templating",
".",
"ThemesLoader",
"(",
"tplSearchPaths",
")",
";",
"var",
"language",
"=",
"config",
".",
"getValue",
"(",
"'language'",
")",
";",
"var",
"context",
"=",
"Api",
".",
"encodeGlobal",
"(",
"output",
")",
";",
"function",
"fileExists",
"(",
"fileName",
")",
"{",
"if",
"(",
"!",
"fileName",
")",
"{",
"return",
"false",
";",
"}",
"var",
"filePath",
"=",
"PathUtils",
".",
"resolveInRoot",
"(",
"outputFolder",
",",
"fileName",
")",
";",
"return",
"fs",
".",
"existsSync",
"(",
"filePath",
")",
";",
"}",
"function",
"getArticleByPath",
"(",
"filePath",
")",
"{",
"var",
"article",
"=",
"summary",
".",
"getByPath",
"(",
"filePath",
")",
";",
"if",
"(",
"!",
"article",
")",
"return",
"undefined",
";",
"return",
"JSONUtils",
".",
"encodeSummaryArticle",
"(",
"article",
")",
";",
"}",
"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",
"(",
"{",
"t",
":",
"function",
"t",
"(",
"s",
")",
"{",
"return",
"i18n",
".",
"t",
"(",
"language",
",",
"s",
")",
";",
"}",
",",
"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",
")",
";",
"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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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",
"(",
")",
";",
"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
|
train
|
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",
";",
"}",
"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",
"(",
")",
"{",
"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
|
train
|
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
|
train
|
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",
")",
"{",
"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
|
train
|
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",
"(",
")",
"{",
"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",
"(",
")",
"{",
"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
|
train
|
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
|
train
|
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",
"(",
")",
";",
"var",
"entries",
"=",
"glossary",
".",
"getEntries",
"(",
")",
";",
"var",
"glossaryFile",
"=",
"glossary",
".",
"getFile",
"(",
")",
";",
"var",
"glossaryFilename",
"=",
"fileToOutput",
"(",
"output",
",",
"glossaryFile",
".",
"getPath",
"(",
")",
")",
";",
"var",
"currentFilePath",
"=",
"file",
".",
"getPath",
"(",
")",
";",
"var",
"blocks",
"=",
"Plugins",
".",
"listBlocks",
"(",
"plugins",
")",
";",
"var",
"code",
"=",
"blocks",
".",
"get",
"(",
"CODEBLOCK",
")",
"||",
"defaultBlocks",
".",
"get",
"(",
"CODEBLOCK",
")",
";",
"var",
"context",
"=",
"Api",
".",
"encodeGlobal",
"(",
"output",
")",
";",
"return",
"[",
"Modifiers",
".",
"addHeadingId",
",",
"Modifiers",
".",
"annotateText",
".",
"bind",
"(",
"null",
",",
"entries",
",",
"glossaryFilename",
")",
",",
"Modifiers",
".",
"resolveImages",
".",
"bind",
"(",
"null",
",",
"currentFilePath",
")",
",",
"Modifiers",
".",
"resolveLinks",
".",
"bind",
"(",
"null",
",",
"currentFilePath",
",",
"resolveFileToURL",
".",
"bind",
"(",
"null",
",",
"output",
")",
")",
",",
"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
|
train
|
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
|
train
|
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
|
train
|
|
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
|
train
|
|
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
|
train
|
|
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
|
train
|
|
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
|
train
|
|
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
|
train
|
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
|
train
|
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
|
train
|
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'",
")",
";",
"var",
"cover",
"=",
"fs",
".",
"pickFile",
"(",
"outputRoot",
",",
"coverName",
")",
";",
"if",
"(",
"cover",
")",
"{",
"return",
"cover",
";",
"}",
"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
|
train
|
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
|
train
|
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",
")",
"{",
"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",
")",
"{",
"var",
"removed",
"=",
"removeArticle",
"(",
"summary",
",",
"originLevel",
")",
";",
"return",
"insertArticle",
"(",
"removed",
",",
"article",
",",
"targetLevel",
")",
";",
"}",
"else",
"{",
"var",
"inserted",
"=",
"insertArticle",
"(",
"summary",
",",
"article",
",",
"targetLevel",
")",
";",
"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
|
train
|
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",
"(",
")",
";",
"var",
"requirements",
"=",
"listDepsForBook",
"(",
"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",
";",
"}",
",",
"[",
"]",
")",
";",
"plugins",
"=",
"Immutable",
".",
"List",
"(",
"plugins",
")",
".",
"map",
"(",
"function",
"(",
"plugin",
")",
"{",
"return",
"[",
"plugin",
".",
"getName",
"(",
")",
",",
"plugin",
"]",
";",
"}",
")",
";",
"plugins",
"=",
"Immutable",
".",
"OrderedMap",
"(",
"plugins",
")",
";",
"logger",
".",
"info",
".",
"ln",
"(",
"installedMap",
".",
"size",
"+",
"' plugins are installed'",
")",
";",
"if",
"(",
"requirements",
".",
"size",
"!=",
"installedMap",
".",
"size",
")",
"{",
"logger",
".",
"info",
".",
"ln",
"(",
"requirements",
".",
"size",
"+",
"' explicitly listed'",
")",
";",
"}",
"if",
"(",
"missing",
".",
"length",
">",
"0",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Couldn\\'t locate plugins \"'",
"+",
"\\'",
"+",
"missing",
".",
"join",
"(",
"', '",
")",
")",
";",
"}",
"'\", Run \\'gitbook install\\' to install plugins from registry.'",
"}",
")",
";",
"}"
] |
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
|
train
|
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
|
train
|
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",
")",
";",
"}",
"var",
"readmeArticle",
"=",
"summary",
".",
"getByPath",
"(",
"readmeFile",
".",
"getPath",
"(",
")",
")",
";",
"if",
"(",
"readmeFile",
".",
"exists",
"(",
")",
"&&",
"!",
"readmeArticle",
")",
"{",
"summary",
"=",
"SummaryModifier",
".",
"unshiftArticle",
"(",
"summary",
",",
"{",
"title",
":",
"'Introduction'",
",",
"ref",
":",
"readmeFile",
".",
"getPath",
"(",
")",
"}",
")",
";",
"}",
"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
|
train
|
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",
"(",
")",
";",
"if",
"(",
"book",
".",
"isLanguageBook",
"(",
")",
")",
"{",
"return",
"Promise",
"(",
"output",
")",
";",
"}",
"var",
"plugins",
"=",
"output",
".",
"getPlugins",
"(",
")",
".",
"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
|
train
|
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
|
train
|
GitbookIO/gitbook
|
lib/output/website/copyPluginAssets.js
|
copyResources
|
function copyResources(output, plugin) {
var logger = output.getLogger();
var options = output.getOptions();
var outputRoot = options.get('root');
var state = output.getState();
var resources = state.getResources();
var pluginRoot = plugin.getPath();
var pluginResources = resources.get(plugin.getName());
var assetsFolder = pluginResources.get('assets');
var assetOutputFolder = path.join(outputRoot, 'gitbook', plugin.getNpmID());
if (!assetsFolder) {
return Promise();
}
// Resolve assets folder
assetsFolder = path.resolve(pluginRoot, assetsFolder);
if (!fs.existsSync(assetsFolder)) {
logger.warn.ln('assets folder for plugin "' + plugin.getName() + '" doesn\'t exist');
return Promise();
}
logger.debug.ln('copy resources from plugin', assetsFolder);
return fs.copyDir(
assetsFolder,
assetOutputFolder,
{
deleteFirst: false,
overwrite: true,
confirm: true
}
);
}
|
javascript
|
function copyResources(output, plugin) {
var logger = output.getLogger();
var options = output.getOptions();
var outputRoot = options.get('root');
var state = output.getState();
var resources = state.getResources();
var pluginRoot = plugin.getPath();
var pluginResources = resources.get(plugin.getName());
var assetsFolder = pluginResources.get('assets');
var assetOutputFolder = path.join(outputRoot, 'gitbook', plugin.getNpmID());
if (!assetsFolder) {
return Promise();
}
// Resolve assets folder
assetsFolder = path.resolve(pluginRoot, assetsFolder);
if (!fs.existsSync(assetsFolder)) {
logger.warn.ln('assets folder for plugin "' + plugin.getName() + '" doesn\'t exist');
return Promise();
}
logger.debug.ln('copy resources from plugin', assetsFolder);
return fs.copyDir(
assetsFolder,
assetOutputFolder,
{
deleteFirst: false,
overwrite: true,
confirm: true
}
);
}
|
[
"function",
"copyResources",
"(",
"output",
",",
"plugin",
")",
"{",
"var",
"logger",
"=",
"output",
".",
"getLogger",
"(",
")",
";",
"var",
"options",
"=",
"output",
".",
"getOptions",
"(",
")",
";",
"var",
"outputRoot",
"=",
"options",
".",
"get",
"(",
"'root'",
")",
";",
"var",
"state",
"=",
"output",
".",
"getState",
"(",
")",
";",
"var",
"resources",
"=",
"state",
".",
"getResources",
"(",
")",
";",
"var",
"pluginRoot",
"=",
"plugin",
".",
"getPath",
"(",
")",
";",
"var",
"pluginResources",
"=",
"resources",
".",
"get",
"(",
"plugin",
".",
"getName",
"(",
")",
")",
";",
"var",
"assetsFolder",
"=",
"pluginResources",
".",
"get",
"(",
"'assets'",
")",
";",
"var",
"assetOutputFolder",
"=",
"path",
".",
"join",
"(",
"outputRoot",
",",
"'gitbook'",
",",
"plugin",
".",
"getNpmID",
"(",
")",
")",
";",
"if",
"(",
"!",
"assetsFolder",
")",
"{",
"return",
"Promise",
"(",
")",
";",
"}",
"assetsFolder",
"=",
"path",
".",
"resolve",
"(",
"pluginRoot",
",",
"assetsFolder",
")",
";",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"assetsFolder",
")",
")",
"{",
"logger",
".",
"warn",
".",
"ln",
"(",
"'assets folder for plugin \"'",
"+",
"plugin",
".",
"getName",
"(",
")",
"+",
"'\" doesn\\'t exist'",
")",
";",
"\\'",
"}",
"return",
"Promise",
"(",
")",
";",
"logger",
".",
"debug",
".",
"ln",
"(",
"'copy resources from plugin'",
",",
"assetsFolder",
")",
";",
"}"
] |
Copy resources from a plugin
@param {Plugin}
@return {Promise}
|
[
"Copy",
"resources",
"from",
"a",
"plugin"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/website/copyPluginAssets.js#L78-L115
|
train
|
GitbookIO/gitbook
|
lib/output/helper/writeFile.js
|
writeFile
|
function writeFile(output, filePath, content) {
var rootFolder = output.getRoot();
filePath = path.join(rootFolder, filePath);
return fs.ensureFile(filePath)
.then(function() {
return fs.writeFile(filePath, content);
})
.thenResolve(output);
}
|
javascript
|
function writeFile(output, filePath, content) {
var rootFolder = output.getRoot();
filePath = path.join(rootFolder, filePath);
return fs.ensureFile(filePath)
.then(function() {
return fs.writeFile(filePath, content);
})
.thenResolve(output);
}
|
[
"function",
"writeFile",
"(",
"output",
",",
"filePath",
",",
"content",
")",
"{",
"var",
"rootFolder",
"=",
"output",
".",
"getRoot",
"(",
")",
";",
"filePath",
"=",
"path",
".",
"join",
"(",
"rootFolder",
",",
"filePath",
")",
";",
"return",
"fs",
".",
"ensureFile",
"(",
"filePath",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"fs",
".",
"writeFile",
"(",
"filePath",
",",
"content",
")",
";",
"}",
")",
".",
"thenResolve",
"(",
"output",
")",
";",
"}"
] |
Write a file to the output folder
@param {Output} output
@param {String} filePath
@param {Buffer|String} content
@return {Promise}
|
[
"Write",
"a",
"file",
"to",
"the",
"output",
"folder"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/helper/writeFile.js#L12-L21
|
train
|
GitbookIO/gitbook
|
lib/api/encodeProgress.js
|
encodeProgress
|
function encodeProgress(output, page) {
var current = page.getPath();
var navigation = encodeNavigation(output);
navigation = Immutable.Map(navigation);
var n = navigation.size;
var percent = 0, prevPercent = 0, currentChapter = null;
var done = true;
var chapters = navigation
.map(function(nav, chapterPath) {
nav.path = chapterPath;
return nav;
})
.valueSeq()
.sortBy(function(nav) {
return nav.index;
})
.map(function(nav, i) {
// Calcul percent
nav.percent = (i * 100) / Math.max((n - 1), 1);
// Is it done
nav.done = done;
if (nav.path == current) {
currentChapter = nav;
percent = nav.percent;
done = false;
} else if (done) {
prevPercent = nav.percent;
}
return nav;
})
.toJS();
return {
// Previous percent
prevPercent: prevPercent,
// Current percent
percent: percent,
// List of chapter with progress
chapters: chapters,
// Current chapter
current: currentChapter
};
}
|
javascript
|
function encodeProgress(output, page) {
var current = page.getPath();
var navigation = encodeNavigation(output);
navigation = Immutable.Map(navigation);
var n = navigation.size;
var percent = 0, prevPercent = 0, currentChapter = null;
var done = true;
var chapters = navigation
.map(function(nav, chapterPath) {
nav.path = chapterPath;
return nav;
})
.valueSeq()
.sortBy(function(nav) {
return nav.index;
})
.map(function(nav, i) {
// Calcul percent
nav.percent = (i * 100) / Math.max((n - 1), 1);
// Is it done
nav.done = done;
if (nav.path == current) {
currentChapter = nav;
percent = nav.percent;
done = false;
} else if (done) {
prevPercent = nav.percent;
}
return nav;
})
.toJS();
return {
// Previous percent
prevPercent: prevPercent,
// Current percent
percent: percent,
// List of chapter with progress
chapters: chapters,
// Current chapter
current: currentChapter
};
}
|
[
"function",
"encodeProgress",
"(",
"output",
",",
"page",
")",
"{",
"var",
"current",
"=",
"page",
".",
"getPath",
"(",
")",
";",
"var",
"navigation",
"=",
"encodeNavigation",
"(",
"output",
")",
";",
"navigation",
"=",
"Immutable",
".",
"Map",
"(",
"navigation",
")",
";",
"var",
"n",
"=",
"navigation",
".",
"size",
";",
"var",
"percent",
"=",
"0",
",",
"prevPercent",
"=",
"0",
",",
"currentChapter",
"=",
"null",
";",
"var",
"done",
"=",
"true",
";",
"var",
"chapters",
"=",
"navigation",
".",
"map",
"(",
"function",
"(",
"nav",
",",
"chapterPath",
")",
"{",
"nav",
".",
"path",
"=",
"chapterPath",
";",
"return",
"nav",
";",
"}",
")",
".",
"valueSeq",
"(",
")",
".",
"sortBy",
"(",
"function",
"(",
"nav",
")",
"{",
"return",
"nav",
".",
"index",
";",
"}",
")",
".",
"map",
"(",
"function",
"(",
"nav",
",",
"i",
")",
"{",
"nav",
".",
"percent",
"=",
"(",
"i",
"*",
"100",
")",
"/",
"Math",
".",
"max",
"(",
"(",
"n",
"-",
"1",
")",
",",
"1",
")",
";",
"nav",
".",
"done",
"=",
"done",
";",
"if",
"(",
"nav",
".",
"path",
"==",
"current",
")",
"{",
"currentChapter",
"=",
"nav",
";",
"percent",
"=",
"nav",
".",
"percent",
";",
"done",
"=",
"false",
";",
"}",
"else",
"if",
"(",
"done",
")",
"{",
"prevPercent",
"=",
"nav",
".",
"percent",
";",
"}",
"return",
"nav",
";",
"}",
")",
".",
"toJS",
"(",
")",
";",
"return",
"{",
"prevPercent",
":",
"prevPercent",
",",
"percent",
":",
"percent",
",",
"chapters",
":",
"chapters",
",",
"current",
":",
"currentChapter",
"}",
";",
"}"
] |
page.progress is a deprecated property from GitBook v2
@param {Output}
@param {Page}
@return {Object}
|
[
"page",
".",
"progress",
"is",
"a",
"deprecated",
"property",
"from",
"GitBook",
"v2"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/api/encodeProgress.js#L11-L60
|
train
|
GitbookIO/gitbook
|
lib/output/modifiers/inlineAssets.js
|
inlineAssets
|
function inlineAssets(rootFolder, currentFile) {
return function($) {
return Promise()
// Resolving images and fetching external images should be
// done before svg conversion
.then(resolveImages.bind(null, currentFile, $))
.then(fetchRemoteImages.bind(null, rootFolder, currentFile, $))
.then(svgToImg.bind(null, rootFolder, currentFile, $))
.then(svgToPng.bind(null, rootFolder, currentFile, $))
.then(inlinePng.bind(null, rootFolder, currentFile, $));
};
}
|
javascript
|
function inlineAssets(rootFolder, currentFile) {
return function($) {
return Promise()
// Resolving images and fetching external images should be
// done before svg conversion
.then(resolveImages.bind(null, currentFile, $))
.then(fetchRemoteImages.bind(null, rootFolder, currentFile, $))
.then(svgToImg.bind(null, rootFolder, currentFile, $))
.then(svgToPng.bind(null, rootFolder, currentFile, $))
.then(inlinePng.bind(null, rootFolder, currentFile, $));
};
}
|
[
"function",
"inlineAssets",
"(",
"rootFolder",
",",
"currentFile",
")",
"{",
"return",
"function",
"(",
"$",
")",
"{",
"return",
"Promise",
"(",
")",
".",
"then",
"(",
"resolveImages",
".",
"bind",
"(",
"null",
",",
"currentFile",
",",
"$",
")",
")",
".",
"then",
"(",
"fetchRemoteImages",
".",
"bind",
"(",
"null",
",",
"rootFolder",
",",
"currentFile",
",",
"$",
")",
")",
".",
"then",
"(",
"svgToImg",
".",
"bind",
"(",
"null",
",",
"rootFolder",
",",
"currentFile",
",",
"$",
")",
")",
".",
"then",
"(",
"svgToPng",
".",
"bind",
"(",
"null",
",",
"rootFolder",
",",
"currentFile",
",",
"$",
")",
")",
".",
"then",
"(",
"inlinePng",
".",
"bind",
"(",
"null",
",",
"rootFolder",
",",
"currentFile",
",",
"$",
")",
")",
";",
"}",
";",
"}"
] |
Inline all assets in a page
@param {String} rootFolder
|
[
"Inline",
"all",
"assets",
"in",
"a",
"page"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/output/modifiers/inlineAssets.js#L14-L27
|
train
|
GitbookIO/gitbook
|
lib/plugins/findForBook.js
|
findForBook
|
function findForBook(book) {
return timing.measure(
'plugins.findForBook',
Promise.all([
findInstalled(locateRootFolder()),
findInstalled(book.getRoot())
])
// Merge all plugins
.then(function(results) {
return Immutable.List(results)
.reduce(function(out, result) {
return out.merge(result);
}, Immutable.OrderedMap());
})
);
}
|
javascript
|
function findForBook(book) {
return timing.measure(
'plugins.findForBook',
Promise.all([
findInstalled(locateRootFolder()),
findInstalled(book.getRoot())
])
// Merge all plugins
.then(function(results) {
return Immutable.List(results)
.reduce(function(out, result) {
return out.merge(result);
}, Immutable.OrderedMap());
})
);
}
|
[
"function",
"findForBook",
"(",
"book",
")",
"{",
"return",
"timing",
".",
"measure",
"(",
"'plugins.findForBook'",
",",
"Promise",
".",
"all",
"(",
"[",
"findInstalled",
"(",
"locateRootFolder",
"(",
")",
")",
",",
"findInstalled",
"(",
"book",
".",
"getRoot",
"(",
")",
")",
"]",
")",
".",
"then",
"(",
"function",
"(",
"results",
")",
"{",
"return",
"Immutable",
".",
"List",
"(",
"results",
")",
".",
"reduce",
"(",
"function",
"(",
"out",
",",
"result",
")",
"{",
"return",
"out",
".",
"merge",
"(",
"result",
")",
";",
"}",
",",
"Immutable",
".",
"OrderedMap",
"(",
")",
")",
";",
"}",
")",
")",
";",
"}"
] |
List all plugins installed in a book
@param {Book}
@return {Promise<OrderedMap<String:Plugin>>}
|
[
"List",
"all",
"plugins",
"installed",
"in",
"a",
"book"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/plugins/findForBook.js#L14-L31
|
train
|
GitbookIO/gitbook
|
lib/parse/parseIgnore.js
|
parseIgnore
|
function parseIgnore(book) {
if (book.isLanguageBook()) {
return Promise.reject(new Error('Ignore files could be parsed for language books'));
}
var fs = book.getFS();
var ignore = book.getIgnore();
ignore = ignore.add(DEFAULT_IGNORES);
return Promise.serie(IGNORE_FILES, function(filename) {
return fs.readAsString(filename)
.then(function(content) {
ignore = ignore.add(content.toString().split(/\r?\n/));
}, function(err) {
return Promise();
});
})
.then(function() {
return book.setIgnore(ignore);
});
}
|
javascript
|
function parseIgnore(book) {
if (book.isLanguageBook()) {
return Promise.reject(new Error('Ignore files could be parsed for language books'));
}
var fs = book.getFS();
var ignore = book.getIgnore();
ignore = ignore.add(DEFAULT_IGNORES);
return Promise.serie(IGNORE_FILES, function(filename) {
return fs.readAsString(filename)
.then(function(content) {
ignore = ignore.add(content.toString().split(/\r?\n/));
}, function(err) {
return Promise();
});
})
.then(function() {
return book.setIgnore(ignore);
});
}
|
[
"function",
"parseIgnore",
"(",
"book",
")",
"{",
"if",
"(",
"book",
".",
"isLanguageBook",
"(",
")",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"Error",
"(",
"'Ignore files could be parsed for language books'",
")",
")",
";",
"}",
"var",
"fs",
"=",
"book",
".",
"getFS",
"(",
")",
";",
"var",
"ignore",
"=",
"book",
".",
"getIgnore",
"(",
")",
";",
"ignore",
"=",
"ignore",
".",
"add",
"(",
"DEFAULT_IGNORES",
")",
";",
"return",
"Promise",
".",
"serie",
"(",
"IGNORE_FILES",
",",
"function",
"(",
"filename",
")",
"{",
"return",
"fs",
".",
"readAsString",
"(",
"filename",
")",
".",
"then",
"(",
"function",
"(",
"content",
")",
"{",
"ignore",
"=",
"ignore",
".",
"add",
"(",
"content",
".",
"toString",
"(",
")",
".",
"split",
"(",
"/",
"\\r?\\n",
"/",
")",
")",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"return",
"Promise",
"(",
")",
";",
"}",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"book",
".",
"setIgnore",
"(",
"ignore",
")",
";",
"}",
")",
";",
"}"
] |
Parse ignore files
@param {Book}
@return {Book}
|
[
"Parse",
"ignore",
"files"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/parse/parseIgnore.js#L27-L49
|
train
|
GitbookIO/gitbook
|
lib/cli/getOutputFolder.js
|
getOutputFolder
|
function getOutputFolder(args) {
var bookRoot = path.resolve(args[0] || process.cwd());
var defaultOutputRoot = path.join(bookRoot, '_book');
var outputFolder = args[1]? path.resolve(process.cwd(), args[1]) : defaultOutputRoot;
return outputFolder;
}
|
javascript
|
function getOutputFolder(args) {
var bookRoot = path.resolve(args[0] || process.cwd());
var defaultOutputRoot = path.join(bookRoot, '_book');
var outputFolder = args[1]? path.resolve(process.cwd(), args[1]) : defaultOutputRoot;
return outputFolder;
}
|
[
"function",
"getOutputFolder",
"(",
"args",
")",
"{",
"var",
"bookRoot",
"=",
"path",
".",
"resolve",
"(",
"args",
"[",
"0",
"]",
"||",
"process",
".",
"cwd",
"(",
")",
")",
";",
"var",
"defaultOutputRoot",
"=",
"path",
".",
"join",
"(",
"bookRoot",
",",
"'_book'",
")",
";",
"var",
"outputFolder",
"=",
"args",
"[",
"1",
"]",
"?",
"path",
".",
"resolve",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"args",
"[",
"1",
"]",
")",
":",
"defaultOutputRoot",
";",
"return",
"outputFolder",
";",
"}"
] |
Return path to output folder
@param {Array} args
@return {String}
|
[
"Return",
"path",
"to",
"output",
"folder"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/cli/getOutputFolder.js#L9-L15
|
train
|
GitbookIO/gitbook
|
lib/api/decodeConfig.js
|
decodeGlobal
|
function decodeGlobal(config, result) {
var values = result.values;
delete values.generator;
delete values.output;
return config.updateValues(values);
}
|
javascript
|
function decodeGlobal(config, result) {
var values = result.values;
delete values.generator;
delete values.output;
return config.updateValues(values);
}
|
[
"function",
"decodeGlobal",
"(",
"config",
",",
"result",
")",
"{",
"var",
"values",
"=",
"result",
".",
"values",
";",
"delete",
"values",
".",
"generator",
";",
"delete",
"values",
".",
"output",
";",
"return",
"config",
".",
"updateValues",
"(",
"values",
")",
";",
"}"
] |
Decode changes from a JS API to a config object
@param {Config} config
@param {Object} result: result from API
@return {Config}
|
[
"Decode",
"changes",
"from",
"a",
"JS",
"API",
"to",
"a",
"config",
"object"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/api/decodeConfig.js#L8-L15
|
train
|
GitbookIO/gitbook
|
lib/api/encodeNavigation.js
|
encodeNavigation
|
function encodeNavigation(output) {
var book = output.getBook();
var pages = output.getPages();
var summary = book.getSummary();
var articles = summary.getArticlesAsList();
var navigation = articles
.map(function(article, i) {
var ref = article.getRef();
if (!ref) {
return undefined;
}
var prev = articles.get(i - 1);
var next = articles.get(i + 1);
return [
ref,
{
index: i,
title: article.getTitle(),
introduction: (i === 0),
prev: prev? encodeArticle(pages, prev) : undefined,
next: next? encodeArticle(pages, next) : undefined,
level: article.getLevel()
}
];
})
.filter(function(e) {
return Boolean(e);
});
return Immutable.Map(navigation).toJS();
}
|
javascript
|
function encodeNavigation(output) {
var book = output.getBook();
var pages = output.getPages();
var summary = book.getSummary();
var articles = summary.getArticlesAsList();
var navigation = articles
.map(function(article, i) {
var ref = article.getRef();
if (!ref) {
return undefined;
}
var prev = articles.get(i - 1);
var next = articles.get(i + 1);
return [
ref,
{
index: i,
title: article.getTitle(),
introduction: (i === 0),
prev: prev? encodeArticle(pages, prev) : undefined,
next: next? encodeArticle(pages, next) : undefined,
level: article.getLevel()
}
];
})
.filter(function(e) {
return Boolean(e);
});
return Immutable.Map(navigation).toJS();
}
|
[
"function",
"encodeNavigation",
"(",
"output",
")",
"{",
"var",
"book",
"=",
"output",
".",
"getBook",
"(",
")",
";",
"var",
"pages",
"=",
"output",
".",
"getPages",
"(",
")",
";",
"var",
"summary",
"=",
"book",
".",
"getSummary",
"(",
")",
";",
"var",
"articles",
"=",
"summary",
".",
"getArticlesAsList",
"(",
")",
";",
"var",
"navigation",
"=",
"articles",
".",
"map",
"(",
"function",
"(",
"article",
",",
"i",
")",
"{",
"var",
"ref",
"=",
"article",
".",
"getRef",
"(",
")",
";",
"if",
"(",
"!",
"ref",
")",
"{",
"return",
"undefined",
";",
"}",
"var",
"prev",
"=",
"articles",
".",
"get",
"(",
"i",
"-",
"1",
")",
";",
"var",
"next",
"=",
"articles",
".",
"get",
"(",
"i",
"+",
"1",
")",
";",
"return",
"[",
"ref",
",",
"{",
"index",
":",
"i",
",",
"title",
":",
"article",
".",
"getTitle",
"(",
")",
",",
"introduction",
":",
"(",
"i",
"===",
"0",
")",
",",
"prev",
":",
"prev",
"?",
"encodeArticle",
"(",
"pages",
",",
"prev",
")",
":",
"undefined",
",",
"next",
":",
"next",
"?",
"encodeArticle",
"(",
"pages",
",",
"next",
")",
":",
"undefined",
",",
"level",
":",
"article",
".",
"getLevel",
"(",
")",
"}",
"]",
";",
"}",
")",
".",
"filter",
"(",
"function",
"(",
"e",
")",
"{",
"return",
"Boolean",
"(",
"e",
")",
";",
"}",
")",
";",
"return",
"Immutable",
".",
"Map",
"(",
"navigation",
")",
".",
"toJS",
"(",
")",
";",
"}"
] |
this.navigation is a deprecated property from GitBook v2
@param {Output}
@return {Object}
|
[
"this",
".",
"navigation",
"is",
"a",
"deprecated",
"property",
"from",
"GitBook",
"v2"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/api/encodeNavigation.js#L28-L62
|
train
|
GitbookIO/gitbook
|
lib/json/encodeOutput.js
|
encodeOutputToJson
|
function encodeOutputToJson(output) {
var book = output.getBook();
var generator = output.getGenerator();
var options = output.getOptions();
var result = encodeBook(book);
result.output = {
name: generator
};
result.options = options.toJS();
return result;
}
|
javascript
|
function encodeOutputToJson(output) {
var book = output.getBook();
var generator = output.getGenerator();
var options = output.getOptions();
var result = encodeBook(book);
result.output = {
name: generator
};
result.options = options.toJS();
return result;
}
|
[
"function",
"encodeOutputToJson",
"(",
"output",
")",
"{",
"var",
"book",
"=",
"output",
".",
"getBook",
"(",
")",
";",
"var",
"generator",
"=",
"output",
".",
"getGenerator",
"(",
")",
";",
"var",
"options",
"=",
"output",
".",
"getOptions",
"(",
")",
";",
"var",
"result",
"=",
"encodeBook",
"(",
"book",
")",
";",
"result",
".",
"output",
"=",
"{",
"name",
":",
"generator",
"}",
";",
"result",
".",
"options",
"=",
"options",
".",
"toJS",
"(",
")",
";",
"return",
"result",
";",
"}"
] |
Encode an output to JSON
@param {Output}
@return {Object}
|
[
"Encode",
"an",
"output",
"to",
"JSON"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/json/encodeOutput.js#L9-L23
|
train
|
GitbookIO/gitbook
|
lib/parse/parsePage.js
|
parsePage
|
function parsePage(book, page) {
var fs = book.getContentFS();
var file = page.getFile();
return fs.readAsString(file.getPath())
.then(function(content) {
return parsePageFromString(page, content);
});
}
|
javascript
|
function parsePage(book, page) {
var fs = book.getContentFS();
var file = page.getFile();
return fs.readAsString(file.getPath())
.then(function(content) {
return parsePageFromString(page, content);
});
}
|
[
"function",
"parsePage",
"(",
"book",
",",
"page",
")",
"{",
"var",
"fs",
"=",
"book",
".",
"getContentFS",
"(",
")",
";",
"var",
"file",
"=",
"page",
".",
"getFile",
"(",
")",
";",
"return",
"fs",
".",
"readAsString",
"(",
"file",
".",
"getPath",
"(",
")",
")",
".",
"then",
"(",
"function",
"(",
"content",
")",
"{",
"return",
"parsePageFromString",
"(",
"page",
",",
"content",
")",
";",
"}",
")",
";",
"}"
] |
Parse a page, read its content and parse the YAMl header
@param {Book} book
@param {Page} page
@return {Promise<Page>}
|
[
"Parse",
"a",
"page",
"read",
"its",
"content",
"and",
"parse",
"the",
"YAMl",
"header"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/parse/parsePage.js#L10-L18
|
train
|
GitbookIO/gitbook
|
lib/parse/listAssets.js
|
listAssets
|
function listAssets(book, pages) {
var fs = book.getContentFS();
var summary = book.getSummary();
var summaryFile = summary.getFile().getPath();
var glossary = book.getGlossary();
var glossaryFile = glossary.getFile().getPath();
var langs = book.getLanguages();
var langsFile = langs.getFile().getPath();
var config = book.getConfig();
var configFile = config.getFile().getPath();
function filterFile(file) {
return !(
file === summaryFile ||
file === glossaryFile ||
file === langsFile ||
file === configFile ||
book.isContentFileIgnored(file) ||
pages.has(file)
);
}
return timing.measure(
'parse.listAssets',
fs.listAllFiles('.', filterFile)
);
}
|
javascript
|
function listAssets(book, pages) {
var fs = book.getContentFS();
var summary = book.getSummary();
var summaryFile = summary.getFile().getPath();
var glossary = book.getGlossary();
var glossaryFile = glossary.getFile().getPath();
var langs = book.getLanguages();
var langsFile = langs.getFile().getPath();
var config = book.getConfig();
var configFile = config.getFile().getPath();
function filterFile(file) {
return !(
file === summaryFile ||
file === glossaryFile ||
file === langsFile ||
file === configFile ||
book.isContentFileIgnored(file) ||
pages.has(file)
);
}
return timing.measure(
'parse.listAssets',
fs.listAllFiles('.', filterFile)
);
}
|
[
"function",
"listAssets",
"(",
"book",
",",
"pages",
")",
"{",
"var",
"fs",
"=",
"book",
".",
"getContentFS",
"(",
")",
";",
"var",
"summary",
"=",
"book",
".",
"getSummary",
"(",
")",
";",
"var",
"summaryFile",
"=",
"summary",
".",
"getFile",
"(",
")",
".",
"getPath",
"(",
")",
";",
"var",
"glossary",
"=",
"book",
".",
"getGlossary",
"(",
")",
";",
"var",
"glossaryFile",
"=",
"glossary",
".",
"getFile",
"(",
")",
".",
"getPath",
"(",
")",
";",
"var",
"langs",
"=",
"book",
".",
"getLanguages",
"(",
")",
";",
"var",
"langsFile",
"=",
"langs",
".",
"getFile",
"(",
")",
".",
"getPath",
"(",
")",
";",
"var",
"config",
"=",
"book",
".",
"getConfig",
"(",
")",
";",
"var",
"configFile",
"=",
"config",
".",
"getFile",
"(",
")",
".",
"getPath",
"(",
")",
";",
"function",
"filterFile",
"(",
"file",
")",
"{",
"return",
"!",
"(",
"file",
"===",
"summaryFile",
"||",
"file",
"===",
"glossaryFile",
"||",
"file",
"===",
"langsFile",
"||",
"file",
"===",
"configFile",
"||",
"book",
".",
"isContentFileIgnored",
"(",
"file",
")",
"||",
"pages",
".",
"has",
"(",
"file",
")",
")",
";",
"}",
"return",
"timing",
".",
"measure",
"(",
"'parse.listAssets'",
",",
"fs",
".",
"listAllFiles",
"(",
"'.'",
",",
"filterFile",
")",
")",
";",
"}"
] |
List all assets in a book
Assets are file not ignored and not a page
@param {Book} book
@param {List<String>} pages
@param
|
[
"List",
"all",
"assets",
"in",
"a",
"book",
"Assets",
"are",
"file",
"not",
"ignored",
"and",
"not",
"a",
"page"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/parse/listAssets.js#L11-L41
|
train
|
GitbookIO/gitbook
|
lib/fs/mock.js
|
createMockFS
|
function createMockFS(files) {
files = Immutable.fromJS(files);
var mtime = new Date();
function getFile(filePath) {
var parts = path.normalize(filePath).split(path.sep);
return parts.reduce(function(list, part, i) {
if (!list) return null;
var file;
if (!part || part === '.') file = list;
else file = list.get(part);
if (!file) return null;
if (is.string(file)) {
if (i === (parts.length - 1)) return file;
else return null;
}
return file;
}, files);
}
function fsExists(filePath) {
return Boolean(getFile(filePath) !== null);
}
function fsReadFile(filePath) {
var file = getFile(filePath);
if (!is.string(file)) {
throw error.FileNotFoundError({
filename: filePath
});
}
return new Buffer(file, 'utf8');
}
function fsStatFile(filePath) {
var file = getFile(filePath);
if (!file) {
throw error.FileNotFoundError({
filename: filePath
});
}
return {
mtime: mtime
};
}
function fsReadDir(filePath) {
var dir = getFile(filePath);
if (!dir || is.string(dir)) {
throw error.FileNotFoundError({
filename: filePath
});
}
return dir
.map(function(content, name) {
if (!is.string(content)) {
name = name + '/';
}
return name;
})
.valueSeq();
}
return FS.create({
root: '',
fsExists: fsExists,
fsReadFile: fsReadFile,
fsStatFile: fsStatFile,
fsReadDir: fsReadDir
});
}
|
javascript
|
function createMockFS(files) {
files = Immutable.fromJS(files);
var mtime = new Date();
function getFile(filePath) {
var parts = path.normalize(filePath).split(path.sep);
return parts.reduce(function(list, part, i) {
if (!list) return null;
var file;
if (!part || part === '.') file = list;
else file = list.get(part);
if (!file) return null;
if (is.string(file)) {
if (i === (parts.length - 1)) return file;
else return null;
}
return file;
}, files);
}
function fsExists(filePath) {
return Boolean(getFile(filePath) !== null);
}
function fsReadFile(filePath) {
var file = getFile(filePath);
if (!is.string(file)) {
throw error.FileNotFoundError({
filename: filePath
});
}
return new Buffer(file, 'utf8');
}
function fsStatFile(filePath) {
var file = getFile(filePath);
if (!file) {
throw error.FileNotFoundError({
filename: filePath
});
}
return {
mtime: mtime
};
}
function fsReadDir(filePath) {
var dir = getFile(filePath);
if (!dir || is.string(dir)) {
throw error.FileNotFoundError({
filename: filePath
});
}
return dir
.map(function(content, name) {
if (!is.string(content)) {
name = name + '/';
}
return name;
})
.valueSeq();
}
return FS.create({
root: '',
fsExists: fsExists,
fsReadFile: fsReadFile,
fsStatFile: fsStatFile,
fsReadDir: fsReadDir
});
}
|
[
"function",
"createMockFS",
"(",
"files",
")",
"{",
"files",
"=",
"Immutable",
".",
"fromJS",
"(",
"files",
")",
";",
"var",
"mtime",
"=",
"new",
"Date",
"(",
")",
";",
"function",
"getFile",
"(",
"filePath",
")",
"{",
"var",
"parts",
"=",
"path",
".",
"normalize",
"(",
"filePath",
")",
".",
"split",
"(",
"path",
".",
"sep",
")",
";",
"return",
"parts",
".",
"reduce",
"(",
"function",
"(",
"list",
",",
"part",
",",
"i",
")",
"{",
"if",
"(",
"!",
"list",
")",
"return",
"null",
";",
"var",
"file",
";",
"if",
"(",
"!",
"part",
"||",
"part",
"===",
"'.'",
")",
"file",
"=",
"list",
";",
"else",
"file",
"=",
"list",
".",
"get",
"(",
"part",
")",
";",
"if",
"(",
"!",
"file",
")",
"return",
"null",
";",
"if",
"(",
"is",
".",
"string",
"(",
"file",
")",
")",
"{",
"if",
"(",
"i",
"===",
"(",
"parts",
".",
"length",
"-",
"1",
")",
")",
"return",
"file",
";",
"else",
"return",
"null",
";",
"}",
"return",
"file",
";",
"}",
",",
"files",
")",
";",
"}",
"function",
"fsExists",
"(",
"filePath",
")",
"{",
"return",
"Boolean",
"(",
"getFile",
"(",
"filePath",
")",
"!==",
"null",
")",
";",
"}",
"function",
"fsReadFile",
"(",
"filePath",
")",
"{",
"var",
"file",
"=",
"getFile",
"(",
"filePath",
")",
";",
"if",
"(",
"!",
"is",
".",
"string",
"(",
"file",
")",
")",
"{",
"throw",
"error",
".",
"FileNotFoundError",
"(",
"{",
"filename",
":",
"filePath",
"}",
")",
";",
"}",
"return",
"new",
"Buffer",
"(",
"file",
",",
"'utf8'",
")",
";",
"}",
"function",
"fsStatFile",
"(",
"filePath",
")",
"{",
"var",
"file",
"=",
"getFile",
"(",
"filePath",
")",
";",
"if",
"(",
"!",
"file",
")",
"{",
"throw",
"error",
".",
"FileNotFoundError",
"(",
"{",
"filename",
":",
"filePath",
"}",
")",
";",
"}",
"return",
"{",
"mtime",
":",
"mtime",
"}",
";",
"}",
"function",
"fsReadDir",
"(",
"filePath",
")",
"{",
"var",
"dir",
"=",
"getFile",
"(",
"filePath",
")",
";",
"if",
"(",
"!",
"dir",
"||",
"is",
".",
"string",
"(",
"dir",
")",
")",
"{",
"throw",
"error",
".",
"FileNotFoundError",
"(",
"{",
"filename",
":",
"filePath",
"}",
")",
";",
"}",
"return",
"dir",
".",
"map",
"(",
"function",
"(",
"content",
",",
"name",
")",
"{",
"if",
"(",
"!",
"is",
".",
"string",
"(",
"content",
")",
")",
"{",
"name",
"=",
"name",
"+",
"'/'",
";",
"}",
"return",
"name",
";",
"}",
")",
".",
"valueSeq",
"(",
")",
";",
"}",
"return",
"FS",
".",
"create",
"(",
"{",
"root",
":",
"''",
",",
"fsExists",
":",
"fsExists",
",",
"fsReadFile",
":",
"fsReadFile",
",",
"fsStatFile",
":",
"fsStatFile",
",",
"fsReadDir",
":",
"fsReadDir",
"}",
")",
";",
"}"
] |
Create a fake filesystem for unit testing GitBook.
@param {Map<String:String|Map>}
|
[
"Create",
"a",
"fake",
"filesystem",
"for",
"unit",
"testing",
"GitBook",
"."
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/fs/mock.js#L14-L93
|
train
|
GitbookIO/gitbook
|
lib/utils/fs.js
|
fileExists
|
function fileExists(filename) {
var d = Promise.defer();
fs.exists(filename, function(exists) {
d.resolve(exists);
});
return d.promise;
}
|
javascript
|
function fileExists(filename) {
var d = Promise.defer();
fs.exists(filename, function(exists) {
d.resolve(exists);
});
return d.promise;
}
|
[
"function",
"fileExists",
"(",
"filename",
")",
"{",
"var",
"d",
"=",
"Promise",
".",
"defer",
"(",
")",
";",
"fs",
".",
"exists",
"(",
"filename",
",",
"function",
"(",
"exists",
")",
"{",
"d",
".",
"resolve",
"(",
"exists",
")",
";",
"}",
")",
";",
"return",
"d",
".",
"promise",
";",
"}"
] |
Return a promise resolved with a boolean
|
[
"Return",
"a",
"promise",
"resolved",
"with",
"a",
"boolean"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/utils/fs.js#L43-L51
|
train
|
GitbookIO/gitbook
|
lib/utils/fs.js
|
ensureFile
|
function ensureFile(filename) {
var base = path.dirname(filename);
return Promise.nfcall(mkdirp, base);
}
|
javascript
|
function ensureFile(filename) {
var base = path.dirname(filename);
return Promise.nfcall(mkdirp, base);
}
|
[
"function",
"ensureFile",
"(",
"filename",
")",
"{",
"var",
"base",
"=",
"path",
".",
"dirname",
"(",
"filename",
")",
";",
"return",
"Promise",
".",
"nfcall",
"(",
"mkdirp",
",",
"base",
")",
";",
"}"
] |
Create all required folder to create a file
|
[
"Create",
"all",
"required",
"folder",
"to",
"create",
"a",
"file"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/utils/fs.js#L88-L91
|
train
|
GitbookIO/gitbook
|
lib/utils/fs.js
|
pickFile
|
function pickFile(rootFolder, fileName) {
var result = path.join(rootFolder, fileName);
if (fs.existsSync(result)) {
return result;
}
return undefined;
}
|
javascript
|
function pickFile(rootFolder, fileName) {
var result = path.join(rootFolder, fileName);
if (fs.existsSync(result)) {
return result;
}
return undefined;
}
|
[
"function",
"pickFile",
"(",
"rootFolder",
",",
"fileName",
")",
"{",
"var",
"result",
"=",
"path",
".",
"join",
"(",
"rootFolder",
",",
"fileName",
")",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"result",
")",
")",
"{",
"return",
"result",
";",
"}",
"return",
"undefined",
";",
"}"
] |
Pick a file, returns the absolute path if exists, undefined otherwise
@param {String} rootFolder
@param {String} fileName
@return {String}
|
[
"Pick",
"a",
"file",
"returns",
"the",
"absolute",
"path",
"if",
"exists",
"undefined",
"otherwise"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/utils/fs.js#L123-L130
|
train
|
GitbookIO/gitbook
|
lib/utils/fs.js
|
ensureFolder
|
function ensureFolder(rootFolder) {
return rmDir(rootFolder)
.fail(function() {
return Promise();
})
.then(function() {
return Promise.nfcall(mkdirp, rootFolder);
});
}
|
javascript
|
function ensureFolder(rootFolder) {
return rmDir(rootFolder)
.fail(function() {
return Promise();
})
.then(function() {
return Promise.nfcall(mkdirp, rootFolder);
});
}
|
[
"function",
"ensureFolder",
"(",
"rootFolder",
")",
"{",
"return",
"rmDir",
"(",
"rootFolder",
")",
".",
"fail",
"(",
"function",
"(",
")",
"{",
"return",
"Promise",
"(",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"Promise",
".",
"nfcall",
"(",
"mkdirp",
",",
"rootFolder",
")",
";",
"}",
")",
";",
"}"
] |
Ensure that a directory exists and is empty
@param {String} folder
@return {Promise}
|
[
"Ensure",
"that",
"a",
"directory",
"exists",
"and",
"is",
"empty"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/utils/fs.js#L138-L146
|
train
|
GitbookIO/gitbook
|
lib/api/decodeGlobal.js
|
decodeGlobal
|
function decodeGlobal(output, result) {
var book = output.getBook();
var config = book.getConfig();
// Update config
config = decodeConfig(config, result.config);
book = book.set('config', config);
return output.set('book', book);
}
|
javascript
|
function decodeGlobal(output, result) {
var book = output.getBook();
var config = book.getConfig();
// Update config
config = decodeConfig(config, result.config);
book = book.set('config', config);
return output.set('book', book);
}
|
[
"function",
"decodeGlobal",
"(",
"output",
",",
"result",
")",
"{",
"var",
"book",
"=",
"output",
".",
"getBook",
"(",
")",
";",
"var",
"config",
"=",
"book",
".",
"getConfig",
"(",
")",
";",
"config",
"=",
"decodeConfig",
"(",
"config",
",",
"result",
".",
"config",
")",
";",
"book",
"=",
"book",
".",
"set",
"(",
"'config'",
",",
"config",
")",
";",
"return",
"output",
".",
"set",
"(",
"'book'",
",",
"book",
")",
";",
"}"
] |
Decode changes from a JS API to a output object.
Only the configuration can be edited by plugin's hooks
@param {Output} output
@param {Object} result: result from API
@return {Output}
|
[
"Decode",
"changes",
"from",
"a",
"JS",
"API",
"to",
"a",
"output",
"object",
".",
"Only",
"the",
"configuration",
"can",
"be",
"edited",
"by",
"plugin",
"s",
"hooks"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/api/decodeGlobal.js#L11-L20
|
train
|
GitbookIO/gitbook
|
lib/json/encodeFile.js
|
encodeFileToJson
|
function encodeFileToJson(file) {
var filePath = file.getPath();
if (!filePath) {
return undefined;
}
return {
path: filePath,
mtime: file.getMTime(),
type: file.getType()
};
}
|
javascript
|
function encodeFileToJson(file) {
var filePath = file.getPath();
if (!filePath) {
return undefined;
}
return {
path: filePath,
mtime: file.getMTime(),
type: file.getType()
};
}
|
[
"function",
"encodeFileToJson",
"(",
"file",
")",
"{",
"var",
"filePath",
"=",
"file",
".",
"getPath",
"(",
")",
";",
"if",
"(",
"!",
"filePath",
")",
"{",
"return",
"undefined",
";",
"}",
"return",
"{",
"path",
":",
"filePath",
",",
"mtime",
":",
"file",
".",
"getMTime",
"(",
")",
",",
"type",
":",
"file",
".",
"getType",
"(",
")",
"}",
";",
"}"
] |
Return a JSON representation of a file
@param {File} file
@return {Object}
|
[
"Return",
"a",
"JSON",
"representation",
"of",
"a",
"file"
] |
6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4
|
https://github.com/GitbookIO/gitbook/blob/6c6ef7f4af32a2977e44dd23d3feb6ebf28970f4/lib/json/encodeFile.js#L8-L19
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.