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
babel/babel
packages/babel-plugin-proposal-object-rest-spread/src/index.js
replaceImpureComputedKeys
function replaceImpureComputedKeys(path) { const impureComputedPropertyDeclarators = []; for (const propPath of path.get("properties")) { const key = propPath.get("key"); if (propPath.node.computed && !key.isPure()) { const name = path.scope.generateUidBasedOnNode(key.node); const declarator = t.variableDeclarator(t.identifier(name), key.node); impureComputedPropertyDeclarators.push(declarator); key.replaceWith(t.identifier(name)); } } return impureComputedPropertyDeclarators; }
javascript
function replaceImpureComputedKeys(path) { const impureComputedPropertyDeclarators = []; for (const propPath of path.get("properties")) { const key = propPath.get("key"); if (propPath.node.computed && !key.isPure()) { const name = path.scope.generateUidBasedOnNode(key.node); const declarator = t.variableDeclarator(t.identifier(name), key.node); impureComputedPropertyDeclarators.push(declarator); key.replaceWith(t.identifier(name)); } } return impureComputedPropertyDeclarators; }
[ "function", "replaceImpureComputedKeys", "(", "path", ")", "{", "const", "impureComputedPropertyDeclarators", "=", "[", "]", ";", "for", "(", "const", "propPath", "of", "path", ".", "get", "(", "\"properties\"", ")", ")", "{", "const", "key", "=", "propPath", ".", "get", "(", "\"key\"", ")", ";", "if", "(", "propPath", ".", "node", ".", "computed", "&&", "!", "key", ".", "isPure", "(", ")", ")", "{", "const", "name", "=", "path", ".", "scope", ".", "generateUidBasedOnNode", "(", "key", ".", "node", ")", ";", "const", "declarator", "=", "t", ".", "variableDeclarator", "(", "t", ".", "identifier", "(", "name", ")", ",", "key", ".", "node", ")", ";", "impureComputedPropertyDeclarators", ".", "push", "(", "declarator", ")", ";", "key", ".", "replaceWith", "(", "t", ".", "identifier", "(", "name", ")", ")", ";", "}", "}", "return", "impureComputedPropertyDeclarators", ";", "}" ]
replaces impure computed keys with new identifiers and returns variable declarators of these new identifiers
[ "replaces", "impure", "computed", "keys", "with", "new", "identifiers", "and", "returns", "variable", "declarators", "of", "these", "new", "identifiers" ]
1969e6b6aa7d90be3fbb3aca98ea96849656a55a
https://github.com/babel/babel/blob/1969e6b6aa7d90be3fbb3aca98ea96849656a55a/packages/babel-plugin-proposal-object-rest-spread/src/index.js#L94-L106
train
babel/babel
packages/babel-plugin-proposal-object-rest-spread/src/index.js
createObjectSpread
function createObjectSpread(path, file, objRef) { const props = path.get("properties"); const last = props[props.length - 1]; t.assertRestElement(last.node); const restElement = t.cloneNode(last.node); last.remove(); const impureComputedPropertyDeclarators = replaceImpureComputedKeys(path); const { keys, allLiteral } = extractNormalizedKeys(path); if (keys.length === 0) { return [ impureComputedPropertyDeclarators, restElement.argument, t.callExpression(getExtendsHelper(file), [ t.objectExpression([]), t.cloneNode(objRef), ]), ]; } let keyExpression; if (!allLiteral) { // map to toPropertyKey to handle the possible non-string values keyExpression = t.callExpression( t.memberExpression(t.arrayExpression(keys), t.identifier("map")), [file.addHelper("toPropertyKey")], ); } else { keyExpression = t.arrayExpression(keys); } return [ impureComputedPropertyDeclarators, restElement.argument, t.callExpression( file.addHelper(`objectWithoutProperties${loose ? "Loose" : ""}`), [t.cloneNode(objRef), keyExpression], ), ]; }
javascript
function createObjectSpread(path, file, objRef) { const props = path.get("properties"); const last = props[props.length - 1]; t.assertRestElement(last.node); const restElement = t.cloneNode(last.node); last.remove(); const impureComputedPropertyDeclarators = replaceImpureComputedKeys(path); const { keys, allLiteral } = extractNormalizedKeys(path); if (keys.length === 0) { return [ impureComputedPropertyDeclarators, restElement.argument, t.callExpression(getExtendsHelper(file), [ t.objectExpression([]), t.cloneNode(objRef), ]), ]; } let keyExpression; if (!allLiteral) { // map to toPropertyKey to handle the possible non-string values keyExpression = t.callExpression( t.memberExpression(t.arrayExpression(keys), t.identifier("map")), [file.addHelper("toPropertyKey")], ); } else { keyExpression = t.arrayExpression(keys); } return [ impureComputedPropertyDeclarators, restElement.argument, t.callExpression( file.addHelper(`objectWithoutProperties${loose ? "Loose" : ""}`), [t.cloneNode(objRef), keyExpression], ), ]; }
[ "function", "createObjectSpread", "(", "path", ",", "file", ",", "objRef", ")", "{", "const", "props", "=", "path", ".", "get", "(", "\"properties\"", ")", ";", "const", "last", "=", "props", "[", "props", ".", "length", "-", "1", "]", ";", "t", ".", "assertRestElement", "(", "last", ".", "node", ")", ";", "const", "restElement", "=", "t", ".", "cloneNode", "(", "last", ".", "node", ")", ";", "last", ".", "remove", "(", ")", ";", "const", "impureComputedPropertyDeclarators", "=", "replaceImpureComputedKeys", "(", "path", ")", ";", "const", "{", "keys", ",", "allLiteral", "}", "=", "extractNormalizedKeys", "(", "path", ")", ";", "if", "(", "keys", ".", "length", "===", "0", ")", "{", "return", "[", "impureComputedPropertyDeclarators", ",", "restElement", ".", "argument", ",", "t", ".", "callExpression", "(", "getExtendsHelper", "(", "file", ")", ",", "[", "t", ".", "objectExpression", "(", "[", "]", ")", ",", "t", ".", "cloneNode", "(", "objRef", ")", ",", "]", ")", ",", "]", ";", "}", "let", "keyExpression", ";", "if", "(", "!", "allLiteral", ")", "{", "keyExpression", "=", "t", ".", "callExpression", "(", "t", ".", "memberExpression", "(", "t", ".", "arrayExpression", "(", "keys", ")", ",", "t", ".", "identifier", "(", "\"map\"", ")", ")", ",", "[", "file", ".", "addHelper", "(", "\"toPropertyKey\"", ")", "]", ",", ")", ";", "}", "else", "{", "keyExpression", "=", "t", ".", "arrayExpression", "(", "keys", ")", ";", "}", "return", "[", "impureComputedPropertyDeclarators", ",", "restElement", ".", "argument", ",", "t", ".", "callExpression", "(", "file", ".", "addHelper", "(", "`", "${", "loose", "?", "\"Loose\"", ":", "\"\"", "}", "`", ")", ",", "[", "t", ".", "cloneNode", "(", "objRef", ")", ",", "keyExpression", "]", ",", ")", ",", "]", ";", "}" ]
expects path to an object pattern
[ "expects", "path", "to", "an", "object", "pattern" ]
1969e6b6aa7d90be3fbb3aca98ea96849656a55a
https://github.com/babel/babel/blob/1969e6b6aa7d90be3fbb3aca98ea96849656a55a/packages/babel-plugin-proposal-object-rest-spread/src/index.js#L124-L164
train
babel/babel
packages/babel-helper-module-transforms/src/index.js
buildInitStatement
function buildInitStatement(metadata, exportNames, initExpr) { return t.expressionStatement( exportNames.reduce( (acc, exportName) => template.expression`EXPORTS.NAME = VALUE`({ EXPORTS: metadata.exportName, NAME: exportName, VALUE: acc, }), initExpr, ), ); }
javascript
function buildInitStatement(metadata, exportNames, initExpr) { return t.expressionStatement( exportNames.reduce( (acc, exportName) => template.expression`EXPORTS.NAME = VALUE`({ EXPORTS: metadata.exportName, NAME: exportName, VALUE: acc, }), initExpr, ), ); }
[ "function", "buildInitStatement", "(", "metadata", ",", "exportNames", ",", "initExpr", ")", "{", "return", "t", ".", "expressionStatement", "(", "exportNames", ".", "reduce", "(", "(", "acc", ",", "exportName", ")", "=>", "template", ".", "expression", "`", "`", "(", "{", "EXPORTS", ":", "metadata", ".", "exportName", ",", "NAME", ":", "exportName", ",", "VALUE", ":", "acc", ",", "}", ")", ",", "initExpr", ",", ")", ",", ")", ";", "}" ]
Given a set of export names, create a set of nested assignments to initialize them all to a given expression.
[ "Given", "a", "set", "of", "export", "names", "create", "a", "set", "of", "nested", "assignments", "to", "initialize", "them", "all", "to", "a", "given", "expression", "." ]
1969e6b6aa7d90be3fbb3aca98ea96849656a55a
https://github.com/babel/babel/blob/1969e6b6aa7d90be3fbb3aca98ea96849656a55a/packages/babel-helper-module-transforms/src/index.js#L356-L368
train
babel/babel
packages/babel-code-frame/src/index.js
getDefs
function getDefs(chalk) { return { gutter: chalk.grey, marker: chalk.red.bold, message: chalk.red.bold, }; }
javascript
function getDefs(chalk) { return { gutter: chalk.grey, marker: chalk.red.bold, message: chalk.red.bold, }; }
[ "function", "getDefs", "(", "chalk", ")", "{", "return", "{", "gutter", ":", "chalk", ".", "grey", ",", "marker", ":", "chalk", ".", "red", ".", "bold", ",", "message", ":", "chalk", ".", "red", ".", "bold", ",", "}", ";", "}" ]
Chalk styles for code frame token types.
[ "Chalk", "styles", "for", "code", "frame", "token", "types", "." ]
1969e6b6aa7d90be3fbb3aca98ea96849656a55a
https://github.com/babel/babel/blob/1969e6b6aa7d90be3fbb3aca98ea96849656a55a/packages/babel-code-frame/src/index.js#L18-L24
train
babel/babel
packages/babel-standalone/src/transformScriptTags.js
load
function load(url, successCallback, errorCallback) { const xhr = new XMLHttpRequest(); // async, however scripts will be executed in the order they are in the // DOM to mirror normal script loading. xhr.open("GET", url, true); if ("overrideMimeType" in xhr) { xhr.overrideMimeType("text/plain"); } xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status === 0 || xhr.status === 200) { successCallback(xhr.responseText); } else { errorCallback(); throw new Error("Could not load " + url); } } }; return xhr.send(null); }
javascript
function load(url, successCallback, errorCallback) { const xhr = new XMLHttpRequest(); // async, however scripts will be executed in the order they are in the // DOM to mirror normal script loading. xhr.open("GET", url, true); if ("overrideMimeType" in xhr) { xhr.overrideMimeType("text/plain"); } xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status === 0 || xhr.status === 200) { successCallback(xhr.responseText); } else { errorCallback(); throw new Error("Could not load " + url); } } }; return xhr.send(null); }
[ "function", "load", "(", "url", ",", "successCallback", ",", "errorCallback", ")", "{", "const", "xhr", "=", "new", "XMLHttpRequest", "(", ")", ";", "xhr", ".", "open", "(", "\"GET\"", ",", "url", ",", "true", ")", ";", "if", "(", "\"overrideMimeType\"", "in", "xhr", ")", "{", "xhr", ".", "overrideMimeType", "(", "\"text/plain\"", ")", ";", "}", "xhr", ".", "onreadystatechange", "=", "function", "(", ")", "{", "if", "(", "xhr", ".", "readyState", "===", "4", ")", "{", "if", "(", "xhr", ".", "status", "===", "0", "||", "xhr", ".", "status", "===", "200", ")", "{", "successCallback", "(", "xhr", ".", "responseText", ")", ";", "}", "else", "{", "errorCallback", "(", ")", ";", "throw", "new", "Error", "(", "\"Could not load \"", "+", "url", ")", ";", "}", "}", "}", ";", "return", "xhr", ".", "send", "(", "null", ")", ";", "}" ]
Load script from the provided url and pass the content to the callback.
[ "Load", "script", "from", "the", "provided", "url", "and", "pass", "the", "content", "to", "the", "callback", "." ]
1969e6b6aa7d90be3fbb3aca98ea96849656a55a
https://github.com/babel/babel/blob/1969e6b6aa7d90be3fbb3aca98ea96849656a55a/packages/babel-standalone/src/transformScriptTags.js#L64-L84
train
babel/babel
packages/babel-standalone/src/transformScriptTags.js
getPluginsOrPresetsFromScript
function getPluginsOrPresetsFromScript(script, attributeName) { const rawValue = script.getAttribute(attributeName); if (rawValue === "") { // Empty string means to not load ANY presets or plugins return []; } if (!rawValue) { // Any other falsy value (null, undefined) means we're not overriding this // setting, and should use the default. return null; } return rawValue.split(",").map(item => item.trim()); }
javascript
function getPluginsOrPresetsFromScript(script, attributeName) { const rawValue = script.getAttribute(attributeName); if (rawValue === "") { // Empty string means to not load ANY presets or plugins return []; } if (!rawValue) { // Any other falsy value (null, undefined) means we're not overriding this // setting, and should use the default. return null; } return rawValue.split(",").map(item => item.trim()); }
[ "function", "getPluginsOrPresetsFromScript", "(", "script", ",", "attributeName", ")", "{", "const", "rawValue", "=", "script", ".", "getAttribute", "(", "attributeName", ")", ";", "if", "(", "rawValue", "===", "\"\"", ")", "{", "return", "[", "]", ";", "}", "if", "(", "!", "rawValue", ")", "{", "return", "null", ";", "}", "return", "rawValue", ".", "split", "(", "\",\"", ")", ".", "map", "(", "item", "=>", "item", ".", "trim", "(", ")", ")", ";", "}" ]
Converts a comma-separated data attribute string into an array of values. If the string is empty, returns an empty array. If the string is not defined, returns null.
[ "Converts", "a", "comma", "-", "separated", "data", "attribute", "string", "into", "an", "array", "of", "values", ".", "If", "the", "string", "is", "empty", "returns", "an", "empty", "array", ".", "If", "the", "string", "is", "not", "defined", "returns", "null", "." ]
1969e6b6aa7d90be3fbb3aca98ea96849656a55a
https://github.com/babel/babel/blob/1969e6b6aa7d90be3fbb3aca98ea96849656a55a/packages/babel-standalone/src/transformScriptTags.js#L91-L103
train
babel/babel
packages/babel-traverse/src/path/evaluation.js
deopt
function deopt(path, state) { if (!state.confident) return; state.deoptPath = path; state.confident = false; }
javascript
function deopt(path, state) { if (!state.confident) return; state.deoptPath = path; state.confident = false; }
[ "function", "deopt", "(", "path", ",", "state", ")", "{", "if", "(", "!", "state", ".", "confident", ")", "return", ";", "state", ".", "deoptPath", "=", "path", ";", "state", ".", "confident", "=", "false", ";", "}" ]
Deopts the evaluation
[ "Deopts", "the", "evaluation" ]
1969e6b6aa7d90be3fbb3aca98ea96849656a55a
https://github.com/babel/babel/blob/1969e6b6aa7d90be3fbb3aca98ea96849656a55a/packages/babel-traverse/src/path/evaluation.js#L34-L38
train
babel/babel
packages/babel-helper-replace-supers/src/index.js
getPrototypeOfExpression
function getPrototypeOfExpression(objectRef, isStatic, file, isPrivateMethod) { objectRef = t.cloneNode(objectRef); const targetRef = isStatic || isPrivateMethod ? objectRef : t.memberExpression(objectRef, t.identifier("prototype")); return t.callExpression(file.addHelper("getPrototypeOf"), [targetRef]); }
javascript
function getPrototypeOfExpression(objectRef, isStatic, file, isPrivateMethod) { objectRef = t.cloneNode(objectRef); const targetRef = isStatic || isPrivateMethod ? objectRef : t.memberExpression(objectRef, t.identifier("prototype")); return t.callExpression(file.addHelper("getPrototypeOf"), [targetRef]); }
[ "function", "getPrototypeOfExpression", "(", "objectRef", ",", "isStatic", ",", "file", ",", "isPrivateMethod", ")", "{", "objectRef", "=", "t", ".", "cloneNode", "(", "objectRef", ")", ";", "const", "targetRef", "=", "isStatic", "||", "isPrivateMethod", "?", "objectRef", ":", "t", ".", "memberExpression", "(", "objectRef", ",", "t", ".", "identifier", "(", "\"prototype\"", ")", ")", ";", "return", "t", ".", "callExpression", "(", "file", ".", "addHelper", "(", "\"getPrototypeOf\"", ")", ",", "[", "targetRef", "]", ")", ";", "}" ]
Creates an expression which result is the proto of objectRef. @example <caption>isStatic === true</caption> helpers.getPrototypeOf(CLASS) @example <caption>isStatic === false</caption> helpers.getPrototypeOf(CLASS.prototype)
[ "Creates", "an", "expression", "which", "result", "is", "the", "proto", "of", "objectRef", "." ]
1969e6b6aa7d90be3fbb3aca98ea96849656a55a
https://github.com/babel/babel/blob/1969e6b6aa7d90be3fbb3aca98ea96849656a55a/packages/babel-helper-replace-supers/src/index.js#L18-L26
train
babel/babel
packages/babel-plugin-proposal-decorators/src/transformer-legacy.js
applyEnsureOrdering
function applyEnsureOrdering(path) { // TODO: This should probably also hoist computed properties. const decorators = (path.isClass() ? [path].concat(path.get("body.body")) : path.get("properties") ).reduce((acc, prop) => acc.concat(prop.node.decorators || []), []); const identDecorators = decorators.filter( decorator => !t.isIdentifier(decorator.expression), ); if (identDecorators.length === 0) return; return t.sequenceExpression( identDecorators .map(decorator => { const expression = decorator.expression; const id = (decorator.expression = path.scope.generateDeclaredUidIdentifier( "dec", )); return t.assignmentExpression("=", id, expression); }) .concat([path.node]), ); }
javascript
function applyEnsureOrdering(path) { // TODO: This should probably also hoist computed properties. const decorators = (path.isClass() ? [path].concat(path.get("body.body")) : path.get("properties") ).reduce((acc, prop) => acc.concat(prop.node.decorators || []), []); const identDecorators = decorators.filter( decorator => !t.isIdentifier(decorator.expression), ); if (identDecorators.length === 0) return; return t.sequenceExpression( identDecorators .map(decorator => { const expression = decorator.expression; const id = (decorator.expression = path.scope.generateDeclaredUidIdentifier( "dec", )); return t.assignmentExpression("=", id, expression); }) .concat([path.node]), ); }
[ "function", "applyEnsureOrdering", "(", "path", ")", "{", "const", "decorators", "=", "(", "path", ".", "isClass", "(", ")", "?", "[", "path", "]", ".", "concat", "(", "path", ".", "get", "(", "\"body.body\"", ")", ")", ":", "path", ".", "get", "(", "\"properties\"", ")", ")", ".", "reduce", "(", "(", "acc", ",", "prop", ")", "=>", "acc", ".", "concat", "(", "prop", ".", "node", ".", "decorators", "||", "[", "]", ")", ",", "[", "]", ")", ";", "const", "identDecorators", "=", "decorators", ".", "filter", "(", "decorator", "=>", "!", "t", ".", "isIdentifier", "(", "decorator", ".", "expression", ")", ",", ")", ";", "if", "(", "identDecorators", ".", "length", "===", "0", ")", "return", ";", "return", "t", ".", "sequenceExpression", "(", "identDecorators", ".", "map", "(", "decorator", "=>", "{", "const", "expression", "=", "decorator", ".", "expression", ";", "const", "id", "=", "(", "decorator", ".", "expression", "=", "path", ".", "scope", ".", "generateDeclaredUidIdentifier", "(", "\"dec\"", ",", ")", ")", ";", "return", "t", ".", "assignmentExpression", "(", "\"=\"", ",", "id", ",", "expression", ")", ";", "}", ")", ".", "concat", "(", "[", "path", ".", "node", "]", ")", ",", ")", ";", "}" ]
If the decorator expressions are non-identifiers, hoist them to before the class so we can be sure that they are evaluated in order.
[ "If", "the", "decorator", "expressions", "are", "non", "-", "identifiers", "hoist", "them", "to", "before", "the", "class", "so", "we", "can", "be", "sure", "that", "they", "are", "evaluated", "in", "order", "." ]
1969e6b6aa7d90be3fbb3aca98ea96849656a55a
https://github.com/babel/babel/blob/1969e6b6aa7d90be3fbb3aca98ea96849656a55a/packages/babel-plugin-proposal-decorators/src/transformer-legacy.js#L34-L57
train
babel/babel
packages/babel-plugin-proposal-decorators/src/transformer-legacy.js
applyClassDecorators
function applyClassDecorators(classPath) { if (!hasClassDecorators(classPath.node)) return; const decorators = classPath.node.decorators || []; classPath.node.decorators = null; const name = classPath.scope.generateDeclaredUidIdentifier("class"); return decorators .map(dec => dec.expression) .reverse() .reduce(function(acc, decorator) { return buildClassDecorator({ CLASS_REF: t.cloneNode(name), DECORATOR: t.cloneNode(decorator), INNER: acc, }).expression; }, classPath.node); }
javascript
function applyClassDecorators(classPath) { if (!hasClassDecorators(classPath.node)) return; const decorators = classPath.node.decorators || []; classPath.node.decorators = null; const name = classPath.scope.generateDeclaredUidIdentifier("class"); return decorators .map(dec => dec.expression) .reverse() .reduce(function(acc, decorator) { return buildClassDecorator({ CLASS_REF: t.cloneNode(name), DECORATOR: t.cloneNode(decorator), INNER: acc, }).expression; }, classPath.node); }
[ "function", "applyClassDecorators", "(", "classPath", ")", "{", "if", "(", "!", "hasClassDecorators", "(", "classPath", ".", "node", ")", ")", "return", ";", "const", "decorators", "=", "classPath", ".", "node", ".", "decorators", "||", "[", "]", ";", "classPath", ".", "node", ".", "decorators", "=", "null", ";", "const", "name", "=", "classPath", ".", "scope", ".", "generateDeclaredUidIdentifier", "(", "\"class\"", ")", ";", "return", "decorators", ".", "map", "(", "dec", "=>", "dec", ".", "expression", ")", ".", "reverse", "(", ")", ".", "reduce", "(", "function", "(", "acc", ",", "decorator", ")", "{", "return", "buildClassDecorator", "(", "{", "CLASS_REF", ":", "t", ".", "cloneNode", "(", "name", ")", ",", "DECORATOR", ":", "t", ".", "cloneNode", "(", "decorator", ")", ",", "INNER", ":", "acc", ",", "}", ")", ".", "expression", ";", "}", ",", "classPath", ".", "node", ")", ";", "}" ]
Given a class expression with class-level decorators, create a new expression with the proper decorated behavior.
[ "Given", "a", "class", "expression", "with", "class", "-", "level", "decorators", "create", "a", "new", "expression", "with", "the", "proper", "decorated", "behavior", "." ]
1969e6b6aa7d90be3fbb3aca98ea96849656a55a
https://github.com/babel/babel/blob/1969e6b6aa7d90be3fbb3aca98ea96849656a55a/packages/babel-plugin-proposal-decorators/src/transformer-legacy.js#L63-L81
train
babel/babel
packages/babel-plugin-proposal-decorators/src/transformer-legacy.js
applyMethodDecorators
function applyMethodDecorators(path, state) { if (!hasMethodDecorators(path.node.body.body)) return; return applyTargetDecorators(path, state, path.node.body.body); }
javascript
function applyMethodDecorators(path, state) { if (!hasMethodDecorators(path.node.body.body)) return; return applyTargetDecorators(path, state, path.node.body.body); }
[ "function", "applyMethodDecorators", "(", "path", ",", "state", ")", "{", "if", "(", "!", "hasMethodDecorators", "(", "path", ".", "node", ".", "body", ".", "body", ")", ")", "return", ";", "return", "applyTargetDecorators", "(", "path", ",", "state", ",", "path", ".", "node", ".", "body", ".", "body", ")", ";", "}" ]
Given a class expression with method-level decorators, create a new expression with the proper decorated behavior.
[ "Given", "a", "class", "expression", "with", "method", "-", "level", "decorators", "create", "a", "new", "expression", "with", "the", "proper", "decorated", "behavior", "." ]
1969e6b6aa7d90be3fbb3aca98ea96849656a55a
https://github.com/babel/babel/blob/1969e6b6aa7d90be3fbb3aca98ea96849656a55a/packages/babel-plugin-proposal-decorators/src/transformer-legacy.js#L91-L95
train
babel/babel
packages/babel-plugin-proposal-decorators/src/transformer-legacy.js
applyObjectDecorators
function applyObjectDecorators(path, state) { if (!hasMethodDecorators(path.node.properties)) return; return applyTargetDecorators(path, state, path.node.properties); }
javascript
function applyObjectDecorators(path, state) { if (!hasMethodDecorators(path.node.properties)) return; return applyTargetDecorators(path, state, path.node.properties); }
[ "function", "applyObjectDecorators", "(", "path", ",", "state", ")", "{", "if", "(", "!", "hasMethodDecorators", "(", "path", ".", "node", ".", "properties", ")", ")", "return", ";", "return", "applyTargetDecorators", "(", "path", ",", "state", ",", "path", ".", "node", ".", "properties", ")", ";", "}" ]
Given an object expression with property decorators, create a new expression with the proper decorated behavior.
[ "Given", "an", "object", "expression", "with", "property", "decorators", "create", "a", "new", "expression", "with", "the", "proper", "decorated", "behavior", "." ]
1969e6b6aa7d90be3fbb3aca98ea96849656a55a
https://github.com/babel/babel/blob/1969e6b6aa7d90be3fbb3aca98ea96849656a55a/packages/babel-plugin-proposal-decorators/src/transformer-legacy.js#L105-L109
train
babel/babel
packages/babel-highlight/src/index.js
getDefs
function getDefs(chalk) { return { keyword: chalk.cyan, capitalized: chalk.yellow, jsx_tag: chalk.yellow, punctuator: chalk.yellow, // bracket: intentionally omitted. number: chalk.magenta, string: chalk.green, regex: chalk.magenta, comment: chalk.grey, invalid: chalk.white.bgRed.bold, }; }
javascript
function getDefs(chalk) { return { keyword: chalk.cyan, capitalized: chalk.yellow, jsx_tag: chalk.yellow, punctuator: chalk.yellow, // bracket: intentionally omitted. number: chalk.magenta, string: chalk.green, regex: chalk.magenta, comment: chalk.grey, invalid: chalk.white.bgRed.bold, }; }
[ "function", "getDefs", "(", "chalk", ")", "{", "return", "{", "keyword", ":", "chalk", ".", "cyan", ",", "capitalized", ":", "chalk", ".", "yellow", ",", "jsx_tag", ":", "chalk", ".", "yellow", ",", "punctuator", ":", "chalk", ".", "yellow", ",", "number", ":", "chalk", ".", "magenta", ",", "string", ":", "chalk", ".", "green", ",", "regex", ":", "chalk", ".", "magenta", ",", "comment", ":", "chalk", ".", "grey", ",", "invalid", ":", "chalk", ".", "white", ".", "bgRed", ".", "bold", ",", "}", ";", "}" ]
Chalk styles for token types.
[ "Chalk", "styles", "for", "token", "types", "." ]
1969e6b6aa7d90be3fbb3aca98ea96849656a55a
https://github.com/babel/babel/blob/1969e6b6aa7d90be3fbb3aca98ea96849656a55a/packages/babel-highlight/src/index.js#L8-L21
train
babel/babel
packages/babel-highlight/src/index.js
getTokenType
function getTokenType(match) { const [offset, text] = match.slice(-2); const token = matchToToken(match); if (token.type === "name") { if (esutils.keyword.isReservedWordES6(token.value)) { return "keyword"; } if ( JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == "</") ) { return "jsx_tag"; } if (token.value[0] !== token.value[0].toLowerCase()) { return "capitalized"; } } if (token.type === "punctuator" && BRACKET.test(token.value)) { return "bracket"; } if ( token.type === "invalid" && (token.value === "@" || token.value === "#") ) { return "punctuator"; } return token.type; }
javascript
function getTokenType(match) { const [offset, text] = match.slice(-2); const token = matchToToken(match); if (token.type === "name") { if (esutils.keyword.isReservedWordES6(token.value)) { return "keyword"; } if ( JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == "</") ) { return "jsx_tag"; } if (token.value[0] !== token.value[0].toLowerCase()) { return "capitalized"; } } if (token.type === "punctuator" && BRACKET.test(token.value)) { return "bracket"; } if ( token.type === "invalid" && (token.value === "@" || token.value === "#") ) { return "punctuator"; } return token.type; }
[ "function", "getTokenType", "(", "match", ")", "{", "const", "[", "offset", ",", "text", "]", "=", "match", ".", "slice", "(", "-", "2", ")", ";", "const", "token", "=", "matchToToken", "(", "match", ")", ";", "if", "(", "token", ".", "type", "===", "\"name\"", ")", "{", "if", "(", "esutils", ".", "keyword", ".", "isReservedWordES6", "(", "token", ".", "value", ")", ")", "{", "return", "\"keyword\"", ";", "}", "if", "(", "JSX_TAG", ".", "test", "(", "token", ".", "value", ")", "&&", "(", "text", "[", "offset", "-", "1", "]", "===", "\"<\"", "||", "text", ".", "substr", "(", "offset", "-", "2", ",", "2", ")", "==", "\"</\"", ")", ")", "{", "return", "\"jsx_tag\"", ";", "}", "if", "(", "token", ".", "value", "[", "0", "]", "!==", "token", ".", "value", "[", "0", "]", ".", "toLowerCase", "(", ")", ")", "{", "return", "\"capitalized\"", ";", "}", "}", "if", "(", "token", ".", "type", "===", "\"punctuator\"", "&&", "BRACKET", ".", "test", "(", "token", ".", "value", ")", ")", "{", "return", "\"bracket\"", ";", "}", "if", "(", "token", ".", "type", "===", "\"invalid\"", "&&", "(", "token", ".", "value", "===", "\"@\"", "||", "token", ".", "value", "===", "\"#\"", ")", ")", "{", "return", "\"punctuator\"", ";", "}", "return", "token", ".", "type", ";", "}" ]
Get the type of token, specifying punctuator type.
[ "Get", "the", "type", "of", "token", "specifying", "punctuator", "type", "." ]
1969e6b6aa7d90be3fbb3aca98ea96849656a55a
https://github.com/babel/babel/blob/1969e6b6aa7d90be3fbb3aca98ea96849656a55a/packages/babel-highlight/src/index.js#L41-L74
train
TryGhost/Ghost
core/server/services/auth/oauth.js
exchangePassword
function exchangePassword(client, username, password, scope, body, authInfo, done) { if (!client || !client.id) { return done(new common.errors.UnauthorizedError({ message: common.i18n.t('errors.middleware.auth.clientCredentialsNotProvided') }), false); } // Validate the user return models.User.check({email: username, password: password}) .then(function then(user) { return authUtils.createTokens({ clientId: client.id, userId: user.id }); }) .then(function then(response) { web.shared.middlewares.api.spamPrevention.userLogin() .reset(authInfo.ip, username + 'login'); return done(null, response.access_token, response.refresh_token, {expires_in: response.expires_in}); }) .catch(function (err) { done(err, false); }); }
javascript
function exchangePassword(client, username, password, scope, body, authInfo, done) { if (!client || !client.id) { return done(new common.errors.UnauthorizedError({ message: common.i18n.t('errors.middleware.auth.clientCredentialsNotProvided') }), false); } // Validate the user return models.User.check({email: username, password: password}) .then(function then(user) { return authUtils.createTokens({ clientId: client.id, userId: user.id }); }) .then(function then(response) { web.shared.middlewares.api.spamPrevention.userLogin() .reset(authInfo.ip, username + 'login'); return done(null, response.access_token, response.refresh_token, {expires_in: response.expires_in}); }) .catch(function (err) { done(err, false); }); }
[ "function", "exchangePassword", "(", "client", ",", "username", ",", "password", ",", "scope", ",", "body", ",", "authInfo", ",", "done", ")", "{", "if", "(", "!", "client", "||", "!", "client", ".", "id", ")", "{", "return", "done", "(", "new", "common", ".", "errors", ".", "UnauthorizedError", "(", "{", "message", ":", "common", ".", "i18n", ".", "t", "(", "'errors.middleware.auth.clientCredentialsNotProvided'", ")", "}", ")", ",", "false", ")", ";", "}", "return", "models", ".", "User", ".", "check", "(", "{", "email", ":", "username", ",", "password", ":", "password", "}", ")", ".", "then", "(", "function", "then", "(", "user", ")", "{", "return", "authUtils", ".", "createTokens", "(", "{", "clientId", ":", "client", ".", "id", ",", "userId", ":", "user", ".", "id", "}", ")", ";", "}", ")", ".", "then", "(", "function", "then", "(", "response", ")", "{", "web", ".", "shared", ".", "middlewares", ".", "api", ".", "spamPrevention", ".", "userLogin", "(", ")", ".", "reset", "(", "authInfo", ".", "ip", ",", "username", "+", "'login'", ")", ";", "return", "done", "(", "null", ",", "response", ".", "access_token", ",", "response", ".", "refresh_token", ",", "{", "expires_in", ":", "response", ".", "expires_in", "}", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "done", "(", "err", ",", "false", ")", ";", "}", ")", ";", "}" ]
We are required to pass in authInfo in order to reset spam counter for user login
[ "We", "are", "required", "to", "pass", "in", "authInfo", "in", "order", "to", "reset", "spam", "counter", "for", "user", "login" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/services/auth/oauth.js#L64-L88
train
TryGhost/Ghost
core/server/api/v0.1/authentication.js
assertSetupCompleted
function assertSetupCompleted(status) { return function checkPermission(__) { return checkSetup().then((isSetup) => { if (isSetup === status) { return __; } const completed = common.i18n.t('errors.api.authentication.setupAlreadyCompleted'), notCompleted = common.i18n.t('errors.api.authentication.setupMustBeCompleted'); function throwReason(reason) { throw new common.errors.NoPermissionError({message: reason}); } if (isSetup) { throwReason(completed); } else { throwReason(notCompleted); } }); }; }
javascript
function assertSetupCompleted(status) { return function checkPermission(__) { return checkSetup().then((isSetup) => { if (isSetup === status) { return __; } const completed = common.i18n.t('errors.api.authentication.setupAlreadyCompleted'), notCompleted = common.i18n.t('errors.api.authentication.setupMustBeCompleted'); function throwReason(reason) { throw new common.errors.NoPermissionError({message: reason}); } if (isSetup) { throwReason(completed); } else { throwReason(notCompleted); } }); }; }
[ "function", "assertSetupCompleted", "(", "status", ")", "{", "return", "function", "checkPermission", "(", "__", ")", "{", "return", "checkSetup", "(", ")", ".", "then", "(", "(", "isSetup", ")", "=>", "{", "if", "(", "isSetup", "===", "status", ")", "{", "return", "__", ";", "}", "const", "completed", "=", "common", ".", "i18n", ".", "t", "(", "'errors.api.authentication.setupAlreadyCompleted'", ")", ",", "notCompleted", "=", "common", ".", "i18n", ".", "t", "(", "'errors.api.authentication.setupMustBeCompleted'", ")", ";", "function", "throwReason", "(", "reason", ")", "{", "throw", "new", "common", ".", "errors", ".", "NoPermissionError", "(", "{", "message", ":", "reason", "}", ")", ";", "}", "if", "(", "isSetup", ")", "{", "throwReason", "(", "completed", ")", ";", "}", "else", "{", "throwReason", "(", "notCompleted", ")", ";", "}", "}", ")", ";", "}", ";", "}" ]
Allows an assertion to be made about setup status. @param {Boolean} status True: setup must be complete. False: setup must not be complete. @return {Function} returns a "task ready" function
[ "Allows", "an", "assertion", "to", "be", "made", "about", "setup", "status", "." ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/api/v0.1/authentication.js#L37-L58
train
TryGhost/Ghost
core/server/helpers/navigation.js
_isCurrentUrl
function _isCurrentUrl(href, currentUrl) { if (!currentUrl) { return false; } var strippedHref = href.replace(/\/+$/, ''), strippedCurrentUrl = currentUrl.replace(/\/+$/, ''); return strippedHref === strippedCurrentUrl; }
javascript
function _isCurrentUrl(href, currentUrl) { if (!currentUrl) { return false; } var strippedHref = href.replace(/\/+$/, ''), strippedCurrentUrl = currentUrl.replace(/\/+$/, ''); return strippedHref === strippedCurrentUrl; }
[ "function", "_isCurrentUrl", "(", "href", ",", "currentUrl", ")", "{", "if", "(", "!", "currentUrl", ")", "{", "return", "false", ";", "}", "var", "strippedHref", "=", "href", ".", "replace", "(", "/", "\\/+$", "/", ",", "''", ")", ",", "strippedCurrentUrl", "=", "currentUrl", ".", "replace", "(", "/", "\\/+$", "/", ",", "''", ")", ";", "return", "strippedHref", "===", "strippedCurrentUrl", ";", "}" ]
strips trailing slashes and compares urls
[ "strips", "trailing", "slashes", "and", "compares", "urls" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/helpers/navigation.js#L53-L61
train
TryGhost/Ghost
core/server/models/settings.js
parseDefaultSettings
function parseDefaultSettings() { var defaultSettingsInCategories = require('../data/schema/').defaultSettings, defaultSettingsFlattened = {}, dynamicDefault = { db_hash: uuid.v4(), public_hash: crypto.randomBytes(15).toString('hex'), // @TODO: session_secret would ideally be named "admin_session_secret" session_secret: crypto.randomBytes(32).toString('hex'), members_session_secret: crypto.randomBytes(32).toString('hex'), theme_session_secret: crypto.randomBytes(32).toString('hex') }; const membersKeypair = keypair({ bits: 1024 }); dynamicDefault.members_public_key = membersKeypair.public; dynamicDefault.members_private_key = membersKeypair.private; _.each(defaultSettingsInCategories, function each(settings, categoryName) { _.each(settings, function each(setting, settingName) { setting.type = categoryName; setting.key = settingName; if (dynamicDefault[setting.key]) { setting.defaultValue = dynamicDefault[setting.key]; } defaultSettingsFlattened[settingName] = setting; }); }); return defaultSettingsFlattened; }
javascript
function parseDefaultSettings() { var defaultSettingsInCategories = require('../data/schema/').defaultSettings, defaultSettingsFlattened = {}, dynamicDefault = { db_hash: uuid.v4(), public_hash: crypto.randomBytes(15).toString('hex'), // @TODO: session_secret would ideally be named "admin_session_secret" session_secret: crypto.randomBytes(32).toString('hex'), members_session_secret: crypto.randomBytes(32).toString('hex'), theme_session_secret: crypto.randomBytes(32).toString('hex') }; const membersKeypair = keypair({ bits: 1024 }); dynamicDefault.members_public_key = membersKeypair.public; dynamicDefault.members_private_key = membersKeypair.private; _.each(defaultSettingsInCategories, function each(settings, categoryName) { _.each(settings, function each(setting, settingName) { setting.type = categoryName; setting.key = settingName; if (dynamicDefault[setting.key]) { setting.defaultValue = dynamicDefault[setting.key]; } defaultSettingsFlattened[settingName] = setting; }); }); return defaultSettingsFlattened; }
[ "function", "parseDefaultSettings", "(", ")", "{", "var", "defaultSettingsInCategories", "=", "require", "(", "'../data/schema/'", ")", ".", "defaultSettings", ",", "defaultSettingsFlattened", "=", "{", "}", ",", "dynamicDefault", "=", "{", "db_hash", ":", "uuid", ".", "v4", "(", ")", ",", "public_hash", ":", "crypto", ".", "randomBytes", "(", "15", ")", ".", "toString", "(", "'hex'", ")", ",", "session_secret", ":", "crypto", ".", "randomBytes", "(", "32", ")", ".", "toString", "(", "'hex'", ")", ",", "members_session_secret", ":", "crypto", ".", "randomBytes", "(", "32", ")", ".", "toString", "(", "'hex'", ")", ",", "theme_session_secret", ":", "crypto", ".", "randomBytes", "(", "32", ")", ".", "toString", "(", "'hex'", ")", "}", ";", "const", "membersKeypair", "=", "keypair", "(", "{", "bits", ":", "1024", "}", ")", ";", "dynamicDefault", ".", "members_public_key", "=", "membersKeypair", ".", "public", ";", "dynamicDefault", ".", "members_private_key", "=", "membersKeypair", ".", "private", ";", "_", ".", "each", "(", "defaultSettingsInCategories", ",", "function", "each", "(", "settings", ",", "categoryName", ")", "{", "_", ".", "each", "(", "settings", ",", "function", "each", "(", "setting", ",", "settingName", ")", "{", "setting", ".", "type", "=", "categoryName", ";", "setting", ".", "key", "=", "settingName", ";", "if", "(", "dynamicDefault", "[", "setting", ".", "key", "]", ")", "{", "setting", ".", "defaultValue", "=", "dynamicDefault", "[", "setting", ".", "key", "]", ";", "}", "defaultSettingsFlattened", "[", "settingName", "]", "=", "setting", ";", "}", ")", ";", "}", ")", ";", "return", "defaultSettingsFlattened", ";", "}" ]
For neatness, the defaults file is split into categories. It's much easier for us to work with it as a single level instead of iterating those categories every time
[ "For", "neatness", "the", "defaults", "file", "is", "split", "into", "categories", ".", "It", "s", "much", "easier", "for", "us", "to", "work", "with", "it", "as", "a", "single", "level", "instead", "of", "iterating", "those", "categories", "every", "time" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/models/settings.js#L16-L48
train
TryGhost/Ghost
core/server/lib/fs/package-json/parse.js
parsePackageJson
function parsePackageJson(path) { return fs.readFile(path) .catch(function () { var err = new Error(common.i18n.t('errors.utils.parsepackagejson.couldNotReadPackage')); err.context = path; return Promise.reject(err); }) .then(function (source) { var hasRequiredKeys, json, err; try { json = JSON.parse(source); hasRequiredKeys = json.name && json.version; if (!hasRequiredKeys) { err = new Error(common.i18n.t('errors.utils.parsepackagejson.nameOrVersionMissing')); err.context = path; err.help = common.i18n.t('errors.utils.parsepackagejson.willBeRequired', {url: 'https://docs.ghost.org/api/handlebars-themes/'}); return Promise.reject(err); } return json; } catch (parseError) { err = new Error(common.i18n.t('errors.utils.parsepackagejson.themeFileIsMalformed')); err.context = path; err.help = common.i18n.t('errors.utils.parsepackagejson.willBeRequired', {url: 'https://docs.ghost.org/api/handlebars-themes/'}); return Promise.reject(err); } }); }
javascript
function parsePackageJson(path) { return fs.readFile(path) .catch(function () { var err = new Error(common.i18n.t('errors.utils.parsepackagejson.couldNotReadPackage')); err.context = path; return Promise.reject(err); }) .then(function (source) { var hasRequiredKeys, json, err; try { json = JSON.parse(source); hasRequiredKeys = json.name && json.version; if (!hasRequiredKeys) { err = new Error(common.i18n.t('errors.utils.parsepackagejson.nameOrVersionMissing')); err.context = path; err.help = common.i18n.t('errors.utils.parsepackagejson.willBeRequired', {url: 'https://docs.ghost.org/api/handlebars-themes/'}); return Promise.reject(err); } return json; } catch (parseError) { err = new Error(common.i18n.t('errors.utils.parsepackagejson.themeFileIsMalformed')); err.context = path; err.help = common.i18n.t('errors.utils.parsepackagejson.willBeRequired', {url: 'https://docs.ghost.org/api/handlebars-themes/'}); return Promise.reject(err); } }); }
[ "function", "parsePackageJson", "(", "path", ")", "{", "return", "fs", ".", "readFile", "(", "path", ")", ".", "catch", "(", "function", "(", ")", "{", "var", "err", "=", "new", "Error", "(", "common", ".", "i18n", ".", "t", "(", "'errors.utils.parsepackagejson.couldNotReadPackage'", ")", ")", ";", "err", ".", "context", "=", "path", ";", "return", "Promise", ".", "reject", "(", "err", ")", ";", "}", ")", ".", "then", "(", "function", "(", "source", ")", "{", "var", "hasRequiredKeys", ",", "json", ",", "err", ";", "try", "{", "json", "=", "JSON", ".", "parse", "(", "source", ")", ";", "hasRequiredKeys", "=", "json", ".", "name", "&&", "json", ".", "version", ";", "if", "(", "!", "hasRequiredKeys", ")", "{", "err", "=", "new", "Error", "(", "common", ".", "i18n", ".", "t", "(", "'errors.utils.parsepackagejson.nameOrVersionMissing'", ")", ")", ";", "err", ".", "context", "=", "path", ";", "err", ".", "help", "=", "common", ".", "i18n", ".", "t", "(", "'errors.utils.parsepackagejson.willBeRequired'", ",", "{", "url", ":", "'https://docs.ghost.org/api/handlebars-themes/'", "}", ")", ";", "return", "Promise", ".", "reject", "(", "err", ")", ";", "}", "return", "json", ";", "}", "catch", "(", "parseError", ")", "{", "err", "=", "new", "Error", "(", "common", ".", "i18n", ".", "t", "(", "'errors.utils.parsepackagejson.themeFileIsMalformed'", ")", ")", ";", "err", ".", "context", "=", "path", ";", "err", ".", "help", "=", "common", ".", "i18n", ".", "t", "(", "'errors.utils.parsepackagejson.willBeRequired'", ",", "{", "url", ":", "'https://docs.ghost.org/api/handlebars-themes/'", "}", ")", ";", "return", "Promise", ".", "reject", "(", "err", ")", ";", "}", "}", ")", ";", "}" ]
Parse package.json and validate it has all the required fields
[ "Parse", "package", ".", "json", "and", "validate", "it", "has", "all", "the", "required", "fields" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/lib/fs/package-json/parse.js#L14-L47
train
TryGhost/Ghost
core/server/data/importer/index.js
function (items) { return '+(' + _.reduce(items, function (memo, ext) { return memo !== '' ? memo + '|' + ext : ext; }, '') + ')'; }
javascript
function (items) { return '+(' + _.reduce(items, function (memo, ext) { return memo !== '' ? memo + '|' + ext : ext; }, '') + ')'; }
[ "function", "(", "items", ")", "{", "return", "'+('", "+", "_", ".", "reduce", "(", "items", ",", "function", "(", "memo", ",", "ext", ")", "{", "return", "memo", "!==", "''", "?", "memo", "+", "'|'", "+", "ext", ":", "ext", ";", "}", ",", "''", ")", "+", "')'", ";", "}" ]
Convert items into a glob string @param {String[]} items @returns {String}
[ "Convert", "items", "into", "a", "glob", "string" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/data/importer/index.js#L72-L76
train
TryGhost/Ghost
core/server/data/importer/index.js
function (directory) { // Globs match content in the root or inside a single directory var extMatchesBase = glob.sync(this.getExtensionGlob(this.getExtensions(), ROOT_OR_SINGLE_DIR), {cwd: directory}), extMatchesAll = glob.sync( this.getExtensionGlob(this.getExtensions(), ALL_DIRS), {cwd: directory} ), dirMatches = glob.sync( this.getDirectoryGlob(this.getDirectories(), ROOT_OR_SINGLE_DIR), {cwd: directory} ), oldRoonMatches = glob.sync(this.getDirectoryGlob(['drafts', 'published', 'deleted'], ROOT_OR_SINGLE_DIR), {cwd: directory}); // This is a temporary extra message for the old format roon export which doesn't work with Ghost if (oldRoonMatches.length > 0) { throw new common.errors.UnsupportedMediaTypeError({message: common.i18n.t('errors.data.importer.index.unsupportedRoonExport')}); } // If this folder contains importable files or a content or images directory if (extMatchesBase.length > 0 || (dirMatches.length > 0 && extMatchesAll.length > 0)) { return true; } if (extMatchesAll.length < 1) { throw new common.errors.UnsupportedMediaTypeError({message: common.i18n.t('errors.data.importer.index.noContentToImport')}); } throw new common.errors.UnsupportedMediaTypeError({message: common.i18n.t('errors.data.importer.index.invalidZipStructure')}); }
javascript
function (directory) { // Globs match content in the root or inside a single directory var extMatchesBase = glob.sync(this.getExtensionGlob(this.getExtensions(), ROOT_OR_SINGLE_DIR), {cwd: directory}), extMatchesAll = glob.sync( this.getExtensionGlob(this.getExtensions(), ALL_DIRS), {cwd: directory} ), dirMatches = glob.sync( this.getDirectoryGlob(this.getDirectories(), ROOT_OR_SINGLE_DIR), {cwd: directory} ), oldRoonMatches = glob.sync(this.getDirectoryGlob(['drafts', 'published', 'deleted'], ROOT_OR_SINGLE_DIR), {cwd: directory}); // This is a temporary extra message for the old format roon export which doesn't work with Ghost if (oldRoonMatches.length > 0) { throw new common.errors.UnsupportedMediaTypeError({message: common.i18n.t('errors.data.importer.index.unsupportedRoonExport')}); } // If this folder contains importable files or a content or images directory if (extMatchesBase.length > 0 || (dirMatches.length > 0 && extMatchesAll.length > 0)) { return true; } if (extMatchesAll.length < 1) { throw new common.errors.UnsupportedMediaTypeError({message: common.i18n.t('errors.data.importer.index.noContentToImport')}); } throw new common.errors.UnsupportedMediaTypeError({message: common.i18n.t('errors.data.importer.index.invalidZipStructure')}); }
[ "function", "(", "directory", ")", "{", "var", "extMatchesBase", "=", "glob", ".", "sync", "(", "this", ".", "getExtensionGlob", "(", "this", ".", "getExtensions", "(", ")", ",", "ROOT_OR_SINGLE_DIR", ")", ",", "{", "cwd", ":", "directory", "}", ")", ",", "extMatchesAll", "=", "glob", ".", "sync", "(", "this", ".", "getExtensionGlob", "(", "this", ".", "getExtensions", "(", ")", ",", "ALL_DIRS", ")", ",", "{", "cwd", ":", "directory", "}", ")", ",", "dirMatches", "=", "glob", ".", "sync", "(", "this", ".", "getDirectoryGlob", "(", "this", ".", "getDirectories", "(", ")", ",", "ROOT_OR_SINGLE_DIR", ")", ",", "{", "cwd", ":", "directory", "}", ")", ",", "oldRoonMatches", "=", "glob", ".", "sync", "(", "this", ".", "getDirectoryGlob", "(", "[", "'drafts'", ",", "'published'", ",", "'deleted'", "]", ",", "ROOT_OR_SINGLE_DIR", ")", ",", "{", "cwd", ":", "directory", "}", ")", ";", "if", "(", "oldRoonMatches", ".", "length", ">", "0", ")", "{", "throw", "new", "common", ".", "errors", ".", "UnsupportedMediaTypeError", "(", "{", "message", ":", "common", ".", "i18n", ".", "t", "(", "'errors.data.importer.index.unsupportedRoonExport'", ")", "}", ")", ";", "}", "if", "(", "extMatchesBase", ".", "length", ">", "0", "||", "(", "dirMatches", ".", "length", ">", "0", "&&", "extMatchesAll", ".", "length", ">", "0", ")", ")", "{", "return", "true", ";", "}", "if", "(", "extMatchesAll", ".", "length", "<", "1", ")", "{", "throw", "new", "common", ".", "errors", ".", "UnsupportedMediaTypeError", "(", "{", "message", ":", "common", ".", "i18n", ".", "t", "(", "'errors.data.importer.index.noContentToImport'", ")", "}", ")", ";", "}", "throw", "new", "common", ".", "errors", ".", "UnsupportedMediaTypeError", "(", "{", "message", ":", "common", ".", "i18n", ".", "t", "(", "'errors.data.importer.index.invalidZipStructure'", ")", "}", ")", ";", "}" ]
Checks the content of a zip folder to see if it is valid. Importable content includes any files or directories which the handlers can process Importable content must be found either in the root, or inside one base directory @param {String} directory @returns {Promise}
[ "Checks", "the", "content", "of", "a", "zip", "folder", "to", "see", "if", "it", "is", "valid", ".", "Importable", "content", "includes", "any", "files", "or", "directories", "which", "the", "handlers", "can", "process", "Importable", "content", "must", "be", "found", "either", "in", "the", "root", "or", "inside", "one", "base", "directory" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/data/importer/index.js#L138-L165
train
TryGhost/Ghost
core/server/data/importer/index.js
function (filePath) { const tmpDir = path.join(os.tmpdir(), uuid.v4()); this.fileToDelete = tmpDir; return Promise.promisify(extract)(filePath, {dir: tmpDir}).then(function () { return tmpDir; }); }
javascript
function (filePath) { const tmpDir = path.join(os.tmpdir(), uuid.v4()); this.fileToDelete = tmpDir; return Promise.promisify(extract)(filePath, {dir: tmpDir}).then(function () { return tmpDir; }); }
[ "function", "(", "filePath", ")", "{", "const", "tmpDir", "=", "path", ".", "join", "(", "os", ".", "tmpdir", "(", ")", ",", "uuid", ".", "v4", "(", ")", ")", ";", "this", ".", "fileToDelete", "=", "tmpDir", ";", "return", "Promise", ".", "promisify", "(", "extract", ")", "(", "filePath", ",", "{", "dir", ":", "tmpDir", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "tmpDir", ";", "}", ")", ";", "}" ]
Use the extract module to extract the given zip file to a temp directory & return the temp directory path @param {String} filePath @returns {Promise[]} Files
[ "Use", "the", "extract", "module", "to", "extract", "the", "given", "zip", "file", "to", "a", "temp", "directory", "&", "return", "the", "temp", "directory", "path" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/data/importer/index.js#L171-L178
train
TryGhost/Ghost
core/server/data/importer/index.js
function (handler, directory) { var globPattern = this.getExtensionGlob(handler.extensions, ALL_DIRS); return _.map(glob.sync(globPattern, {cwd: directory}), function (file) { return {name: file, path: path.join(directory, file)}; }); }
javascript
function (handler, directory) { var globPattern = this.getExtensionGlob(handler.extensions, ALL_DIRS); return _.map(glob.sync(globPattern, {cwd: directory}), function (file) { return {name: file, path: path.join(directory, file)}; }); }
[ "function", "(", "handler", ",", "directory", ")", "{", "var", "globPattern", "=", "this", ".", "getExtensionGlob", "(", "handler", ".", "extensions", ",", "ALL_DIRS", ")", ";", "return", "_", ".", "map", "(", "glob", ".", "sync", "(", "globPattern", ",", "{", "cwd", ":", "directory", "}", ")", ",", "function", "(", "file", ")", "{", "return", "{", "name", ":", "file", ",", "path", ":", "path", ".", "join", "(", "directory", ",", "file", ")", "}", ";", "}", ")", ";", "}" ]
Use the handler extensions to get a globbing pattern, then use that to fetch all the files from the zip which are relevant to the given handler, and return them as a name and path combo @param {Object} handler @param {String} directory @returns [] Files
[ "Use", "the", "handler", "extensions", "to", "get", "a", "globbing", "pattern", "then", "use", "that", "to", "fetch", "all", "the", "files", "from", "the", "zip", "which", "are", "relevant", "to", "the", "given", "handler", "and", "return", "them", "as", "a", "name", "and", "path", "combo" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/data/importer/index.js#L186-L191
train
TryGhost/Ghost
core/server/data/importer/index.js
function (directory) { // Globs match root level only var extMatches = glob.sync(this.getExtensionGlob(this.getExtensions(), ROOT_ONLY), {cwd: directory}), dirMatches = glob.sync(this.getDirectoryGlob(this.getDirectories(), ROOT_ONLY), {cwd: directory}), extMatchesAll; // There is no base directory if (extMatches.length > 0 || dirMatches.length > 0) { return; } // There is a base directory, grab it from any ext match extMatchesAll = glob.sync( this.getExtensionGlob(this.getExtensions(), ALL_DIRS), {cwd: directory} ); if (extMatchesAll.length < 1 || extMatchesAll[0].split('/') < 1) { throw new common.errors.ValidationError({message: common.i18n.t('errors.data.importer.index.invalidZipFileBaseDirectory')}); } return extMatchesAll[0].split('/')[0]; }
javascript
function (directory) { // Globs match root level only var extMatches = glob.sync(this.getExtensionGlob(this.getExtensions(), ROOT_ONLY), {cwd: directory}), dirMatches = glob.sync(this.getDirectoryGlob(this.getDirectories(), ROOT_ONLY), {cwd: directory}), extMatchesAll; // There is no base directory if (extMatches.length > 0 || dirMatches.length > 0) { return; } // There is a base directory, grab it from any ext match extMatchesAll = glob.sync( this.getExtensionGlob(this.getExtensions(), ALL_DIRS), {cwd: directory} ); if (extMatchesAll.length < 1 || extMatchesAll[0].split('/') < 1) { throw new common.errors.ValidationError({message: common.i18n.t('errors.data.importer.index.invalidZipFileBaseDirectory')}); } return extMatchesAll[0].split('/')[0]; }
[ "function", "(", "directory", ")", "{", "var", "extMatches", "=", "glob", ".", "sync", "(", "this", ".", "getExtensionGlob", "(", "this", ".", "getExtensions", "(", ")", ",", "ROOT_ONLY", ")", ",", "{", "cwd", ":", "directory", "}", ")", ",", "dirMatches", "=", "glob", ".", "sync", "(", "this", ".", "getDirectoryGlob", "(", "this", ".", "getDirectories", "(", ")", ",", "ROOT_ONLY", ")", ",", "{", "cwd", ":", "directory", "}", ")", ",", "extMatchesAll", ";", "if", "(", "extMatches", ".", "length", ">", "0", "||", "dirMatches", ".", "length", ">", "0", ")", "{", "return", ";", "}", "extMatchesAll", "=", "glob", ".", "sync", "(", "this", ".", "getExtensionGlob", "(", "this", ".", "getExtensions", "(", ")", ",", "ALL_DIRS", ")", ",", "{", "cwd", ":", "directory", "}", ")", ";", "if", "(", "extMatchesAll", ".", "length", "<", "1", "||", "extMatchesAll", "[", "0", "]", ".", "split", "(", "'/'", ")", "<", "1", ")", "{", "throw", "new", "common", ".", "errors", ".", "ValidationError", "(", "{", "message", ":", "common", ".", "i18n", ".", "t", "(", "'errors.data.importer.index.invalidZipFileBaseDirectory'", ")", "}", ")", ";", "}", "return", "extMatchesAll", "[", "0", "]", ".", "split", "(", "'/'", ")", "[", "0", "]", ";", "}" ]
Get the name of the single base directory if there is one, else return an empty string @param {String} directory @returns {Promise (String)}
[ "Get", "the", "name", "of", "the", "single", "base", "directory", "if", "there", "is", "one", "else", "return", "an", "empty", "string" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/data/importer/index.js#L197-L216
train
TryGhost/Ghost
core/server/data/importer/index.js
function (file, importOptions = {}) { var self = this; // Step 1: Handle converting the file to usable data return this.loadFile(file).then(function (importData) { // Step 2: Let the importers pre-process the data return self.preProcess(importData); }).then(function (importData) { // Step 3: Actually do the import // @TODO: It would be cool to have some sort of dry run flag here return self.doImport(importData, importOptions); }).then(function (importData) { // Step 4: Report on the import return self.generateReport(importData); }).finally(() => self.cleanUp()); // Step 5: Cleanup any files }
javascript
function (file, importOptions = {}) { var self = this; // Step 1: Handle converting the file to usable data return this.loadFile(file).then(function (importData) { // Step 2: Let the importers pre-process the data return self.preProcess(importData); }).then(function (importData) { // Step 3: Actually do the import // @TODO: It would be cool to have some sort of dry run flag here return self.doImport(importData, importOptions); }).then(function (importData) { // Step 4: Report on the import return self.generateReport(importData); }).finally(() => self.cleanUp()); // Step 5: Cleanup any files }
[ "function", "(", "file", ",", "importOptions", "=", "{", "}", ")", "{", "var", "self", "=", "this", ";", "return", "this", ".", "loadFile", "(", "file", ")", ".", "then", "(", "function", "(", "importData", ")", "{", "return", "self", ".", "preProcess", "(", "importData", ")", ";", "}", ")", ".", "then", "(", "function", "(", "importData", ")", "{", "return", "self", ".", "doImport", "(", "importData", ",", "importOptions", ")", ";", "}", ")", ".", "then", "(", "function", "(", "importData", ")", "{", "return", "self", ".", "generateReport", "(", "importData", ")", ";", "}", ")", ".", "finally", "(", "(", ")", "=>", "self", ".", "cleanUp", "(", ")", ")", ";", "}" ]
Import From File The main method of the ImportManager, call this to kick everything off! @param {File} file @param {importOptions} importOptions to allow override of certain import features such as locking a user @returns {Promise}
[ "Import", "From", "File", "The", "main", "method", "of", "the", "ImportManager", "call", "this", "to", "kick", "everything", "off!" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/data/importer/index.js#L356-L371
train
TryGhost/Ghost
core/server/data/meta/schema.js
trimSchema
function trimSchema(schema) { var schemaObject = {}; _.each(schema, function (value, key) { if (value !== null && typeof value !== 'undefined') { schemaObject[key] = value; } }); return schemaObject; }
javascript
function trimSchema(schema) { var schemaObject = {}; _.each(schema, function (value, key) { if (value !== null && typeof value !== 'undefined') { schemaObject[key] = value; } }); return schemaObject; }
[ "function", "trimSchema", "(", "schema", ")", "{", "var", "schemaObject", "=", "{", "}", ";", "_", ".", "each", "(", "schema", ",", "function", "(", "value", ",", "key", ")", "{", "if", "(", "value", "!==", "null", "&&", "typeof", "value", "!==", "'undefined'", ")", "{", "schemaObject", "[", "key", "]", "=", "value", ";", "}", "}", ")", ";", "return", "schemaObject", ";", "}" ]
Creates the final schema object with values that are not null
[ "Creates", "the", "final", "schema", "object", "with", "values", "that", "are", "not", "null" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/data/meta/schema.js#L26-L36
train
TryGhost/Ghost
core/server/lib/promise/sequence.js
sequence
function sequence(tasks /* Any Arguments */) { const args = Array.prototype.slice.call(arguments, 1); return Promise.reduce(tasks, function (results, task) { const response = task.apply(this, args); if (response && response.then) { return response.then(function (result) { results.push(result); return results; }); } else { return Promise.resolve().then(() => { results.push(response); return results; }); } }, []); }
javascript
function sequence(tasks /* Any Arguments */) { const args = Array.prototype.slice.call(arguments, 1); return Promise.reduce(tasks, function (results, task) { const response = task.apply(this, args); if (response && response.then) { return response.then(function (result) { results.push(result); return results; }); } else { return Promise.resolve().then(() => { results.push(response); return results; }); } }, []); }
[ "function", "sequence", "(", "tasks", ")", "{", "const", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ";", "return", "Promise", ".", "reduce", "(", "tasks", ",", "function", "(", "results", ",", "task", ")", "{", "const", "response", "=", "task", ".", "apply", "(", "this", ",", "args", ")", ";", "if", "(", "response", "&&", "response", ".", "then", ")", "{", "return", "response", ".", "then", "(", "function", "(", "result", ")", "{", "results", ".", "push", "(", "result", ")", ";", "return", "results", ";", "}", ")", ";", "}", "else", "{", "return", "Promise", ".", "resolve", "(", ")", ".", "then", "(", "(", ")", "=>", "{", "results", ".", "push", "(", "response", ")", ";", "return", "results", ";", "}", ")", ";", "}", "}", ",", "[", "]", ")", ";", "}" ]
expects an array of functions returning a promise
[ "expects", "an", "array", "of", "functions", "returning", "a", "promise" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/lib/promise/sequence.js#L6-L24
train
TryGhost/Ghost
core/server/data/validation/index.js
characterOccurance
function characterOccurance(stringToTest) { var chars = {}, allowedOccurancy, valid = true; stringToTest = _.toString(stringToTest); allowedOccurancy = stringToTest.length / 2; // Loop through string and accumulate character counts _.each(stringToTest, function (char) { if (!chars[char]) { chars[char] = 1; } else { chars[char] += 1; } }); // check if any of the accumulated chars exceed the allowed occurancy // of 50% of the words' length. _.forIn(chars, function (charCount) { if (charCount >= allowedOccurancy) { valid = false; } }); return valid; }
javascript
function characterOccurance(stringToTest) { var chars = {}, allowedOccurancy, valid = true; stringToTest = _.toString(stringToTest); allowedOccurancy = stringToTest.length / 2; // Loop through string and accumulate character counts _.each(stringToTest, function (char) { if (!chars[char]) { chars[char] = 1; } else { chars[char] += 1; } }); // check if any of the accumulated chars exceed the allowed occurancy // of 50% of the words' length. _.forIn(chars, function (charCount) { if (charCount >= allowedOccurancy) { valid = false; } }); return valid; }
[ "function", "characterOccurance", "(", "stringToTest", ")", "{", "var", "chars", "=", "{", "}", ",", "allowedOccurancy", ",", "valid", "=", "true", ";", "stringToTest", "=", "_", ".", "toString", "(", "stringToTest", ")", ";", "allowedOccurancy", "=", "stringToTest", ".", "length", "/", "2", ";", "_", ".", "each", "(", "stringToTest", ",", "function", "(", "char", ")", "{", "if", "(", "!", "chars", "[", "char", "]", ")", "{", "chars", "[", "char", "]", "=", "1", ";", "}", "else", "{", "chars", "[", "char", "]", "+=", "1", ";", "}", "}", ")", ";", "_", ".", "forIn", "(", "chars", ",", "function", "(", "charCount", ")", "{", "if", "(", "charCount", ">=", "allowedOccurancy", ")", "{", "valid", "=", "false", ";", "}", "}", ")", ";", "return", "valid", ";", "}" ]
Counts repeated characters in a string. When 50% or more characters are the same, we return false and therefore invalidate the string. @param {String} stringToTest The password string to check. @return {Boolean}
[ "Counts", "repeated", "characters", "in", "a", "string", ".", "When", "50%", "or", "more", "characters", "are", "the", "same", "we", "return", "false", "and", "therefore", "invalidate", "the", "string", "." ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/data/validation/index.js#L27-L53
train
TryGhost/Ghost
core/server/models/permission.js
permittedAttributes
function permittedAttributes() { let filteredKeys = ghostBookshelf.Model.prototype.permittedAttributes.apply(this, arguments); this.relationships.forEach((key) => { filteredKeys.push(key); }); return filteredKeys; }
javascript
function permittedAttributes() { let filteredKeys = ghostBookshelf.Model.prototype.permittedAttributes.apply(this, arguments); this.relationships.forEach((key) => { filteredKeys.push(key); }); return filteredKeys; }
[ "function", "permittedAttributes", "(", ")", "{", "let", "filteredKeys", "=", "ghostBookshelf", ".", "Model", ".", "prototype", ".", "permittedAttributes", ".", "apply", "(", "this", ",", "arguments", ")", ";", "this", ".", "relationships", ".", "forEach", "(", "(", "key", ")", "=>", "{", "filteredKeys", ".", "push", "(", "key", ")", ";", "}", ")", ";", "return", "filteredKeys", ";", "}" ]
The base model keeps only the columns, which are defined in the schema. We have to add the relations on top, otherwise bookshelf-relations has no access to the nested relations, which should be updated.
[ "The", "base", "model", "keeps", "only", "the", "columns", "which", "are", "defined", "in", "the", "schema", ".", "We", "have", "to", "add", "the", "relations", "on", "top", "otherwise", "bookshelf", "-", "relations", "has", "no", "access", "to", "the", "nested", "relations", "which", "should", "be", "updated", "." ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/models/permission.js#L20-L28
train
TryGhost/Ghost
core/server/services/apps/loader.js
function (name) { const {app, proxy} = getAppByName(name); // Check for an activate() method on the app. if (!_.isFunction(app.activate)) { return Promise.reject(new Error(common.i18n.t('errors.apps.noActivateMethodLoadingApp.error', {name: name}))); } // Wrapping the activate() with a when because it's possible // to not return a promise from it. return Promise.resolve(app.activate(proxy)).return(app); }
javascript
function (name) { const {app, proxy} = getAppByName(name); // Check for an activate() method on the app. if (!_.isFunction(app.activate)) { return Promise.reject(new Error(common.i18n.t('errors.apps.noActivateMethodLoadingApp.error', {name: name}))); } // Wrapping the activate() with a when because it's possible // to not return a promise from it. return Promise.resolve(app.activate(proxy)).return(app); }
[ "function", "(", "name", ")", "{", "const", "{", "app", ",", "proxy", "}", "=", "getAppByName", "(", "name", ")", ";", "if", "(", "!", "_", ".", "isFunction", "(", "app", ".", "activate", ")", ")", "{", "return", "Promise", ".", "reject", "(", "new", "Error", "(", "common", ".", "i18n", ".", "t", "(", "'errors.apps.noActivateMethodLoadingApp.error'", ",", "{", "name", ":", "name", "}", ")", ")", ")", ";", "}", "return", "Promise", ".", "resolve", "(", "app", ".", "activate", "(", "proxy", ")", ")", ".", "return", "(", "app", ")", ";", "}" ]
Activate a app and return it
[ "Activate", "a", "app", "and", "return", "it" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/services/apps/loader.js#L33-L44
train
TryGhost/Ghost
core/server/apps/amp/lib/router.js
getPostData
function getPostData(req, res, next) { req.body = req.body || {}; const urlWithoutSubdirectoryWithoutAmp = res.locals.relativeUrl.match(/(.*?\/)amp\/?$/)[1]; /** * @NOTE * * We have to figure out the target permalink, otherwise it would be possible to serve a post * which lives in two collections. * * @TODO: * * This is not optimal and caused by the fact how apps currently work. But apps weren't designed * for dynamic routing. * * I think if the responsible, target router would first take care fetching/determining the post, the * request could then be forwarded to this app. Then we don't have to: * * 1. care about fetching the post * 2. care about if the post can be served * 3. then this app would act like an extension * * The challenge is to design different types of apps e.g. extensions of routers, standalone pages etc. */ const permalinks = urlService.getPermalinkByUrl(urlWithoutSubdirectoryWithoutAmp, {withUrlOptions: true}); if (!permalinks) { return next(new common.errors.NotFoundError({ message: common.i18n.t('errors.errors.pageNotFound') })); } // @NOTE: amp is not supported for static pages // @TODO: https://github.com/TryGhost/Ghost/issues/10548 helpers.entryLookup(urlWithoutSubdirectoryWithoutAmp, {permalinks, query: {controller: 'postsPublic', resource: 'posts'}}, res.locals) .then((result) => { if (result && result.entry) { req.body.post = result.entry; } next(); }) .catch(next); }
javascript
function getPostData(req, res, next) { req.body = req.body || {}; const urlWithoutSubdirectoryWithoutAmp = res.locals.relativeUrl.match(/(.*?\/)amp\/?$/)[1]; /** * @NOTE * * We have to figure out the target permalink, otherwise it would be possible to serve a post * which lives in two collections. * * @TODO: * * This is not optimal and caused by the fact how apps currently work. But apps weren't designed * for dynamic routing. * * I think if the responsible, target router would first take care fetching/determining the post, the * request could then be forwarded to this app. Then we don't have to: * * 1. care about fetching the post * 2. care about if the post can be served * 3. then this app would act like an extension * * The challenge is to design different types of apps e.g. extensions of routers, standalone pages etc. */ const permalinks = urlService.getPermalinkByUrl(urlWithoutSubdirectoryWithoutAmp, {withUrlOptions: true}); if (!permalinks) { return next(new common.errors.NotFoundError({ message: common.i18n.t('errors.errors.pageNotFound') })); } // @NOTE: amp is not supported for static pages // @TODO: https://github.com/TryGhost/Ghost/issues/10548 helpers.entryLookup(urlWithoutSubdirectoryWithoutAmp, {permalinks, query: {controller: 'postsPublic', resource: 'posts'}}, res.locals) .then((result) => { if (result && result.entry) { req.body.post = result.entry; } next(); }) .catch(next); }
[ "function", "getPostData", "(", "req", ",", "res", ",", "next", ")", "{", "req", ".", "body", "=", "req", ".", "body", "||", "{", "}", ";", "const", "urlWithoutSubdirectoryWithoutAmp", "=", "res", ".", "locals", ".", "relativeUrl", ".", "match", "(", "/", "(.*?\\/)amp\\/?$", "/", ")", "[", "1", "]", ";", "const", "permalinks", "=", "urlService", ".", "getPermalinkByUrl", "(", "urlWithoutSubdirectoryWithoutAmp", ",", "{", "withUrlOptions", ":", "true", "}", ")", ";", "if", "(", "!", "permalinks", ")", "{", "return", "next", "(", "new", "common", ".", "errors", ".", "NotFoundError", "(", "{", "message", ":", "common", ".", "i18n", ".", "t", "(", "'errors.errors.pageNotFound'", ")", "}", ")", ")", ";", "}", "helpers", ".", "entryLookup", "(", "urlWithoutSubdirectoryWithoutAmp", ",", "{", "permalinks", ",", "query", ":", "{", "controller", ":", "'postsPublic'", ",", "resource", ":", "'posts'", "}", "}", ",", "res", ".", "locals", ")", ".", "then", "(", "(", "result", ")", "=>", "{", "if", "(", "result", "&&", "result", ".", "entry", ")", "{", "req", ".", "body", ".", "post", "=", "result", ".", "entry", ";", "}", "next", "(", ")", ";", "}", ")", ".", "catch", "(", "next", ")", ";", "}" ]
This here is a controller. In fact, this whole file is nothing more than a controller + renderer & doesn't need to be a router
[ "This", "here", "is", "a", "controller", ".", "In", "fact", "this", "whole", "file", "is", "nothing", "more", "than", "a", "controller", "+", "renderer", "&", "doesn", "t", "need", "to", "be", "a", "router" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/apps/amp/lib/router.js#L33-L77
train
TryGhost/Ghost
core/server/data/meta/image-dimensions.js
getImageDimensions
function getImageDimensions(metaData) { var fetch = { coverImage: imageLib.imageSizeCache(metaData.coverImage.url), authorImage: imageLib.imageSizeCache(metaData.authorImage.url), ogImage: imageLib.imageSizeCache(metaData.ogImage.url), logo: imageLib.imageSizeCache(metaData.blog.logo.url) }; return Promise .props(fetch) .then(function (imageObj) { _.forEach(imageObj, function (key, value) { if (_.has(key, 'width') && _.has(key, 'height')) { // We have some restrictions for publisher.logo: // The image needs to be <=600px wide and <=60px high (ideally exactly 600px x 60px). // Unless we have proper image-handling (see https://github.com/TryGhost/Ghost/issues/4453), // we will fake it in some cases or not produce an imageObject at all. if (value === 'logo') { if (key.height <= 60 && key.width <= 600) { _.assign(metaData.blog[value], { dimensions: { width: key.width, height: key.height } }); } else if (key.width === key.height) { // CASE: the logo is too large, but it is a square. We fake it... _.assign(metaData.blog[value], { dimensions: { width: 60, height: 60 } }); } } else { _.assign(metaData[value], { dimensions: { width: key.width, height: key.height } }); } } }); return metaData; }); }
javascript
function getImageDimensions(metaData) { var fetch = { coverImage: imageLib.imageSizeCache(metaData.coverImage.url), authorImage: imageLib.imageSizeCache(metaData.authorImage.url), ogImage: imageLib.imageSizeCache(metaData.ogImage.url), logo: imageLib.imageSizeCache(metaData.blog.logo.url) }; return Promise .props(fetch) .then(function (imageObj) { _.forEach(imageObj, function (key, value) { if (_.has(key, 'width') && _.has(key, 'height')) { // We have some restrictions for publisher.logo: // The image needs to be <=600px wide and <=60px high (ideally exactly 600px x 60px). // Unless we have proper image-handling (see https://github.com/TryGhost/Ghost/issues/4453), // we will fake it in some cases or not produce an imageObject at all. if (value === 'logo') { if (key.height <= 60 && key.width <= 600) { _.assign(metaData.blog[value], { dimensions: { width: key.width, height: key.height } }); } else if (key.width === key.height) { // CASE: the logo is too large, but it is a square. We fake it... _.assign(metaData.blog[value], { dimensions: { width: 60, height: 60 } }); } } else { _.assign(metaData[value], { dimensions: { width: key.width, height: key.height } }); } } }); return metaData; }); }
[ "function", "getImageDimensions", "(", "metaData", ")", "{", "var", "fetch", "=", "{", "coverImage", ":", "imageLib", ".", "imageSizeCache", "(", "metaData", ".", "coverImage", ".", "url", ")", ",", "authorImage", ":", "imageLib", ".", "imageSizeCache", "(", "metaData", ".", "authorImage", ".", "url", ")", ",", "ogImage", ":", "imageLib", ".", "imageSizeCache", "(", "metaData", ".", "ogImage", ".", "url", ")", ",", "logo", ":", "imageLib", ".", "imageSizeCache", "(", "metaData", ".", "blog", ".", "logo", ".", "url", ")", "}", ";", "return", "Promise", ".", "props", "(", "fetch", ")", ".", "then", "(", "function", "(", "imageObj", ")", "{", "_", ".", "forEach", "(", "imageObj", ",", "function", "(", "key", ",", "value", ")", "{", "if", "(", "_", ".", "has", "(", "key", ",", "'width'", ")", "&&", "_", ".", "has", "(", "key", ",", "'height'", ")", ")", "{", "if", "(", "value", "===", "'logo'", ")", "{", "if", "(", "key", ".", "height", "<=", "60", "&&", "key", ".", "width", "<=", "600", ")", "{", "_", ".", "assign", "(", "metaData", ".", "blog", "[", "value", "]", ",", "{", "dimensions", ":", "{", "width", ":", "key", ".", "width", ",", "height", ":", "key", ".", "height", "}", "}", ")", ";", "}", "else", "if", "(", "key", ".", "width", "===", "key", ".", "height", ")", "{", "_", ".", "assign", "(", "metaData", ".", "blog", "[", "value", "]", ",", "{", "dimensions", ":", "{", "width", ":", "60", ",", "height", ":", "60", "}", "}", ")", ";", "}", "}", "else", "{", "_", ".", "assign", "(", "metaData", "[", "value", "]", ",", "{", "dimensions", ":", "{", "width", ":", "key", ".", "width", ",", "height", ":", "key", ".", "height", "}", "}", ")", ";", "}", "}", "}", ")", ";", "return", "metaData", ";", "}", ")", ";", "}" ]
Get Image dimensions @param {object} metaData @returns {object} metaData @description for image properties in meta data (coverImage, authorImage and blog.logo), `getCachedImageSizeFromUrl` is called to receive image width and height
[ "Get", "Image", "dimensions" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/data/meta/image-dimensions.js#L12-L59
train
TryGhost/Ghost
core/server/services/permissions/can-this.js
function (perm) { var permObjId; // Look for a matching action type and object type first if (perm.get('action_type') !== actType || perm.get('object_type') !== objType) { return false; } // Grab the object id (if specified, could be null) permObjId = perm.get('object_id'); // If we didn't specify a model (any thing) // or the permission didn't have an id scope set // then the "thing" has permission if (!modelId || !permObjId) { return true; } // Otherwise, check if the id's match // TODO: String vs Int comparison possibility here? return modelId === permObjId; }
javascript
function (perm) { var permObjId; // Look for a matching action type and object type first if (perm.get('action_type') !== actType || perm.get('object_type') !== objType) { return false; } // Grab the object id (if specified, could be null) permObjId = perm.get('object_id'); // If we didn't specify a model (any thing) // or the permission didn't have an id scope set // then the "thing" has permission if (!modelId || !permObjId) { return true; } // Otherwise, check if the id's match // TODO: String vs Int comparison possibility here? return modelId === permObjId; }
[ "function", "(", "perm", ")", "{", "var", "permObjId", ";", "if", "(", "perm", ".", "get", "(", "'action_type'", ")", "!==", "actType", "||", "perm", ".", "get", "(", "'object_type'", ")", "!==", "objType", ")", "{", "return", "false", ";", "}", "permObjId", "=", "perm", ".", "get", "(", "'object_id'", ")", ";", "if", "(", "!", "modelId", "||", "!", "permObjId", ")", "{", "return", "true", ";", "}", "return", "modelId", "===", "permObjId", ";", "}" ]
Iterate through the user permissions looking for an affirmation
[ "Iterate", "through", "the", "user", "permissions", "looking", "for", "an", "affirmation" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/services/permissions/can-this.js#L58-L79
train
TryGhost/Ghost
core/server/api/v0.1/mail.js
sendMail
function sendMail(object) { if (!(mailer instanceof mail.GhostMailer)) { mailer = new mail.GhostMailer(); } return mailer.send(object.mail[0].message).catch((err) => { if (mailer.state.usingDirect) { notificationsAPI.add( { notifications: [{ type: 'warn', message: [ common.i18n.t('warnings.index.unableToSendEmail'), common.i18n.t('common.seeLinkForInstructions', {link: 'https://docs.ghost.org/mail/'}) ].join(' ') }] }, {context: {internal: true}} ); } return Promise.reject(err); }); }
javascript
function sendMail(object) { if (!(mailer instanceof mail.GhostMailer)) { mailer = new mail.GhostMailer(); } return mailer.send(object.mail[0].message).catch((err) => { if (mailer.state.usingDirect) { notificationsAPI.add( { notifications: [{ type: 'warn', message: [ common.i18n.t('warnings.index.unableToSendEmail'), common.i18n.t('common.seeLinkForInstructions', {link: 'https://docs.ghost.org/mail/'}) ].join(' ') }] }, {context: {internal: true}} ); } return Promise.reject(err); }); }
[ "function", "sendMail", "(", "object", ")", "{", "if", "(", "!", "(", "mailer", "instanceof", "mail", ".", "GhostMailer", ")", ")", "{", "mailer", "=", "new", "mail", ".", "GhostMailer", "(", ")", ";", "}", "return", "mailer", ".", "send", "(", "object", ".", "mail", "[", "0", "]", ".", "message", ")", ".", "catch", "(", "(", "err", ")", "=>", "{", "if", "(", "mailer", ".", "state", ".", "usingDirect", ")", "{", "notificationsAPI", ".", "add", "(", "{", "notifications", ":", "[", "{", "type", ":", "'warn'", ",", "message", ":", "[", "common", ".", "i18n", ".", "t", "(", "'warnings.index.unableToSendEmail'", ")", ",", "common", ".", "i18n", ".", "t", "(", "'common.seeLinkForInstructions'", ",", "{", "link", ":", "'https://docs.ghost.org/mail/'", "}", ")", "]", ".", "join", "(", "' '", ")", "}", "]", "}", ",", "{", "context", ":", "{", "internal", ":", "true", "}", "}", ")", ";", "}", "return", "Promise", ".", "reject", "(", "err", ")", ";", "}", ")", ";", "}" ]
Send mail helper
[ "Send", "mail", "helper" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/api/v0.1/mail.js#L18-L41
train
TryGhost/Ghost
core/server/apps/subscribers/lib/router.js
errorHandler
function errorHandler(error, req, res, next) { req.body.email = ''; req.body.subscribed_url = santizeUrl(req.body.subscribed_url); req.body.subscribed_referrer = santizeUrl(req.body.subscribed_referrer); if (error.statusCode !== 404) { res.locals.error = error; return _renderer(req, res); } next(error); }
javascript
function errorHandler(error, req, res, next) { req.body.email = ''; req.body.subscribed_url = santizeUrl(req.body.subscribed_url); req.body.subscribed_referrer = santizeUrl(req.body.subscribed_referrer); if (error.statusCode !== 404) { res.locals.error = error; return _renderer(req, res); } next(error); }
[ "function", "errorHandler", "(", "error", ",", "req", ",", "res", ",", "next", ")", "{", "req", ".", "body", ".", "email", "=", "''", ";", "req", ".", "body", ".", "subscribed_url", "=", "santizeUrl", "(", "req", ".", "body", ".", "subscribed_url", ")", ";", "req", ".", "body", ".", "subscribed_referrer", "=", "santizeUrl", "(", "req", ".", "body", ".", "subscribed_referrer", ")", ";", "if", "(", "error", ".", "statusCode", "!==", "404", ")", "{", "res", ".", "locals", ".", "error", "=", "error", ";", "return", "_renderer", "(", "req", ",", "res", ")", ";", "}", "next", "(", "error", ")", ";", "}" ]
Takes care of sanitizing the email input. XSS prevention. For success cases, we don't have to worry, because then the input contained a valid email address.
[ "Takes", "care", "of", "sanitizing", "the", "email", "input", ".", "XSS", "prevention", ".", "For", "success", "cases", "we", "don", "t", "have", "to", "worry", "because", "then", "the", "input", "contained", "a", "valid", "email", "address", "." ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/apps/subscribers/lib/router.js#L33-L44
train
TryGhost/Ghost
core/server/api/v0.1/subscribers.js
exportSubscribers
function exportSubscribers() { return models.Subscriber.findAll(options).then((data) => { return formatCSV(data.toJSON(options)); }).catch((err) => { return Promise.reject(new common.errors.GhostError({err: err})); }); }
javascript
function exportSubscribers() { return models.Subscriber.findAll(options).then((data) => { return formatCSV(data.toJSON(options)); }).catch((err) => { return Promise.reject(new common.errors.GhostError({err: err})); }); }
[ "function", "exportSubscribers", "(", ")", "{", "return", "models", ".", "Subscriber", ".", "findAll", "(", "options", ")", ".", "then", "(", "(", "data", ")", "=>", "{", "return", "formatCSV", "(", "data", ".", "toJSON", "(", "options", ")", ")", ";", "}", ")", ".", "catch", "(", "(", "err", ")", "=>", "{", "return", "Promise", ".", "reject", "(", "new", "common", ".", "errors", ".", "GhostError", "(", "{", "err", ":", "err", "}", ")", ")", ";", "}", ")", ";", "}" ]
Export data, otherwise send error 500
[ "Export", "data", "otherwise", "send", "error", "500" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/api/v0.1/subscribers.js#L285-L291
train
TryGhost/Ghost
core/server/lib/common/i18n.js
t
function t(path, bindings) { let string, isTheme, msg; currentLocale = I18n.locale(); if (bindings !== undefined) { isTheme = bindings.isThemeString; delete bindings.isThemeString; } string = I18n.findString(path, {isThemeString: isTheme}); // If the path returns an array (as in the case with anything that has multiple paragraphs such as emails), then // loop through them and return an array of translated/formatted strings. Otherwise, just return the normal // translated/formatted string. if (Array.isArray(string)) { msg = []; string.forEach(function (s) { let m = new MessageFormat(s, currentLocale); try { m.format(bindings); } catch (err) { logging.error(err.message); // fallback m = new MessageFormat(coreStrings.errors.errors.anErrorOccurred, currentLocale); m = msg.format(); } msg.push(m); }); } else { msg = new MessageFormat(string, currentLocale); try { msg = msg.format(bindings); } catch (err) { logging.error(err.message); // fallback msg = new MessageFormat(coreStrings.errors.errors.anErrorOccurred, currentLocale); msg = msg.format(); } } return msg; }
javascript
function t(path, bindings) { let string, isTheme, msg; currentLocale = I18n.locale(); if (bindings !== undefined) { isTheme = bindings.isThemeString; delete bindings.isThemeString; } string = I18n.findString(path, {isThemeString: isTheme}); // If the path returns an array (as in the case with anything that has multiple paragraphs such as emails), then // loop through them and return an array of translated/formatted strings. Otherwise, just return the normal // translated/formatted string. if (Array.isArray(string)) { msg = []; string.forEach(function (s) { let m = new MessageFormat(s, currentLocale); try { m.format(bindings); } catch (err) { logging.error(err.message); // fallback m = new MessageFormat(coreStrings.errors.errors.anErrorOccurred, currentLocale); m = msg.format(); } msg.push(m); }); } else { msg = new MessageFormat(string, currentLocale); try { msg = msg.format(bindings); } catch (err) { logging.error(err.message); // fallback msg = new MessageFormat(coreStrings.errors.errors.anErrorOccurred, currentLocale); msg = msg.format(); } } return msg; }
[ "function", "t", "(", "path", ",", "bindings", ")", "{", "let", "string", ",", "isTheme", ",", "msg", ";", "currentLocale", "=", "I18n", ".", "locale", "(", ")", ";", "if", "(", "bindings", "!==", "undefined", ")", "{", "isTheme", "=", "bindings", ".", "isThemeString", ";", "delete", "bindings", ".", "isThemeString", ";", "}", "string", "=", "I18n", ".", "findString", "(", "path", ",", "{", "isThemeString", ":", "isTheme", "}", ")", ";", "if", "(", "Array", ".", "isArray", "(", "string", ")", ")", "{", "msg", "=", "[", "]", ";", "string", ".", "forEach", "(", "function", "(", "s", ")", "{", "let", "m", "=", "new", "MessageFormat", "(", "s", ",", "currentLocale", ")", ";", "try", "{", "m", ".", "format", "(", "bindings", ")", ";", "}", "catch", "(", "err", ")", "{", "logging", ".", "error", "(", "err", ".", "message", ")", ";", "m", "=", "new", "MessageFormat", "(", "coreStrings", ".", "errors", ".", "errors", ".", "anErrorOccurred", ",", "currentLocale", ")", ";", "m", "=", "msg", ".", "format", "(", ")", ";", "}", "msg", ".", "push", "(", "m", ")", ";", "}", ")", ";", "}", "else", "{", "msg", "=", "new", "MessageFormat", "(", "string", ",", "currentLocale", ")", ";", "try", "{", "msg", "=", "msg", ".", "format", "(", "bindings", ")", ";", "}", "catch", "(", "err", ")", "{", "logging", ".", "error", "(", "err", ".", "message", ")", ";", "msg", "=", "new", "MessageFormat", "(", "coreStrings", ".", "errors", ".", "errors", ".", "anErrorOccurred", ",", "currentLocale", ")", ";", "msg", "=", "msg", ".", "format", "(", ")", ";", "}", "}", "return", "msg", ";", "}" ]
Helper method to find and compile the given data context with a proper string resource. @param {string} path Path with in the JSON language file to desired string (ie: "errors.init.jsNotBuilt") @param {object} [bindings] @returns {string}
[ "Helper", "method", "to", "find", "and", "compile", "the", "given", "data", "context", "with", "a", "proper", "string", "resource", "." ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/lib/common/i18n.js#L61-L106
train
TryGhost/Ghost
core/server/lib/common/i18n.js
findString
function findString(msgPath, opts) { const options = merge({log: true}, opts || {}); let candidateString, matchingString, path; // no path? no string if (msgPath.length === 0 || !isString(msgPath)) { chalk.yellow('i18n.t() - received an empty path.'); return ''; } // If not in memory, load translations for core if (coreStrings === undefined) { I18n.init(); } if (options.isThemeString) { // If not in memory, load translations for theme if (themeStrings === undefined) { I18n.loadThemeTranslations(); } // Both jsonpath's dot-notation and bracket-notation start with '$' // E.g.: $.store.book.title or $['store']['book']['title'] // The {{t}} translation helper passes the default English text // The full Unicode jsonpath with '$' is built here // jp.stringify and jp.value are jsonpath methods // Info: https://www.npmjs.com/package/jsonpath path = jp.stringify(['$', msgPath]); candidateString = jp.value(themeStrings, path) || msgPath; } else { // Backend messages use dot-notation, and the '$.' prefix is added here // While bracket-notation allows any Unicode characters in keys for themes, // dot-notation allows only word characters in keys for backend messages // (that is \w or [A-Za-z0-9_] in RegExp) path = `$.${msgPath}`; candidateString = jp.value(coreStrings, path); } matchingString = candidateString || {}; if (isObject(matchingString) || isEqual(matchingString, {})) { if (options.log) { logging.error(new errors.IncorrectUsageError({ message: `i18n error: path "${msgPath}" was not found` })); } matchingString = coreStrings.errors.errors.anErrorOccurred; } return matchingString; }
javascript
function findString(msgPath, opts) { const options = merge({log: true}, opts || {}); let candidateString, matchingString, path; // no path? no string if (msgPath.length === 0 || !isString(msgPath)) { chalk.yellow('i18n.t() - received an empty path.'); return ''; } // If not in memory, load translations for core if (coreStrings === undefined) { I18n.init(); } if (options.isThemeString) { // If not in memory, load translations for theme if (themeStrings === undefined) { I18n.loadThemeTranslations(); } // Both jsonpath's dot-notation and bracket-notation start with '$' // E.g.: $.store.book.title or $['store']['book']['title'] // The {{t}} translation helper passes the default English text // The full Unicode jsonpath with '$' is built here // jp.stringify and jp.value are jsonpath methods // Info: https://www.npmjs.com/package/jsonpath path = jp.stringify(['$', msgPath]); candidateString = jp.value(themeStrings, path) || msgPath; } else { // Backend messages use dot-notation, and the '$.' prefix is added here // While bracket-notation allows any Unicode characters in keys for themes, // dot-notation allows only word characters in keys for backend messages // (that is \w or [A-Za-z0-9_] in RegExp) path = `$.${msgPath}`; candidateString = jp.value(coreStrings, path); } matchingString = candidateString || {}; if (isObject(matchingString) || isEqual(matchingString, {})) { if (options.log) { logging.error(new errors.IncorrectUsageError({ message: `i18n error: path "${msgPath}" was not found` })); } matchingString = coreStrings.errors.errors.anErrorOccurred; } return matchingString; }
[ "function", "findString", "(", "msgPath", ",", "opts", ")", "{", "const", "options", "=", "merge", "(", "{", "log", ":", "true", "}", ",", "opts", "||", "{", "}", ")", ";", "let", "candidateString", ",", "matchingString", ",", "path", ";", "if", "(", "msgPath", ".", "length", "===", "0", "||", "!", "isString", "(", "msgPath", ")", ")", "{", "chalk", ".", "yellow", "(", "'i18n.t() - received an empty path.'", ")", ";", "return", "''", ";", "}", "if", "(", "coreStrings", "===", "undefined", ")", "{", "I18n", ".", "init", "(", ")", ";", "}", "if", "(", "options", ".", "isThemeString", ")", "{", "if", "(", "themeStrings", "===", "undefined", ")", "{", "I18n", ".", "loadThemeTranslations", "(", ")", ";", "}", "path", "=", "jp", ".", "stringify", "(", "[", "'$'", ",", "msgPath", "]", ")", ";", "candidateString", "=", "jp", ".", "value", "(", "themeStrings", ",", "path", ")", "||", "msgPath", ";", "}", "else", "{", "path", "=", "`", "${", "msgPath", "}", "`", ";", "candidateString", "=", "jp", ".", "value", "(", "coreStrings", ",", "path", ")", ";", "}", "matchingString", "=", "candidateString", "||", "{", "}", ";", "if", "(", "isObject", "(", "matchingString", ")", "||", "isEqual", "(", "matchingString", ",", "{", "}", ")", ")", "{", "if", "(", "options", ".", "log", ")", "{", "logging", ".", "error", "(", "new", "errors", ".", "IncorrectUsageError", "(", "{", "message", ":", "`", "${", "msgPath", "}", "`", "}", ")", ")", ";", "}", "matchingString", "=", "coreStrings", ".", "errors", ".", "errors", ".", "anErrorOccurred", ";", "}", "return", "matchingString", ";", "}" ]
Parse JSON file for matching locale, returns string giving path. @param {string} msgPath Path with in the JSON language file to desired string (ie: "errors.init.jsNotBuilt") @returns {string}
[ "Parse", "JSON", "file", "for", "matching", "locale", "returns", "string", "giving", "path", "." ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/lib/common/i18n.js#L114-L164
train
TryGhost/Ghost
core/server/models/post.js
onSaved
function onSaved(model, response, options) { ghostBookshelf.Model.prototype.onSaved.apply(this, arguments); if (options.method !== 'insert') { return; } var status = model.get('status'); model.emitChange('added', options); if (['published', 'scheduled'].indexOf(status) !== -1) { model.emitChange(status, options); } }
javascript
function onSaved(model, response, options) { ghostBookshelf.Model.prototype.onSaved.apply(this, arguments); if (options.method !== 'insert') { return; } var status = model.get('status'); model.emitChange('added', options); if (['published', 'scheduled'].indexOf(status) !== -1) { model.emitChange(status, options); } }
[ "function", "onSaved", "(", "model", ",", "response", ",", "options", ")", "{", "ghostBookshelf", ".", "Model", ".", "prototype", ".", "onSaved", ".", "apply", "(", "this", ",", "arguments", ")", ";", "if", "(", "options", ".", "method", "!==", "'insert'", ")", "{", "return", ";", "}", "var", "status", "=", "model", ".", "get", "(", "'status'", ")", ";", "model", ".", "emitChange", "(", "'added'", ",", "options", ")", ";", "if", "(", "[", "'published'", ",", "'scheduled'", "]", ".", "indexOf", "(", "status", ")", "!==", "-", "1", ")", "{", "model", ".", "emitChange", "(", "status", ",", "options", ")", ";", "}", "}" ]
We update the tags after the Post was inserted. We update the tags before the Post was updated, see `onSaving` event. `onCreated` is called before `onSaved`. `onSaved` is the last event in the line - triggered for updating or inserting data. bookshelf-relations listens on `created` + `updated`. We ensure that we are catching the event after bookshelf relations.
[ "We", "update", "the", "tags", "after", "the", "Post", "was", "inserted", ".", "We", "update", "the", "tags", "before", "the", "Post", "was", "updated", "see", "onSaving", "event", ".", "onCreated", "is", "called", "before", "onSaved", "." ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/models/post.js#L97-L111
train
TryGhost/Ghost
core/server/models/post.js
filterData
function filterData(data) { var filteredData = ghostBookshelf.Model.filterData.apply(this, arguments), extraData = _.pick(data, this.prototype.relationships); _.merge(filteredData, extraData); return filteredData; }
javascript
function filterData(data) { var filteredData = ghostBookshelf.Model.filterData.apply(this, arguments), extraData = _.pick(data, this.prototype.relationships); _.merge(filteredData, extraData); return filteredData; }
[ "function", "filterData", "(", "data", ")", "{", "var", "filteredData", "=", "ghostBookshelf", ".", "Model", ".", "filterData", ".", "apply", "(", "this", ",", "arguments", ")", ",", "extraData", "=", "_", ".", "pick", "(", "data", ",", "this", ".", "prototype", ".", "relationships", ")", ";", "_", ".", "merge", "(", "filteredData", ",", "extraData", ")", ";", "return", "filteredData", ";", "}" ]
Manually add 'tags' attribute since it's not in the schema and call parent. @param {Object} data Has keys representing the model's attributes/fields in the database. @return {Object} The filtered results of the passed in data, containing only what's allowed in the schema.
[ "Manually", "add", "tags", "attribute", "since", "it", "s", "not", "in", "the", "schema", "and", "call", "parent", "." ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/models/post.js#L749-L755
train
TryGhost/Ghost
core/server/api/v2/utils/serializers/output/utils/members.js
hideMembersOnlyContent
function hideMembersOnlyContent(attrs, frame) { const membersEnabled = labs.isSet('members'); if (!membersEnabled) { return PERMIT_CONTENT; } const postHasMemberTag = attrs.tags && attrs.tags.find((tag) => { return (tag.name === MEMBER_TAG); }); const requestFromMember = frame.original.context.member; if (!postHasMemberTag) { return PERMIT_CONTENT; } if (!requestFromMember) { return BLOCK_CONTENT; } const memberHasPlan = !!(frame.original.context.member.plans || []).length; if (!membersService.api.isPaymentConfigured()) { return PERMIT_CONTENT; } if (memberHasPlan) { return PERMIT_CONTENT; } return BLOCK_CONTENT; }
javascript
function hideMembersOnlyContent(attrs, frame) { const membersEnabled = labs.isSet('members'); if (!membersEnabled) { return PERMIT_CONTENT; } const postHasMemberTag = attrs.tags && attrs.tags.find((tag) => { return (tag.name === MEMBER_TAG); }); const requestFromMember = frame.original.context.member; if (!postHasMemberTag) { return PERMIT_CONTENT; } if (!requestFromMember) { return BLOCK_CONTENT; } const memberHasPlan = !!(frame.original.context.member.plans || []).length; if (!membersService.api.isPaymentConfigured()) { return PERMIT_CONTENT; } if (memberHasPlan) { return PERMIT_CONTENT; } return BLOCK_CONTENT; }
[ "function", "hideMembersOnlyContent", "(", "attrs", ",", "frame", ")", "{", "const", "membersEnabled", "=", "labs", ".", "isSet", "(", "'members'", ")", ";", "if", "(", "!", "membersEnabled", ")", "{", "return", "PERMIT_CONTENT", ";", "}", "const", "postHasMemberTag", "=", "attrs", ".", "tags", "&&", "attrs", ".", "tags", ".", "find", "(", "(", "tag", ")", "=>", "{", "return", "(", "tag", ".", "name", "===", "MEMBER_TAG", ")", ";", "}", ")", ";", "const", "requestFromMember", "=", "frame", ".", "original", ".", "context", ".", "member", ";", "if", "(", "!", "postHasMemberTag", ")", "{", "return", "PERMIT_CONTENT", ";", "}", "if", "(", "!", "requestFromMember", ")", "{", "return", "BLOCK_CONTENT", ";", "}", "const", "memberHasPlan", "=", "!", "!", "(", "frame", ".", "original", ".", "context", ".", "member", ".", "plans", "||", "[", "]", ")", ".", "length", ";", "if", "(", "!", "membersService", ".", "api", ".", "isPaymentConfigured", "(", ")", ")", "{", "return", "PERMIT_CONTENT", ";", "}", "if", "(", "memberHasPlan", ")", "{", "return", "PERMIT_CONTENT", ";", "}", "return", "BLOCK_CONTENT", ";", "}" ]
Checks if request should hide memnbers only content
[ "Checks", "if", "request", "should", "hide", "memnbers", "only", "content" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/api/v2/utils/serializers/output/utils/members.js#L8-L33
train
TryGhost/Ghost
core/server/services/url/utils.js
getVersionPath
function getVersionPath(options) { const apiVersions = config.get('api:versions'); let requestedVersion = options.version || 'v0.1'; let requestedVersionType = options.type || 'content'; let versionData = apiVersions[requestedVersion]; if (typeof versionData === 'string') { versionData = apiVersions[versionData]; } let versionPath = versionData[requestedVersionType]; return `/${versionPath}/`; }
javascript
function getVersionPath(options) { const apiVersions = config.get('api:versions'); let requestedVersion = options.version || 'v0.1'; let requestedVersionType = options.type || 'content'; let versionData = apiVersions[requestedVersion]; if (typeof versionData === 'string') { versionData = apiVersions[versionData]; } let versionPath = versionData[requestedVersionType]; return `/${versionPath}/`; }
[ "function", "getVersionPath", "(", "options", ")", "{", "const", "apiVersions", "=", "config", ".", "get", "(", "'api:versions'", ")", ";", "let", "requestedVersion", "=", "options", ".", "version", "||", "'v0.1'", ";", "let", "requestedVersionType", "=", "options", ".", "type", "||", "'content'", ";", "let", "versionData", "=", "apiVersions", "[", "requestedVersion", "]", ";", "if", "(", "typeof", "versionData", "===", "'string'", ")", "{", "versionData", "=", "apiVersions", "[", "versionData", "]", ";", "}", "let", "versionPath", "=", "versionData", "[", "requestedVersionType", "]", ";", "return", "`", "${", "versionPath", "}", "`", ";", "}" ]
Returns path containing only the path for the specific version asked or deprecated by default @param {Object} options {version} for which to get the path(stable, actice, deprecated), {type} admin|content: defaults to {version: deprecated, type: content} @return {string} API version path
[ "Returns", "path", "containing", "only", "the", "path", "for", "the", "specific", "version", "asked", "or", "deprecated", "by", "default" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/services/url/utils.js#L29-L39
train
TryGhost/Ghost
core/server/services/url/utils.js
getBlogUrl
function getBlogUrl(secure) { var blogUrl; if (secure) { blogUrl = config.get('url').replace('http://', 'https://'); } else { blogUrl = config.get('url'); } if (!blogUrl.match(/\/$/)) { blogUrl += '/'; } return blogUrl; }
javascript
function getBlogUrl(secure) { var blogUrl; if (secure) { blogUrl = config.get('url').replace('http://', 'https://'); } else { blogUrl = config.get('url'); } if (!blogUrl.match(/\/$/)) { blogUrl += '/'; } return blogUrl; }
[ "function", "getBlogUrl", "(", "secure", ")", "{", "var", "blogUrl", ";", "if", "(", "secure", ")", "{", "blogUrl", "=", "config", ".", "get", "(", "'url'", ")", ".", "replace", "(", "'http://'", ",", "'https://'", ")", ";", "}", "else", "{", "blogUrl", "=", "config", ".", "get", "(", "'url'", ")", ";", "}", "if", "(", "!", "blogUrl", ".", "match", "(", "/", "\\/$", "/", ")", ")", "{", "blogUrl", "+=", "'/'", ";", "}", "return", "blogUrl", ";", "}" ]
Returns the base URL of the blog as set in the config. Secure: If the request is secure, we want to force returning the blog url as https. Imagine Ghost runs with http, but nginx allows SSL connections. @param {boolean} secure @return {string} URL returns the url as defined in config, but always with a trailing `/`
[ "Returns", "the", "base", "URL", "of", "the", "blog", "as", "set", "in", "the", "config", "." ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/services/url/utils.js#L51-L65
train
TryGhost/Ghost
core/server/services/url/utils.js
getSubdir
function getSubdir() { // Parse local path location var localPath = url.parse(config.get('url')).path, subdir; // Remove trailing slash if (localPath !== '/') { localPath = localPath.replace(/\/$/, ''); } subdir = localPath === '/' ? '' : localPath; return subdir; }
javascript
function getSubdir() { // Parse local path location var localPath = url.parse(config.get('url')).path, subdir; // Remove trailing slash if (localPath !== '/') { localPath = localPath.replace(/\/$/, ''); } subdir = localPath === '/' ? '' : localPath; return subdir; }
[ "function", "getSubdir", "(", ")", "{", "var", "localPath", "=", "url", ".", "parse", "(", "config", ".", "get", "(", "'url'", ")", ")", ".", "path", ",", "subdir", ";", "if", "(", "localPath", "!==", "'/'", ")", "{", "localPath", "=", "localPath", ".", "replace", "(", "/", "\\/$", "/", ",", "''", ")", ";", "}", "subdir", "=", "localPath", "===", "'/'", "?", "''", ":", "localPath", ";", "return", "subdir", ";", "}" ]
Returns a subdirectory URL, if defined so in the config. @return {string} URL a subdirectory if configured.
[ "Returns", "a", "subdirectory", "URL", "if", "defined", "so", "in", "the", "config", "." ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/services/url/utils.js#L71-L83
train
TryGhost/Ghost
core/server/services/url/utils.js
replacePermalink
function replacePermalink(permalink, resource) { let output = permalink, primaryTagFallback = 'all', publishedAtMoment = moment.tz(resource.published_at || Date.now(), settingsCache.get('active_timezone')), permalinkLookUp = { year: function () { return publishedAtMoment.format('YYYY'); }, month: function () { return publishedAtMoment.format('MM'); }, day: function () { return publishedAtMoment.format('DD'); }, author: function () { return resource.primary_author.slug; }, primary_author: function () { return resource.primary_author ? resource.primary_author.slug : primaryTagFallback; }, primary_tag: function () { return resource.primary_tag ? resource.primary_tag.slug : primaryTagFallback; }, slug: function () { return resource.slug; }, id: function () { return resource.id; } }; // replace tags like :slug or :year with actual values output = output.replace(/(:[a-z_]+)/g, function (match) { if (_.has(permalinkLookUp, match.substr(1))) { return permalinkLookUp[match.substr(1)](); } }); return output; }
javascript
function replacePermalink(permalink, resource) { let output = permalink, primaryTagFallback = 'all', publishedAtMoment = moment.tz(resource.published_at || Date.now(), settingsCache.get('active_timezone')), permalinkLookUp = { year: function () { return publishedAtMoment.format('YYYY'); }, month: function () { return publishedAtMoment.format('MM'); }, day: function () { return publishedAtMoment.format('DD'); }, author: function () { return resource.primary_author.slug; }, primary_author: function () { return resource.primary_author ? resource.primary_author.slug : primaryTagFallback; }, primary_tag: function () { return resource.primary_tag ? resource.primary_tag.slug : primaryTagFallback; }, slug: function () { return resource.slug; }, id: function () { return resource.id; } }; // replace tags like :slug or :year with actual values output = output.replace(/(:[a-z_]+)/g, function (match) { if (_.has(permalinkLookUp, match.substr(1))) { return permalinkLookUp[match.substr(1)](); } }); return output; }
[ "function", "replacePermalink", "(", "permalink", ",", "resource", ")", "{", "let", "output", "=", "permalink", ",", "primaryTagFallback", "=", "'all'", ",", "publishedAtMoment", "=", "moment", ".", "tz", "(", "resource", ".", "published_at", "||", "Date", ".", "now", "(", ")", ",", "settingsCache", ".", "get", "(", "'active_timezone'", ")", ")", ",", "permalinkLookUp", "=", "{", "year", ":", "function", "(", ")", "{", "return", "publishedAtMoment", ".", "format", "(", "'YYYY'", ")", ";", "}", ",", "month", ":", "function", "(", ")", "{", "return", "publishedAtMoment", ".", "format", "(", "'MM'", ")", ";", "}", ",", "day", ":", "function", "(", ")", "{", "return", "publishedAtMoment", ".", "format", "(", "'DD'", ")", ";", "}", ",", "author", ":", "function", "(", ")", "{", "return", "resource", ".", "primary_author", ".", "slug", ";", "}", ",", "primary_author", ":", "function", "(", ")", "{", "return", "resource", ".", "primary_author", "?", "resource", ".", "primary_author", ".", "slug", ":", "primaryTagFallback", ";", "}", ",", "primary_tag", ":", "function", "(", ")", "{", "return", "resource", ".", "primary_tag", "?", "resource", ".", "primary_tag", ".", "slug", ":", "primaryTagFallback", ";", "}", ",", "slug", ":", "function", "(", ")", "{", "return", "resource", ".", "slug", ";", "}", ",", "id", ":", "function", "(", ")", "{", "return", "resource", ".", "id", ";", "}", "}", ";", "output", "=", "output", ".", "replace", "(", "/", "(:[a-z_]+)", "/", "g", ",", "function", "(", "match", ")", "{", "if", "(", "_", ".", "has", "(", "permalinkLookUp", ",", "match", ".", "substr", "(", "1", ")", ")", ")", "{", "return", "permalinkLookUp", "[", "match", ".", "substr", "(", "1", ")", "]", "(", ")", ";", "}", "}", ")", ";", "return", "output", ";", "}" ]
creates the url path for a post based on blog timezone and permalink pattern
[ "creates", "the", "url", "path", "for", "a", "post", "based", "on", "blog", "timezone", "and", "permalink", "pattern" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/services/url/utils.js#L204-L243
train
TryGhost/Ghost
core/server/services/url/utils.js
makeAbsoluteUrls
function makeAbsoluteUrls(html, siteUrl, itemUrl, options = {assetsOnly: false}) { html = html || ''; const htmlContent = cheerio.load(html, {decodeEntities: false}); const staticImageUrlPrefixRegex = new RegExp(STATIC_IMAGE_URL_PREFIX); // convert relative resource urls to absolute ['href', 'src'].forEach(function forEach(attributeName) { htmlContent('[' + attributeName + ']').each(function each(ix, el) { el = htmlContent(el); let attributeValue = el.attr(attributeName); // if URL is absolute move on to the next element try { const parsed = url.parse(attributeValue); if (parsed.protocol) { return; } // Do not convert protocol relative URLs if (attributeValue.lastIndexOf('//', 0) === 0) { return; } } catch (e) { return; } // CASE: don't convert internal links if (attributeValue[0] === '#') { return; } if (options.assetsOnly && !attributeValue.match(staticImageUrlPrefixRegex)) { return; } // compose an absolute URL // if the relative URL begins with a '/' use the blog URL (including sub-directory) // as the base URL, otherwise use the post's URL. const baseUrl = attributeValue[0] === '/' ? siteUrl : itemUrl; attributeValue = urlJoin(baseUrl, attributeValue); el.attr(attributeName, attributeValue); }); }); return htmlContent; }
javascript
function makeAbsoluteUrls(html, siteUrl, itemUrl, options = {assetsOnly: false}) { html = html || ''; const htmlContent = cheerio.load(html, {decodeEntities: false}); const staticImageUrlPrefixRegex = new RegExp(STATIC_IMAGE_URL_PREFIX); // convert relative resource urls to absolute ['href', 'src'].forEach(function forEach(attributeName) { htmlContent('[' + attributeName + ']').each(function each(ix, el) { el = htmlContent(el); let attributeValue = el.attr(attributeName); // if URL is absolute move on to the next element try { const parsed = url.parse(attributeValue); if (parsed.protocol) { return; } // Do not convert protocol relative URLs if (attributeValue.lastIndexOf('//', 0) === 0) { return; } } catch (e) { return; } // CASE: don't convert internal links if (attributeValue[0] === '#') { return; } if (options.assetsOnly && !attributeValue.match(staticImageUrlPrefixRegex)) { return; } // compose an absolute URL // if the relative URL begins with a '/' use the blog URL (including sub-directory) // as the base URL, otherwise use the post's URL. const baseUrl = attributeValue[0] === '/' ? siteUrl : itemUrl; attributeValue = urlJoin(baseUrl, attributeValue); el.attr(attributeName, attributeValue); }); }); return htmlContent; }
[ "function", "makeAbsoluteUrls", "(", "html", ",", "siteUrl", ",", "itemUrl", ",", "options", "=", "{", "assetsOnly", ":", "false", "}", ")", "{", "html", "=", "html", "||", "''", ";", "const", "htmlContent", "=", "cheerio", ".", "load", "(", "html", ",", "{", "decodeEntities", ":", "false", "}", ")", ";", "const", "staticImageUrlPrefixRegex", "=", "new", "RegExp", "(", "STATIC_IMAGE_URL_PREFIX", ")", ";", "[", "'href'", ",", "'src'", "]", ".", "forEach", "(", "function", "forEach", "(", "attributeName", ")", "{", "htmlContent", "(", "'['", "+", "attributeName", "+", "']'", ")", ".", "each", "(", "function", "each", "(", "ix", ",", "el", ")", "{", "el", "=", "htmlContent", "(", "el", ")", ";", "let", "attributeValue", "=", "el", ".", "attr", "(", "attributeName", ")", ";", "try", "{", "const", "parsed", "=", "url", ".", "parse", "(", "attributeValue", ")", ";", "if", "(", "parsed", ".", "protocol", ")", "{", "return", ";", "}", "if", "(", "attributeValue", ".", "lastIndexOf", "(", "'//'", ",", "0", ")", "===", "0", ")", "{", "return", ";", "}", "}", "catch", "(", "e", ")", "{", "return", ";", "}", "if", "(", "attributeValue", "[", "0", "]", "===", "'#'", ")", "{", "return", ";", "}", "if", "(", "options", ".", "assetsOnly", "&&", "!", "attributeValue", ".", "match", "(", "staticImageUrlPrefixRegex", ")", ")", "{", "return", ";", "}", "const", "baseUrl", "=", "attributeValue", "[", "0", "]", "===", "'/'", "?", "siteUrl", ":", "itemUrl", ";", "attributeValue", "=", "urlJoin", "(", "baseUrl", ",", "attributeValue", ")", ";", "el", ".", "attr", "(", "attributeName", ",", "attributeValue", ")", ";", "}", ")", ";", "}", ")", ";", "return", "htmlContent", ";", "}" ]
Make absolute URLs @param {string} html @param {string} siteUrl (blog URL) @param {string} itemUrl (URL of current context) @returns {object} htmlContent @description Takes html, blog url and item url and converts relative url into absolute urls. Returns an object. The html string can be accessed by calling `html()` on the variable that takes the result of this function
[ "Make", "absolute", "URLs" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/services/url/utils.js#L395-L442
train
TryGhost/Ghost
core/server/models/base/index.js
initialize
function initialize() { var self = this; // NOTE: triggered before `creating`/`updating` this.on('saving', function onSaving(newObj, attrs, options) { if (options.method === 'insert') { // id = 0 is still a valid value for external usage if (_.isUndefined(newObj.id) || _.isNull(newObj.id)) { newObj.setId(); } } }); [ 'fetching', 'fetching:collection', 'fetched', 'fetched:collection', 'creating', 'created', 'updating', 'updated', 'destroying', 'destroyed', 'saving', 'saved' ].forEach(function (eventName) { var functionName = 'on' + eventName[0].toUpperCase() + eventName.slice(1); if (functionName.indexOf(':') !== -1) { functionName = functionName.slice(0, functionName.indexOf(':')) + functionName[functionName.indexOf(':') + 1].toUpperCase() + functionName.slice(functionName.indexOf(':') + 2); functionName = functionName.replace(':', ''); } if (!self[functionName]) { return; } self.on(eventName, self[functionName]); }); // @NOTE: Please keep here. If we don't initialize the parent, bookshelf-relations won't work. proto.initialize.call(this); }
javascript
function initialize() { var self = this; // NOTE: triggered before `creating`/`updating` this.on('saving', function onSaving(newObj, attrs, options) { if (options.method === 'insert') { // id = 0 is still a valid value for external usage if (_.isUndefined(newObj.id) || _.isNull(newObj.id)) { newObj.setId(); } } }); [ 'fetching', 'fetching:collection', 'fetched', 'fetched:collection', 'creating', 'created', 'updating', 'updated', 'destroying', 'destroyed', 'saving', 'saved' ].forEach(function (eventName) { var functionName = 'on' + eventName[0].toUpperCase() + eventName.slice(1); if (functionName.indexOf(':') !== -1) { functionName = functionName.slice(0, functionName.indexOf(':')) + functionName[functionName.indexOf(':') + 1].toUpperCase() + functionName.slice(functionName.indexOf(':') + 2); functionName = functionName.replace(':', ''); } if (!self[functionName]) { return; } self.on(eventName, self[functionName]); }); // @NOTE: Please keep here. If we don't initialize the parent, bookshelf-relations won't work. proto.initialize.call(this); }
[ "function", "initialize", "(", ")", "{", "var", "self", "=", "this", ";", "this", ".", "on", "(", "'saving'", ",", "function", "onSaving", "(", "newObj", ",", "attrs", ",", "options", ")", "{", "if", "(", "options", ".", "method", "===", "'insert'", ")", "{", "if", "(", "_", ".", "isUndefined", "(", "newObj", ".", "id", ")", "||", "_", ".", "isNull", "(", "newObj", ".", "id", ")", ")", "{", "newObj", ".", "setId", "(", ")", ";", "}", "}", "}", ")", ";", "[", "'fetching'", ",", "'fetching:collection'", ",", "'fetched'", ",", "'fetched:collection'", ",", "'creating'", ",", "'created'", ",", "'updating'", ",", "'updated'", ",", "'destroying'", ",", "'destroyed'", ",", "'saving'", ",", "'saved'", "]", ".", "forEach", "(", "function", "(", "eventName", ")", "{", "var", "functionName", "=", "'on'", "+", "eventName", "[", "0", "]", ".", "toUpperCase", "(", ")", "+", "eventName", ".", "slice", "(", "1", ")", ";", "if", "(", "functionName", ".", "indexOf", "(", "':'", ")", "!==", "-", "1", ")", "{", "functionName", "=", "functionName", ".", "slice", "(", "0", ",", "functionName", ".", "indexOf", "(", "':'", ")", ")", "+", "functionName", "[", "functionName", ".", "indexOf", "(", "':'", ")", "+", "1", "]", ".", "toUpperCase", "(", ")", "+", "functionName", ".", "slice", "(", "functionName", ".", "indexOf", "(", "':'", ")", "+", "2", ")", ";", "functionName", "=", "functionName", ".", "replace", "(", "':'", ",", "''", ")", ";", "}", "if", "(", "!", "self", "[", "functionName", "]", ")", "{", "return", ";", "}", "self", ".", "on", "(", "eventName", ",", "self", "[", "functionName", "]", ")", ";", "}", ")", ";", "proto", ".", "initialize", ".", "call", "(", "this", ")", ";", "}" ]
Bookshelf `initialize` - declare a constructor-like method for model creation
[ "Bookshelf", "initialize", "-", "declare", "a", "constructor", "-", "like", "method", "for", "model", "creation" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/models/base/index.js#L223-L268
train
TryGhost/Ghost
core/server/models/base/index.js
onUpdating
function onUpdating(model, attr, options) { if (this.relationships) { model.changed = _.omit(model.changed, this.relationships); } if (schema.tables[this.tableName].hasOwnProperty('updated_by')) { if (!options.importing && !options.migrating) { this.set('updated_by', String(this.contextUser(options))); } } if (options && options.context && !options.context.internal && !options.importing) { if (schema.tables[this.tableName].hasOwnProperty('created_at')) { if (model.hasDateChanged('created_at', {beforeWrite: true})) { model.set('created_at', this.previous('created_at')); } } if (schema.tables[this.tableName].hasOwnProperty('created_by')) { if (model.hasChanged('created_by')) { model.set('created_by', String(this.previous('created_by'))); } } } // CASE: do not allow setting only the `updated_at` field, exception: importing if (schema.tables[this.tableName].hasOwnProperty('updated_at') && !options.importing) { if (options.migrating) { model.set('updated_at', model.previous('updated_at')); } else if (Object.keys(model.changed).length === 1 && model.changed.updated_at) { model.set('updated_at', model.previous('updated_at')); delete model.changed.updated_at; } } model._changed = _.cloneDeep(model.changed); return Promise.resolve(this.onValidate(model, attr, options)); }
javascript
function onUpdating(model, attr, options) { if (this.relationships) { model.changed = _.omit(model.changed, this.relationships); } if (schema.tables[this.tableName].hasOwnProperty('updated_by')) { if (!options.importing && !options.migrating) { this.set('updated_by', String(this.contextUser(options))); } } if (options && options.context && !options.context.internal && !options.importing) { if (schema.tables[this.tableName].hasOwnProperty('created_at')) { if (model.hasDateChanged('created_at', {beforeWrite: true})) { model.set('created_at', this.previous('created_at')); } } if (schema.tables[this.tableName].hasOwnProperty('created_by')) { if (model.hasChanged('created_by')) { model.set('created_by', String(this.previous('created_by'))); } } } // CASE: do not allow setting only the `updated_at` field, exception: importing if (schema.tables[this.tableName].hasOwnProperty('updated_at') && !options.importing) { if (options.migrating) { model.set('updated_at', model.previous('updated_at')); } else if (Object.keys(model.changed).length === 1 && model.changed.updated_at) { model.set('updated_at', model.previous('updated_at')); delete model.changed.updated_at; } } model._changed = _.cloneDeep(model.changed); return Promise.resolve(this.onValidate(model, attr, options)); }
[ "function", "onUpdating", "(", "model", ",", "attr", ",", "options", ")", "{", "if", "(", "this", ".", "relationships", ")", "{", "model", ".", "changed", "=", "_", ".", "omit", "(", "model", ".", "changed", ",", "this", ".", "relationships", ")", ";", "}", "if", "(", "schema", ".", "tables", "[", "this", ".", "tableName", "]", ".", "hasOwnProperty", "(", "'updated_by'", ")", ")", "{", "if", "(", "!", "options", ".", "importing", "&&", "!", "options", ".", "migrating", ")", "{", "this", ".", "set", "(", "'updated_by'", ",", "String", "(", "this", ".", "contextUser", "(", "options", ")", ")", ")", ";", "}", "}", "if", "(", "options", "&&", "options", ".", "context", "&&", "!", "options", ".", "context", ".", "internal", "&&", "!", "options", ".", "importing", ")", "{", "if", "(", "schema", ".", "tables", "[", "this", ".", "tableName", "]", ".", "hasOwnProperty", "(", "'created_at'", ")", ")", "{", "if", "(", "model", ".", "hasDateChanged", "(", "'created_at'", ",", "{", "beforeWrite", ":", "true", "}", ")", ")", "{", "model", ".", "set", "(", "'created_at'", ",", "this", ".", "previous", "(", "'created_at'", ")", ")", ";", "}", "}", "if", "(", "schema", ".", "tables", "[", "this", ".", "tableName", "]", ".", "hasOwnProperty", "(", "'created_by'", ")", ")", "{", "if", "(", "model", ".", "hasChanged", "(", "'created_by'", ")", ")", "{", "model", ".", "set", "(", "'created_by'", ",", "String", "(", "this", ".", "previous", "(", "'created_by'", ")", ")", ")", ";", "}", "}", "}", "if", "(", "schema", ".", "tables", "[", "this", ".", "tableName", "]", ".", "hasOwnProperty", "(", "'updated_at'", ")", "&&", "!", "options", ".", "importing", ")", "{", "if", "(", "options", ".", "migrating", ")", "{", "model", ".", "set", "(", "'updated_at'", ",", "model", ".", "previous", "(", "'updated_at'", ")", ")", ";", "}", "else", "if", "(", "Object", ".", "keys", "(", "model", ".", "changed", ")", ".", "length", "===", "1", "&&", "model", ".", "changed", ".", "updated_at", ")", "{", "model", ".", "set", "(", "'updated_at'", ",", "model", ".", "previous", "(", "'updated_at'", ")", ")", ";", "delete", "model", ".", "changed", ".", "updated_at", ";", "}", "}", "model", ".", "_changed", "=", "_", ".", "cloneDeep", "(", "model", ".", "changed", ")", ";", "return", "Promise", ".", "resolve", "(", "this", ".", "onValidate", "(", "model", ",", "attr", ",", "options", ")", ")", ";", "}" ]
Changing resources implies setting these properties on the server side - set `updated_by` based on the context - ensure `created_at` never changes - ensure `created_by` never changes - the bookshelf `timestamps` plugin sets `updated_at` automatically Exceptions: - importing data - internal context - if no context @deprecated: x_by fields (https://github.com/TryGhost/Ghost/issues/10286)
[ "Changing", "resources", "implies", "setting", "these", "properties", "on", "the", "server", "side", "-", "set", "updated_by", "based", "on", "the", "context", "-", "ensure", "created_at", "never", "changes", "-", "ensure", "created_by", "never", "changes", "-", "the", "bookshelf", "timestamps", "plugin", "sets", "updated_at", "automatically" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/models/base/index.js#L376-L414
train
TryGhost/Ghost
core/server/models/base/index.js
fixDates
function fixDates(attrs) { var self = this; _.each(attrs, function each(value, key) { if (value !== null && schema.tables[self.tableName].hasOwnProperty(key) && schema.tables[self.tableName][key].type === 'dateTime') { attrs[key] = moment(value).format('YYYY-MM-DD HH:mm:ss'); } }); return attrs; }
javascript
function fixDates(attrs) { var self = this; _.each(attrs, function each(value, key) { if (value !== null && schema.tables[self.tableName].hasOwnProperty(key) && schema.tables[self.tableName][key].type === 'dateTime') { attrs[key] = moment(value).format('YYYY-MM-DD HH:mm:ss'); } }); return attrs; }
[ "function", "fixDates", "(", "attrs", ")", "{", "var", "self", "=", "this", ";", "_", ".", "each", "(", "attrs", ",", "function", "each", "(", "value", ",", "key", ")", "{", "if", "(", "value", "!==", "null", "&&", "schema", ".", "tables", "[", "self", ".", "tableName", "]", ".", "hasOwnProperty", "(", "key", ")", "&&", "schema", ".", "tables", "[", "self", ".", "tableName", "]", "[", "key", "]", ".", "type", "===", "'dateTime'", ")", "{", "attrs", "[", "key", "]", "=", "moment", "(", "value", ")", ".", "format", "(", "'YYYY-MM-DD HH:mm:ss'", ")", ";", "}", "}", ")", ";", "return", "attrs", ";", "}" ]
before we insert dates into the database, we have to normalize date format is now in each db the same
[ "before", "we", "insert", "dates", "into", "the", "database", "we", "have", "to", "normalize", "date", "format", "is", "now", "in", "each", "db", "the", "same" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/models/base/index.js#L443-L455
train
TryGhost/Ghost
core/server/models/base/index.js
fixBools
function fixBools(attrs) { var self = this; _.each(attrs, function each(value, key) { if (schema.tables[self.tableName].hasOwnProperty(key) && schema.tables[self.tableName][key].type === 'bool') { attrs[key] = value ? true : false; } }); return attrs; }
javascript
function fixBools(attrs) { var self = this; _.each(attrs, function each(value, key) { if (schema.tables[self.tableName].hasOwnProperty(key) && schema.tables[self.tableName][key].type === 'bool') { attrs[key] = value ? true : false; } }); return attrs; }
[ "function", "fixBools", "(", "attrs", ")", "{", "var", "self", "=", "this", ";", "_", ".", "each", "(", "attrs", ",", "function", "each", "(", "value", ",", "key", ")", "{", "if", "(", "schema", ".", "tables", "[", "self", ".", "tableName", "]", ".", "hasOwnProperty", "(", "key", ")", "&&", "schema", ".", "tables", "[", "self", ".", "tableName", "]", "[", "key", "]", ".", "type", "===", "'bool'", ")", "{", "attrs", "[", "key", "]", "=", "value", "?", "true", ":", "false", ";", "}", "}", ")", ";", "return", "attrs", ";", "}" ]
Convert integers to real booleans
[ "Convert", "integers", "to", "real", "booleans" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/models/base/index.js#L488-L498
train
TryGhost/Ghost
core/server/models/base/index.js
contextUser
function contextUser(options) { options = options || {}; options.context = options.context || {}; if (options.context.user || ghostBookshelf.Model.isExternalUser(options.context.user)) { return options.context.user; } else if (options.context.integration) { /** * @NOTE: * * This is a dirty hotfix for v0.1 only. * The `x_by` columns are getting deprecated soon (https://github.com/TryGhost/Ghost/issues/10286). * * We return the owner ID '1' in case an integration updates or creates * resources. v0.1 will continue to use the `x_by` columns. v0.1 does not support integrations. * API v2 will introduce a new feature to solve inserting/updating resources * from users or integrations. API v2 won't expose `x_by` columns anymore. * * --- * * Why using ID '1'? WAIT. What??????? * * See https://github.com/TryGhost/Ghost/issues/9299. * * We currently don't read the correct owner ID from the database and assume it's '1'. * This is a leftover from switching from auto increment ID's to Object ID's. * But this takes too long to refactor out now. If an internal update happens, we also * use ID '1'. This logic exists for a LONG while now. The owner ID only changes from '1' to something else, * if you transfer ownership. */ return ghostBookshelf.Model.internalUser; } else if (options.context.internal) { return ghostBookshelf.Model.internalUser; } else if (this.get('id')) { return this.get('id'); } else if (options.context.external) { return ghostBookshelf.Model.externalUser; } else { throw new common.errors.NotFoundError({ message: common.i18n.t('errors.models.base.index.missingContext'), level: 'critical' }); } }
javascript
function contextUser(options) { options = options || {}; options.context = options.context || {}; if (options.context.user || ghostBookshelf.Model.isExternalUser(options.context.user)) { return options.context.user; } else if (options.context.integration) { /** * @NOTE: * * This is a dirty hotfix for v0.1 only. * The `x_by` columns are getting deprecated soon (https://github.com/TryGhost/Ghost/issues/10286). * * We return the owner ID '1' in case an integration updates or creates * resources. v0.1 will continue to use the `x_by` columns. v0.1 does not support integrations. * API v2 will introduce a new feature to solve inserting/updating resources * from users or integrations. API v2 won't expose `x_by` columns anymore. * * --- * * Why using ID '1'? WAIT. What??????? * * See https://github.com/TryGhost/Ghost/issues/9299. * * We currently don't read the correct owner ID from the database and assume it's '1'. * This is a leftover from switching from auto increment ID's to Object ID's. * But this takes too long to refactor out now. If an internal update happens, we also * use ID '1'. This logic exists for a LONG while now. The owner ID only changes from '1' to something else, * if you transfer ownership. */ return ghostBookshelf.Model.internalUser; } else if (options.context.internal) { return ghostBookshelf.Model.internalUser; } else if (this.get('id')) { return this.get('id'); } else if (options.context.external) { return ghostBookshelf.Model.externalUser; } else { throw new common.errors.NotFoundError({ message: common.i18n.t('errors.models.base.index.missingContext'), level: 'critical' }); } }
[ "function", "contextUser", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "options", ".", "context", "=", "options", ".", "context", "||", "{", "}", ";", "if", "(", "options", ".", "context", ".", "user", "||", "ghostBookshelf", ".", "Model", ".", "isExternalUser", "(", "options", ".", "context", ".", "user", ")", ")", "{", "return", "options", ".", "context", ".", "user", ";", "}", "else", "if", "(", "options", ".", "context", ".", "integration", ")", "{", "return", "ghostBookshelf", ".", "Model", ".", "internalUser", ";", "}", "else", "if", "(", "options", ".", "context", ".", "internal", ")", "{", "return", "ghostBookshelf", ".", "Model", ".", "internalUser", ";", "}", "else", "if", "(", "this", ".", "get", "(", "'id'", ")", ")", "{", "return", "this", ".", "get", "(", "'id'", ")", ";", "}", "else", "if", "(", "options", ".", "context", ".", "external", ")", "{", "return", "ghostBookshelf", ".", "Model", ".", "externalUser", ";", "}", "else", "{", "throw", "new", "common", ".", "errors", ".", "NotFoundError", "(", "{", "message", ":", "common", ".", "i18n", ".", "t", "(", "'errors.models.base.index.missingContext'", ")", ",", "level", ":", "'critical'", "}", ")", ";", "}", "}" ]
Get the user from the options object
[ "Get", "the", "user", "from", "the", "options", "object" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/models/base/index.js#L533-L576
train
TryGhost/Ghost
core/server/models/base/index.js
toJSON
function toJSON(unfilteredOptions) { const options = ghostBookshelf.Model.filterOptions(unfilteredOptions, 'toJSON'); options.omitPivot = true; // CASE: get JSON of previous attrs if (options.previous) { const clonedModel = _.cloneDeep(this); clonedModel.attributes = this._previousAttributes; if (this.relationships) { this.relationships.forEach((relation) => { if (this._previousRelations && this._previousRelations.hasOwnProperty(relation)) { clonedModel.related(relation).models = this._previousRelations[relation].models; } }); } return proto.toJSON.call(clonedModel, options); } return proto.toJSON.call(this, options); }
javascript
function toJSON(unfilteredOptions) { const options = ghostBookshelf.Model.filterOptions(unfilteredOptions, 'toJSON'); options.omitPivot = true; // CASE: get JSON of previous attrs if (options.previous) { const clonedModel = _.cloneDeep(this); clonedModel.attributes = this._previousAttributes; if (this.relationships) { this.relationships.forEach((relation) => { if (this._previousRelations && this._previousRelations.hasOwnProperty(relation)) { clonedModel.related(relation).models = this._previousRelations[relation].models; } }); } return proto.toJSON.call(clonedModel, options); } return proto.toJSON.call(this, options); }
[ "function", "toJSON", "(", "unfilteredOptions", ")", "{", "const", "options", "=", "ghostBookshelf", ".", "Model", ".", "filterOptions", "(", "unfilteredOptions", ",", "'toJSON'", ")", ";", "options", ".", "omitPivot", "=", "true", ";", "if", "(", "options", ".", "previous", ")", "{", "const", "clonedModel", "=", "_", ".", "cloneDeep", "(", "this", ")", ";", "clonedModel", ".", "attributes", "=", "this", ".", "_previousAttributes", ";", "if", "(", "this", ".", "relationships", ")", "{", "this", ".", "relationships", ".", "forEach", "(", "(", "relation", ")", "=>", "{", "if", "(", "this", ".", "_previousRelations", "&&", "this", ".", "_previousRelations", ".", "hasOwnProperty", "(", "relation", ")", ")", "{", "clonedModel", ".", "related", "(", "relation", ")", ".", "models", "=", "this", ".", "_previousRelations", "[", "relation", "]", ".", "models", ";", "}", "}", ")", ";", "}", "return", "proto", ".", "toJSON", ".", "call", "(", "clonedModel", ",", "options", ")", ";", "}", "return", "proto", ".", "toJSON", ".", "call", "(", "this", ",", "options", ")", ";", "}" ]
`shallow` - won't return relations `omitPivot` - won't return pivot fields `toJSON` calls `serialize`. @param unfilteredOptions @returns {*}
[ "shallow", "-", "won", "t", "return", "relations", "omitPivot", "-", "won", "t", "return", "pivot", "fields" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/models/base/index.js#L597-L618
train
TryGhost/Ghost
core/server/models/base/index.js
permittedOptions
function permittedOptions(methodName) { const baseOptions = ['context', 'withRelated']; const extraOptions = ['transacting', 'importing', 'forUpdate', 'migrating']; switch (methodName) { case 'toJSON': return baseOptions.concat('shallow', 'columns', 'previous'); case 'destroy': return baseOptions.concat(extraOptions, ['id', 'destroyBy', 'require']); case 'edit': return baseOptions.concat(extraOptions, ['id', 'require']); case 'findOne': return baseOptions.concat(extraOptions, ['columns', 'require']); case 'findAll': return baseOptions.concat(extraOptions, ['columns']); case 'findPage': return baseOptions.concat(extraOptions, ['filter', 'order', 'page', 'limit', 'columns']); default: return baseOptions.concat(extraOptions); } }
javascript
function permittedOptions(methodName) { const baseOptions = ['context', 'withRelated']; const extraOptions = ['transacting', 'importing', 'forUpdate', 'migrating']; switch (methodName) { case 'toJSON': return baseOptions.concat('shallow', 'columns', 'previous'); case 'destroy': return baseOptions.concat(extraOptions, ['id', 'destroyBy', 'require']); case 'edit': return baseOptions.concat(extraOptions, ['id', 'require']); case 'findOne': return baseOptions.concat(extraOptions, ['columns', 'require']); case 'findAll': return baseOptions.concat(extraOptions, ['columns']); case 'findPage': return baseOptions.concat(extraOptions, ['filter', 'order', 'page', 'limit', 'columns']); default: return baseOptions.concat(extraOptions); } }
[ "function", "permittedOptions", "(", "methodName", ")", "{", "const", "baseOptions", "=", "[", "'context'", ",", "'withRelated'", "]", ";", "const", "extraOptions", "=", "[", "'transacting'", ",", "'importing'", ",", "'forUpdate'", ",", "'migrating'", "]", ";", "switch", "(", "methodName", ")", "{", "case", "'toJSON'", ":", "return", "baseOptions", ".", "concat", "(", "'shallow'", ",", "'columns'", ",", "'previous'", ")", ";", "case", "'destroy'", ":", "return", "baseOptions", ".", "concat", "(", "extraOptions", ",", "[", "'id'", ",", "'destroyBy'", ",", "'require'", "]", ")", ";", "case", "'edit'", ":", "return", "baseOptions", ".", "concat", "(", "extraOptions", ",", "[", "'id'", ",", "'require'", "]", ")", ";", "case", "'findOne'", ":", "return", "baseOptions", ".", "concat", "(", "extraOptions", ",", "[", "'columns'", ",", "'require'", "]", ")", ";", "case", "'findAll'", ":", "return", "baseOptions", ".", "concat", "(", "extraOptions", ",", "[", "'columns'", "]", ")", ";", "case", "'findPage'", ":", "return", "baseOptions", ".", "concat", "(", "extraOptions", ",", "[", "'filter'", ",", "'order'", ",", "'page'", ",", "'limit'", ",", "'columns'", "]", ")", ";", "default", ":", "return", "baseOptions", ".", "concat", "(", "extraOptions", ")", ";", "}", "}" ]
Returns an array of keys permitted in every method's `options` hash. Can be overridden and added to by a model's `permittedOptions` method. importing: is used when import a JSON file or when migrating the database @return {Object} Keys allowed in the `options` hash of every model's method.
[ "Returns", "an", "array", "of", "keys", "permitted", "in", "every", "method", "s", "options", "hash", ".", "Can", "be", "overridden", "and", "added", "to", "by", "a", "model", "s", "permittedOptions", "method", "." ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/models/base/index.js#L677-L697
train
TryGhost/Ghost
core/server/models/base/index.js
sanitizeData
function sanitizeData(data) { var tableName = _.result(this.prototype, 'tableName'), date; _.each(data, (value, property) => { if (value !== null && schema.tables[tableName].hasOwnProperty(property) && schema.tables[tableName][property].type === 'dateTime' && typeof value === 'string' ) { date = new Date(value); // CASE: client sends `0000-00-00 00:00:00` if (isNaN(date)) { throw new common.errors.ValidationError({ message: common.i18n.t('errors.models.base.invalidDate', {key: property}), code: 'DATE_INVALID' }); } data[property] = moment(value).toDate(); } if (this.prototype.relationships && this.prototype.relationships.indexOf(property) !== -1) { _.each(data[property], (relation, indexInArr) => { _.each(relation, (value, relationProperty) => { if (value !== null && schema.tables[this.prototype.relationshipBelongsTo[property]].hasOwnProperty(relationProperty) && schema.tables[this.prototype.relationshipBelongsTo[property]][relationProperty].type === 'dateTime' && typeof value === 'string' ) { date = new Date(value); // CASE: client sends `0000-00-00 00:00:00` if (isNaN(date)) { throw new common.errors.ValidationError({ message: common.i18n.t('errors.models.base.invalidDate', {key: relationProperty}), code: 'DATE_INVALID' }); } data[property][indexInArr][relationProperty] = moment(value).toDate(); } }); }); } }); return data; }
javascript
function sanitizeData(data) { var tableName = _.result(this.prototype, 'tableName'), date; _.each(data, (value, property) => { if (value !== null && schema.tables[tableName].hasOwnProperty(property) && schema.tables[tableName][property].type === 'dateTime' && typeof value === 'string' ) { date = new Date(value); // CASE: client sends `0000-00-00 00:00:00` if (isNaN(date)) { throw new common.errors.ValidationError({ message: common.i18n.t('errors.models.base.invalidDate', {key: property}), code: 'DATE_INVALID' }); } data[property] = moment(value).toDate(); } if (this.prototype.relationships && this.prototype.relationships.indexOf(property) !== -1) { _.each(data[property], (relation, indexInArr) => { _.each(relation, (value, relationProperty) => { if (value !== null && schema.tables[this.prototype.relationshipBelongsTo[property]].hasOwnProperty(relationProperty) && schema.tables[this.prototype.relationshipBelongsTo[property]][relationProperty].type === 'dateTime' && typeof value === 'string' ) { date = new Date(value); // CASE: client sends `0000-00-00 00:00:00` if (isNaN(date)) { throw new common.errors.ValidationError({ message: common.i18n.t('errors.models.base.invalidDate', {key: relationProperty}), code: 'DATE_INVALID' }); } data[property][indexInArr][relationProperty] = moment(value).toDate(); } }); }); } }); return data; }
[ "function", "sanitizeData", "(", "data", ")", "{", "var", "tableName", "=", "_", ".", "result", "(", "this", ".", "prototype", ",", "'tableName'", ")", ",", "date", ";", "_", ".", "each", "(", "data", ",", "(", "value", ",", "property", ")", "=>", "{", "if", "(", "value", "!==", "null", "&&", "schema", ".", "tables", "[", "tableName", "]", ".", "hasOwnProperty", "(", "property", ")", "&&", "schema", ".", "tables", "[", "tableName", "]", "[", "property", "]", ".", "type", "===", "'dateTime'", "&&", "typeof", "value", "===", "'string'", ")", "{", "date", "=", "new", "Date", "(", "value", ")", ";", "if", "(", "isNaN", "(", "date", ")", ")", "{", "throw", "new", "common", ".", "errors", ".", "ValidationError", "(", "{", "message", ":", "common", ".", "i18n", ".", "t", "(", "'errors.models.base.invalidDate'", ",", "{", "key", ":", "property", "}", ")", ",", "code", ":", "'DATE_INVALID'", "}", ")", ";", "}", "data", "[", "property", "]", "=", "moment", "(", "value", ")", ".", "toDate", "(", ")", ";", "}", "if", "(", "this", ".", "prototype", ".", "relationships", "&&", "this", ".", "prototype", ".", "relationships", ".", "indexOf", "(", "property", ")", "!==", "-", "1", ")", "{", "_", ".", "each", "(", "data", "[", "property", "]", ",", "(", "relation", ",", "indexInArr", ")", "=>", "{", "_", ".", "each", "(", "relation", ",", "(", "value", ",", "relationProperty", ")", "=>", "{", "if", "(", "value", "!==", "null", "&&", "schema", ".", "tables", "[", "this", ".", "prototype", ".", "relationshipBelongsTo", "[", "property", "]", "]", ".", "hasOwnProperty", "(", "relationProperty", ")", "&&", "schema", ".", "tables", "[", "this", ".", "prototype", ".", "relationshipBelongsTo", "[", "property", "]", "]", "[", "relationProperty", "]", ".", "type", "===", "'dateTime'", "&&", "typeof", "value", "===", "'string'", ")", "{", "date", "=", "new", "Date", "(", "value", ")", ";", "if", "(", "isNaN", "(", "date", ")", ")", "{", "throw", "new", "common", ".", "errors", ".", "ValidationError", "(", "{", "message", ":", "common", ".", "i18n", ".", "t", "(", "'errors.models.base.invalidDate'", ",", "{", "key", ":", "relationProperty", "}", ")", ",", "code", ":", "'DATE_INVALID'", "}", ")", ";", "}", "data", "[", "property", "]", "[", "indexInArr", "]", "[", "relationProperty", "]", "=", "moment", "(", "value", ")", ".", "toDate", "(", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}", "}", ")", ";", "return", "data", ";", "}" ]
`sanitizeData` ensures that client data is in the correct format for further operations. Dates: - client dates are sent as ISO 8601 format (moment(..).format()) - server dates are in JS Date format >> when bookshelf fetches data from the database, all dates are in JS Dates >> see `parse` - Bookshelf updates the model with the new client data via the `set` function - Bookshelf uses a simple `isEqual` function from lodash to detect real changes - .previous(attr) and .get(attr) returns false obviously - internally we use our `hasDateChanged` if we have to compare previous dates - but Bookshelf is not in our control for this case @IMPORTANT Before the new client data get's inserted again, the dates get's re-transformed into proper strings, see `format`. @IMPORTANT Sanitize relations.
[ "sanitizeData", "ensures", "that", "client", "data", "is", "in", "the", "correct", "format", "for", "further", "operations", "." ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/models/base/index.js#L735-L783
train
TryGhost/Ghost
core/server/models/base/index.js
filterByVisibility
function filterByVisibility(items, visibility, explicit, fn) { var memo = _.isArray(items) ? [] : {}; if (_.includes(visibility, 'all')) { return fn ? _.map(items, fn) : items; } // We don't want to change the structure of what is returned return _.reduce(items, function (items, item, key) { if (!item.visibility && !explicit || _.includes(visibility, item.visibility)) { var newItem = fn ? fn(item) : item; if (_.isArray(items)) { memo.push(newItem); } else { memo[key] = newItem; } } return memo; }, memo); }
javascript
function filterByVisibility(items, visibility, explicit, fn) { var memo = _.isArray(items) ? [] : {}; if (_.includes(visibility, 'all')) { return fn ? _.map(items, fn) : items; } // We don't want to change the structure of what is returned return _.reduce(items, function (items, item, key) { if (!item.visibility && !explicit || _.includes(visibility, item.visibility)) { var newItem = fn ? fn(item) : item; if (_.isArray(items)) { memo.push(newItem); } else { memo[key] = newItem; } } return memo; }, memo); }
[ "function", "filterByVisibility", "(", "items", ",", "visibility", ",", "explicit", ",", "fn", ")", "{", "var", "memo", "=", "_", ".", "isArray", "(", "items", ")", "?", "[", "]", ":", "{", "}", ";", "if", "(", "_", ".", "includes", "(", "visibility", ",", "'all'", ")", ")", "{", "return", "fn", "?", "_", ".", "map", "(", "items", ",", "fn", ")", ":", "items", ";", "}", "return", "_", ".", "reduce", "(", "items", ",", "function", "(", "items", ",", "item", ",", "key", ")", "{", "if", "(", "!", "item", ".", "visibility", "&&", "!", "explicit", "||", "_", ".", "includes", "(", "visibility", ",", "item", ".", "visibility", ")", ")", "{", "var", "newItem", "=", "fn", "?", "fn", "(", "item", ")", ":", "item", ";", "if", "(", "_", ".", "isArray", "(", "items", ")", ")", "{", "memo", ".", "push", "(", "newItem", ")", ";", "}", "else", "{", "memo", "[", "key", "]", "=", "newItem", ";", "}", "}", "return", "memo", ";", "}", ",", "memo", ")", ";", "}" ]
All models which have a visibility property, can use this static helper function. Filter models by visibility. @param {Array|Object} items @param {Array} visibility @param {Boolean} [explicit] @param {Function} [fn] @returns {Array|Object} filtered items
[ "All", "models", "which", "have", "a", "visibility", "property", "can", "use", "this", "static", "helper", "function", ".", "Filter", "models", "by", "visibility", "." ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/models/base/index.js#L1168-L1187
train
ReactiveX/rxjs
docs_app/src/app/search/search-worker.js
handleMessage
function handleMessage(message) { var type = message.data.type; var id = message.data.id; var payload = message.data.payload; switch(type) { case 'load-index': makeRequest(SEARCH_TERMS_URL, function(searchInfo) { index = createIndex(loadIndex(searchInfo)); self.postMessage({type: type, id: id, payload: true}); }); break; case 'query-index': self.postMessage({type: type, id: id, payload: {query: payload, results: queryIndex(payload)}}); break; default: self.postMessage({type: type, id: id, payload: {error: 'invalid message type'}}) } }
javascript
function handleMessage(message) { var type = message.data.type; var id = message.data.id; var payload = message.data.payload; switch(type) { case 'load-index': makeRequest(SEARCH_TERMS_URL, function(searchInfo) { index = createIndex(loadIndex(searchInfo)); self.postMessage({type: type, id: id, payload: true}); }); break; case 'query-index': self.postMessage({type: type, id: id, payload: {query: payload, results: queryIndex(payload)}}); break; default: self.postMessage({type: type, id: id, payload: {error: 'invalid message type'}}) } }
[ "function", "handleMessage", "(", "message", ")", "{", "var", "type", "=", "message", ".", "data", ".", "type", ";", "var", "id", "=", "message", ".", "data", ".", "id", ";", "var", "payload", "=", "message", ".", "data", ".", "payload", ";", "switch", "(", "type", ")", "{", "case", "'load-index'", ":", "makeRequest", "(", "SEARCH_TERMS_URL", ",", "function", "(", "searchInfo", ")", "{", "index", "=", "createIndex", "(", "loadIndex", "(", "searchInfo", ")", ")", ";", "self", ".", "postMessage", "(", "{", "type", ":", "type", ",", "id", ":", "id", ",", "payload", ":", "true", "}", ")", ";", "}", ")", ";", "break", ";", "case", "'query-index'", ":", "self", ".", "postMessage", "(", "{", "type", ":", "type", ",", "id", ":", "id", ",", "payload", ":", "{", "query", ":", "payload", ",", "results", ":", "queryIndex", "(", "payload", ")", "}", "}", ")", ";", "break", ";", "default", ":", "self", ".", "postMessage", "(", "{", "type", ":", "type", ",", "id", ":", "id", ",", "payload", ":", "{", "error", ":", "'invalid message type'", "}", "}", ")", "}", "}" ]
The worker receives a message to load the index and to query the index
[ "The", "worker", "receives", "a", "message", "to", "load", "the", "index", "and", "to", "query", "the", "index" ]
1037a1d1e6b80c7218e7ffdf8c0d96a612653a4f
https://github.com/ReactiveX/rxjs/blob/1037a1d1e6b80c7218e7ffdf8c0d96a612653a4f/docs_app/src/app/search/search-worker.js#L42-L59
train
ReactiveX/rxjs
docs_app/src/app/search/search-worker.js
makeRequest
function makeRequest(url, callback) { // The JSON file that is loaded should be an array of PageInfo: var searchDataRequest = new XMLHttpRequest(); searchDataRequest.onload = function() { callback(JSON.parse(this.responseText)); }; searchDataRequest.open('GET', url); searchDataRequest.send(); }
javascript
function makeRequest(url, callback) { // The JSON file that is loaded should be an array of PageInfo: var searchDataRequest = new XMLHttpRequest(); searchDataRequest.onload = function() { callback(JSON.parse(this.responseText)); }; searchDataRequest.open('GET', url); searchDataRequest.send(); }
[ "function", "makeRequest", "(", "url", ",", "callback", ")", "{", "var", "searchDataRequest", "=", "new", "XMLHttpRequest", "(", ")", ";", "searchDataRequest", ".", "onload", "=", "function", "(", ")", "{", "callback", "(", "JSON", ".", "parse", "(", "this", ".", "responseText", ")", ")", ";", "}", ";", "searchDataRequest", ".", "open", "(", "'GET'", ",", "url", ")", ";", "searchDataRequest", ".", "send", "(", ")", ";", "}" ]
Use XHR to make a request to the server
[ "Use", "XHR", "to", "make", "a", "request", "to", "the", "server" ]
1037a1d1e6b80c7218e7ffdf8c0d96a612653a4f
https://github.com/ReactiveX/rxjs/blob/1037a1d1e6b80c7218e7ffdf8c0d96a612653a4f/docs_app/src/app/search/search-worker.js#L62-L71
train
ReactiveX/rxjs
docs_app/src/app/search/search-worker.js
loadIndex
function loadIndex(searchInfo /*: SearchInfo */) { return function(index) { // Store the pages data to be used in mapping query results back to pages // Add search terms from each page to the search index searchInfo.forEach(function(page /*: PageInfo */) { index.add(page); pages[page.path] = page; }); }; }
javascript
function loadIndex(searchInfo /*: SearchInfo */) { return function(index) { // Store the pages data to be used in mapping query results back to pages // Add search terms from each page to the search index searchInfo.forEach(function(page /*: PageInfo */) { index.add(page); pages[page.path] = page; }); }; }
[ "function", "loadIndex", "(", "searchInfo", ")", "{", "return", "function", "(", "index", ")", "{", "searchInfo", ".", "forEach", "(", "function", "(", "page", ")", "{", "index", ".", "add", "(", "page", ")", ";", "pages", "[", "page", ".", "path", "]", "=", "page", ";", "}", ")", ";", "}", ";", "}" ]
Create the search index from the searchInfo which contains the information about each page to be indexed
[ "Create", "the", "search", "index", "from", "the", "searchInfo", "which", "contains", "the", "information", "about", "each", "page", "to", "be", "indexed" ]
1037a1d1e6b80c7218e7ffdf8c0d96a612653a4f
https://github.com/ReactiveX/rxjs/blob/1037a1d1e6b80c7218e7ffdf8c0d96a612653a4f/docs_app/src/app/search/search-worker.js#L75-L84
train
ReactiveX/rxjs
.make-helpers.js
createImportTargets
function createImportTargets(importTargets, targetName, targetDirectory) { const importMap = {}; for (const x in importTargets) { importMap['rxjs/' + x] = ('rxjs-compat/' + targetName + importTargets[x]).replace(/\.js$/, ''); } const outputData = ` "use strict" var path = require('path'); var dir = path.resolve(__dirname); module.exports = function() { return ${JSON.stringify(importMap, null, 4)}; } ` fs.outputFileSync(targetDirectory + 'path-mapping.js', outputData); }
javascript
function createImportTargets(importTargets, targetName, targetDirectory) { const importMap = {}; for (const x in importTargets) { importMap['rxjs/' + x] = ('rxjs-compat/' + targetName + importTargets[x]).replace(/\.js$/, ''); } const outputData = ` "use strict" var path = require('path'); var dir = path.resolve(__dirname); module.exports = function() { return ${JSON.stringify(importMap, null, 4)}; } ` fs.outputFileSync(targetDirectory + 'path-mapping.js', outputData); }
[ "function", "createImportTargets", "(", "importTargets", ",", "targetName", ",", "targetDirectory", ")", "{", "const", "importMap", "=", "{", "}", ";", "for", "(", "const", "x", "in", "importTargets", ")", "{", "importMap", "[", "'rxjs/'", "+", "x", "]", "=", "(", "'rxjs-compat/'", "+", "targetName", "+", "importTargets", "[", "x", "]", ")", ".", "replace", "(", "/", "\\.js$", "/", ",", "''", ")", ";", "}", "const", "outputData", "=", "`", "${", "JSON", ".", "stringify", "(", "importMap", ",", "null", ",", "4", ")", "}", "`", "fs", ".", "outputFileSync", "(", "targetDirectory", "+", "'path-mapping.js'", ",", "outputData", ")", ";", "}" ]
Create a file that exports the importTargets object
[ "Create", "a", "file", "that", "exports", "the", "importTargets", "object" ]
1037a1d1e6b80c7218e7ffdf8c0d96a612653a4f
https://github.com/ReactiveX/rxjs/blob/1037a1d1e6b80c7218e7ffdf8c0d96a612653a4f/.make-helpers.js#L40-L59
train
jhipster/generator-jhipster
generators/aws-containers/lib/utils.js
spinner
function spinner(promise, text = 'loading', spinnerIcon = 'monkey') { const spinner = ora({ spinner: spinnerIcon, text }).start(); return new Promise((resolve, reject) => { promise .then(resolved => { spinner.stop(); resolve(resolved); }) .catch(err => { spinner.stop(); reject(err); }); }); }
javascript
function spinner(promise, text = 'loading', spinnerIcon = 'monkey') { const spinner = ora({ spinner: spinnerIcon, text }).start(); return new Promise((resolve, reject) => { promise .then(resolved => { spinner.stop(); resolve(resolved); }) .catch(err => { spinner.stop(); reject(err); }); }); }
[ "function", "spinner", "(", "promise", ",", "text", "=", "'loading'", ",", "spinnerIcon", "=", "'monkey'", ")", "{", "const", "spinner", "=", "ora", "(", "{", "spinner", ":", "spinnerIcon", ",", "text", "}", ")", ".", "start", "(", ")", ";", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "promise", ".", "then", "(", "resolved", "=>", "{", "spinner", ".", "stop", "(", ")", ";", "resolve", "(", "resolved", ")", ";", "}", ")", ".", "catch", "(", "err", "=>", "{", "spinner", ".", "stop", "(", ")", ";", "reject", "(", "err", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
eslint-disable-line Wraps the promise in a CLI spinner @param promise @param text @param spinnerIcon
[ "eslint", "-", "disable", "-", "line", "Wraps", "the", "promise", "in", "a", "CLI", "spinner" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/aws-containers/lib/utils.js#L28-L41
train
jhipster/generator-jhipster
generators/aws-containers/prompts.js
askTypeOfApplication
function askTypeOfApplication() { if (this.abort) return null; const done = this.async(); const prompts = [ { type: 'list', name: 'applicationType', message: 'Which *type* of application would you like to deploy?', choices: [ { value: 'monolith', name: 'Monolithic application' }, { value: 'microservice', name: 'Microservice application' } ], default: 'monolith' } ]; return this.prompt(prompts).then(props => { const applicationType = props.applicationType; this.deploymentApplicationType = props.applicationType; if (applicationType) { this.log(applicationType); done(); } else { this.abort = true; done(); } }); }
javascript
function askTypeOfApplication() { if (this.abort) return null; const done = this.async(); const prompts = [ { type: 'list', name: 'applicationType', message: 'Which *type* of application would you like to deploy?', choices: [ { value: 'monolith', name: 'Monolithic application' }, { value: 'microservice', name: 'Microservice application' } ], default: 'monolith' } ]; return this.prompt(prompts).then(props => { const applicationType = props.applicationType; this.deploymentApplicationType = props.applicationType; if (applicationType) { this.log(applicationType); done(); } else { this.abort = true; done(); } }); }
[ "function", "askTypeOfApplication", "(", ")", "{", "if", "(", "this", ".", "abort", ")", "return", "null", ";", "const", "done", "=", "this", ".", "async", "(", ")", ";", "const", "prompts", "=", "[", "{", "type", ":", "'list'", ",", "name", ":", "'applicationType'", ",", "message", ":", "'Which *type* of application would you like to deploy?'", ",", "choices", ":", "[", "{", "value", ":", "'monolith'", ",", "name", ":", "'Monolithic application'", "}", ",", "{", "value", ":", "'microservice'", ",", "name", ":", "'Microservice application'", "}", "]", ",", "default", ":", "'monolith'", "}", "]", ";", "return", "this", ".", "prompt", "(", "prompts", ")", ".", "then", "(", "props", "=>", "{", "const", "applicationType", "=", "props", ".", "applicationType", ";", "this", ".", "deploymentApplicationType", "=", "props", ".", "applicationType", ";", "if", "(", "applicationType", ")", "{", "this", ".", "log", "(", "applicationType", ")", ";", "done", "(", ")", ";", "}", "else", "{", "this", ".", "abort", "=", "true", ";", "done", "(", ")", ";", "}", "}", ")", ";", "}" ]
Ask user what type of application is to be created?
[ "Ask", "user", "what", "type", "of", "application", "is", "to", "be", "created?" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/aws-containers/prompts.js#L116-L150
train
jhipster/generator-jhipster
generators/aws-containers/prompts.js
askRegion
function askRegion() { if (this.abort) return null; const done = this.async(); const prompts = [ { type: 'list', name: 'region', message: 'Which region?', choices: regionList, default: this.aws.region ? _.indexOf(regionList, this.aws.region) : this.awsFacts.defaultRegion } ]; return this.prompt(prompts).then(props => { const region = props.region; if (region) { this.aws.region = region; done(); } else { this.abort = true; done(); } }); }
javascript
function askRegion() { if (this.abort) return null; const done = this.async(); const prompts = [ { type: 'list', name: 'region', message: 'Which region?', choices: regionList, default: this.aws.region ? _.indexOf(regionList, this.aws.region) : this.awsFacts.defaultRegion } ]; return this.prompt(prompts).then(props => { const region = props.region; if (region) { this.aws.region = region; done(); } else { this.abort = true; done(); } }); }
[ "function", "askRegion", "(", ")", "{", "if", "(", "this", ".", "abort", ")", "return", "null", ";", "const", "done", "=", "this", ".", "async", "(", ")", ";", "const", "prompts", "=", "[", "{", "type", ":", "'list'", ",", "name", ":", "'region'", ",", "message", ":", "'Which region?'", ",", "choices", ":", "regionList", ",", "default", ":", "this", ".", "aws", ".", "region", "?", "_", ".", "indexOf", "(", "regionList", ",", "this", ".", "aws", ".", "region", ")", ":", "this", ".", "awsFacts", ".", "defaultRegion", "}", "]", ";", "return", "this", ".", "prompt", "(", "prompts", ")", ".", "then", "(", "props", "=>", "{", "const", "region", "=", "props", ".", "region", ";", "if", "(", "region", ")", "{", "this", ".", "aws", ".", "region", "=", "region", ";", "done", "(", ")", ";", "}", "else", "{", "this", ".", "abort", "=", "true", ";", "done", "(", ")", ";", "}", "}", ")", ";", "}" ]
Ask user what type of Region is to be created?
[ "Ask", "user", "what", "type", "of", "Region", "is", "to", "be", "created?" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/aws-containers/prompts.js#L155-L178
train
jhipster/generator-jhipster
generators/aws-containers/prompts.js
askCloudFormation
function askCloudFormation() { if (this.abort) return null; const done = this.async(); const prompts = [ { type: 'input', name: 'cloudFormationName', message: "Please enter your stack's name. (must be unique within a region)", default: this.aws.cloudFormationName || this.baseName, validate: input => { if (_.isEmpty(input) || !input.match(CLOUDFORMATION_STACK_NAME)) { return 'Stack name must contain letters, digits, or hyphens '; } return true; } } ]; return this.prompt(prompts).then(props => { const cloudFormationName = props.cloudFormationName; if (cloudFormationName) { this.aws.cloudFormationName = cloudFormationName; while (this.aws.cloudFormationName.includes('_')) { this.aws.cloudFormationName = _.replace(this.aws.cloudFormationName, '_', ''); } this.log(`CloudFormation Stack name will be ${this.aws.cloudFormationName}`); done(); } else { this.abort = true; done(); } }); }
javascript
function askCloudFormation() { if (this.abort) return null; const done = this.async(); const prompts = [ { type: 'input', name: 'cloudFormationName', message: "Please enter your stack's name. (must be unique within a region)", default: this.aws.cloudFormationName || this.baseName, validate: input => { if (_.isEmpty(input) || !input.match(CLOUDFORMATION_STACK_NAME)) { return 'Stack name must contain letters, digits, or hyphens '; } return true; } } ]; return this.prompt(prompts).then(props => { const cloudFormationName = props.cloudFormationName; if (cloudFormationName) { this.aws.cloudFormationName = cloudFormationName; while (this.aws.cloudFormationName.includes('_')) { this.aws.cloudFormationName = _.replace(this.aws.cloudFormationName, '_', ''); } this.log(`CloudFormation Stack name will be ${this.aws.cloudFormationName}`); done(); } else { this.abort = true; done(); } }); }
[ "function", "askCloudFormation", "(", ")", "{", "if", "(", "this", ".", "abort", ")", "return", "null", ";", "const", "done", "=", "this", ".", "async", "(", ")", ";", "const", "prompts", "=", "[", "{", "type", ":", "'input'", ",", "name", ":", "'cloudFormationName'", ",", "message", ":", "\"Please enter your stack's name. (must be unique within a region)\"", ",", "default", ":", "this", ".", "aws", ".", "cloudFormationName", "||", "this", ".", "baseName", ",", "validate", ":", "input", "=>", "{", "if", "(", "_", ".", "isEmpty", "(", "input", ")", "||", "!", "input", ".", "match", "(", "CLOUDFORMATION_STACK_NAME", ")", ")", "{", "return", "'Stack name must contain letters, digits, or hyphens '", ";", "}", "return", "true", ";", "}", "}", "]", ";", "return", "this", ".", "prompt", "(", "prompts", ")", ".", "then", "(", "props", "=>", "{", "const", "cloudFormationName", "=", "props", ".", "cloudFormationName", ";", "if", "(", "cloudFormationName", ")", "{", "this", ".", "aws", ".", "cloudFormationName", "=", "cloudFormationName", ";", "while", "(", "this", ".", "aws", ".", "cloudFormationName", ".", "includes", "(", "'_'", ")", ")", "{", "this", ".", "aws", ".", "cloudFormationName", "=", "_", ".", "replace", "(", "this", ".", "aws", ".", "cloudFormationName", ",", "'_'", ",", "''", ")", ";", "}", "this", ".", "log", "(", "`", "${", "this", ".", "aws", ".", "cloudFormationName", "}", "`", ")", ";", "done", "(", ")", ";", "}", "else", "{", "this", ".", "abort", "=", "true", ";", "done", "(", ")", ";", "}", "}", ")", ";", "}" ]
Ask user for CloudFormation name.
[ "Ask", "user", "for", "CloudFormation", "name", "." ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/aws-containers/prompts.js#L183-L215
train
jhipster/generator-jhipster
generators/aws-containers/prompts.js
askPerformances
function askPerformances() { if (this.abort) return null; const done = this.async(); const chainPromises = index => { if (index === this.appConfigs.length) { done(); return null; } const config = this.appConfigs[index]; const awsConfig = this.aws.apps.find(a => a.baseName === config.baseName) || { baseName: config.baseName }; return promptPerformance.call(this, config, awsConfig).then(performance => { awsConfig.performance = performance; awsConfig.fargate = { ...awsConfig.fargate, ...PERF_TO_CONFIG[performance].fargate }; awsConfig.database = { ...awsConfig.database, ...PERF_TO_CONFIG[performance].database }; _.remove(this.aws.apps, a => _.isEqual(a, awsConfig)); this.aws.apps.push(awsConfig); return chainPromises(index + 1); }); }; return chainPromises(0); }
javascript
function askPerformances() { if (this.abort) return null; const done = this.async(); const chainPromises = index => { if (index === this.appConfigs.length) { done(); return null; } const config = this.appConfigs[index]; const awsConfig = this.aws.apps.find(a => a.baseName === config.baseName) || { baseName: config.baseName }; return promptPerformance.call(this, config, awsConfig).then(performance => { awsConfig.performance = performance; awsConfig.fargate = { ...awsConfig.fargate, ...PERF_TO_CONFIG[performance].fargate }; awsConfig.database = { ...awsConfig.database, ...PERF_TO_CONFIG[performance].database }; _.remove(this.aws.apps, a => _.isEqual(a, awsConfig)); this.aws.apps.push(awsConfig); return chainPromises(index + 1); }); }; return chainPromises(0); }
[ "function", "askPerformances", "(", ")", "{", "if", "(", "this", ".", "abort", ")", "return", "null", ";", "const", "done", "=", "this", ".", "async", "(", ")", ";", "const", "chainPromises", "=", "index", "=>", "{", "if", "(", "index", "===", "this", ".", "appConfigs", ".", "length", ")", "{", "done", "(", ")", ";", "return", "null", ";", "}", "const", "config", "=", "this", ".", "appConfigs", "[", "index", "]", ";", "const", "awsConfig", "=", "this", ".", "aws", ".", "apps", ".", "find", "(", "a", "=>", "a", ".", "baseName", "===", "config", ".", "baseName", ")", "||", "{", "baseName", ":", "config", ".", "baseName", "}", ";", "return", "promptPerformance", ".", "call", "(", "this", ",", "config", ",", "awsConfig", ")", ".", "then", "(", "performance", "=>", "{", "awsConfig", ".", "performance", "=", "performance", ";", "awsConfig", ".", "fargate", "=", "{", "...", "awsConfig", ".", "fargate", ",", "...", "PERF_TO_CONFIG", "[", "performance", "]", ".", "fargate", "}", ";", "awsConfig", ".", "database", "=", "{", "...", "awsConfig", ".", "database", ",", "...", "PERF_TO_CONFIG", "[", "performance", "]", ".", "database", "}", ";", "_", ".", "remove", "(", "this", ".", "aws", ".", "apps", ",", "a", "=>", "_", ".", "isEqual", "(", "a", ",", "awsConfig", ")", ")", ";", "this", ".", "aws", ".", "apps", ".", "push", "(", "awsConfig", ")", ";", "return", "chainPromises", "(", "index", "+", "1", ")", ";", "}", ")", ";", "}", ";", "return", "chainPromises", "(", "0", ")", ";", "}" ]
As user to select AWS performance.
[ "As", "user", "to", "select", "AWS", "performance", "." ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/aws-containers/prompts.js#L220-L243
train
jhipster/generator-jhipster
generators/aws-containers/prompts.js
askScaling
function askScaling() { if (this.abort) return null; const done = this.async(); const chainPromises = index => { if (index === this.appConfigs.length) { done(); return null; } const config = this.appConfigs[index]; const awsConfig = this.aws.apps.find(a => a.baseName === config.baseName) || { baseName: config.baseName }; return promptScaling.call(this, config, awsConfig).then(scaling => { awsConfig.scaling = scaling; awsConfig.fargate = { ...awsConfig.fargate, ...SCALING_TO_CONFIG[scaling].fargate }; awsConfig.database = { ...awsConfig.database, ...SCALING_TO_CONFIG[scaling].database }; _.remove(this.aws.apps, a => _.isEqual(a, awsConfig)); this.aws.apps.push(awsConfig); return chainPromises(index + 1); }); }; return chainPromises(0); }
javascript
function askScaling() { if (this.abort) return null; const done = this.async(); const chainPromises = index => { if (index === this.appConfigs.length) { done(); return null; } const config = this.appConfigs[index]; const awsConfig = this.aws.apps.find(a => a.baseName === config.baseName) || { baseName: config.baseName }; return promptScaling.call(this, config, awsConfig).then(scaling => { awsConfig.scaling = scaling; awsConfig.fargate = { ...awsConfig.fargate, ...SCALING_TO_CONFIG[scaling].fargate }; awsConfig.database = { ...awsConfig.database, ...SCALING_TO_CONFIG[scaling].database }; _.remove(this.aws.apps, a => _.isEqual(a, awsConfig)); this.aws.apps.push(awsConfig); return chainPromises(index + 1); }); }; return chainPromises(0); }
[ "function", "askScaling", "(", ")", "{", "if", "(", "this", ".", "abort", ")", "return", "null", ";", "const", "done", "=", "this", ".", "async", "(", ")", ";", "const", "chainPromises", "=", "index", "=>", "{", "if", "(", "index", "===", "this", ".", "appConfigs", ".", "length", ")", "{", "done", "(", ")", ";", "return", "null", ";", "}", "const", "config", "=", "this", ".", "appConfigs", "[", "index", "]", ";", "const", "awsConfig", "=", "this", ".", "aws", ".", "apps", ".", "find", "(", "a", "=>", "a", ".", "baseName", "===", "config", ".", "baseName", ")", "||", "{", "baseName", ":", "config", ".", "baseName", "}", ";", "return", "promptScaling", ".", "call", "(", "this", ",", "config", ",", "awsConfig", ")", ".", "then", "(", "scaling", "=>", "{", "awsConfig", ".", "scaling", "=", "scaling", ";", "awsConfig", ".", "fargate", "=", "{", "...", "awsConfig", ".", "fargate", ",", "...", "SCALING_TO_CONFIG", "[", "scaling", "]", ".", "fargate", "}", ";", "awsConfig", ".", "database", "=", "{", "...", "awsConfig", ".", "database", ",", "...", "SCALING_TO_CONFIG", "[", "scaling", "]", ".", "database", "}", ";", "_", ".", "remove", "(", "this", ".", "aws", ".", "apps", ",", "a", "=>", "_", ".", "isEqual", "(", "a", ",", "awsConfig", ")", ")", ";", "this", ".", "aws", ".", "apps", ".", "push", "(", "awsConfig", ")", ";", "return", "chainPromises", "(", "index", "+", "1", ")", ";", "}", ")", ";", "}", ";", "return", "chainPromises", "(", "0", ")", ";", "}" ]
Ask about scaling
[ "Ask", "about", "scaling" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/aws-containers/prompts.js#L291-L313
train
jhipster/generator-jhipster
generators/aws-containers/prompts.js
askVPC
function askVPC() { if (this.abort) return null; const done = this.async(); const vpcList = this.awsFacts.availableVpcs.map(vpc => { const friendlyName = _getFriendlyNameFromTag(vpc); return { name: `ID: ${vpc.VpcId} (${friendlyName ? `name: '${friendlyName}', ` : ''}default: ${vpc.IsDefault}, state: ${vpc.State})`, value: vpc.VpcId, short: vpc.VpcId }; }); const prompts = [ { type: 'list', name: 'targetVPC', message: 'Please select your target Virtual Private Network.', choices: vpcList, default: this.aws.vpc.id } ]; return this.prompt(prompts).then(props => { const targetVPC = props.targetVPC; if (targetVPC) { this.aws.vpc.id = targetVPC; this.aws.vpc.cidr = _.find(this.awsFacts.availableVpcs, ['VpcId', targetVPC]).CidrBlock; done(); } else { this.abort = true; done(); } }); }
javascript
function askVPC() { if (this.abort) return null; const done = this.async(); const vpcList = this.awsFacts.availableVpcs.map(vpc => { const friendlyName = _getFriendlyNameFromTag(vpc); return { name: `ID: ${vpc.VpcId} (${friendlyName ? `name: '${friendlyName}', ` : ''}default: ${vpc.IsDefault}, state: ${vpc.State})`, value: vpc.VpcId, short: vpc.VpcId }; }); const prompts = [ { type: 'list', name: 'targetVPC', message: 'Please select your target Virtual Private Network.', choices: vpcList, default: this.aws.vpc.id } ]; return this.prompt(prompts).then(props => { const targetVPC = props.targetVPC; if (targetVPC) { this.aws.vpc.id = targetVPC; this.aws.vpc.cidr = _.find(this.awsFacts.availableVpcs, ['VpcId', targetVPC]).CidrBlock; done(); } else { this.abort = true; done(); } }); }
[ "function", "askVPC", "(", ")", "{", "if", "(", "this", ".", "abort", ")", "return", "null", ";", "const", "done", "=", "this", ".", "async", "(", ")", ";", "const", "vpcList", "=", "this", ".", "awsFacts", ".", "availableVpcs", ".", "map", "(", "vpc", "=>", "{", "const", "friendlyName", "=", "_getFriendlyNameFromTag", "(", "vpc", ")", ";", "return", "{", "name", ":", "`", "${", "vpc", ".", "VpcId", "}", "${", "friendlyName", "?", "`", "${", "friendlyName", "}", "`", ":", "''", "}", "${", "vpc", ".", "IsDefault", "}", "${", "vpc", ".", "State", "}", "`", ",", "value", ":", "vpc", ".", "VpcId", ",", "short", ":", "vpc", ".", "VpcId", "}", ";", "}", ")", ";", "const", "prompts", "=", "[", "{", "type", ":", "'list'", ",", "name", ":", "'targetVPC'", ",", "message", ":", "'Please select your target Virtual Private Network.'", ",", "choices", ":", "vpcList", ",", "default", ":", "this", ".", "aws", ".", "vpc", ".", "id", "}", "]", ";", "return", "this", ".", "prompt", "(", "prompts", ")", ".", "then", "(", "props", "=>", "{", "const", "targetVPC", "=", "props", ".", "targetVPC", ";", "if", "(", "targetVPC", ")", "{", "this", ".", "aws", ".", "vpc", ".", "id", "=", "targetVPC", ";", "this", ".", "aws", ".", "vpc", ".", "cidr", "=", "_", ".", "find", "(", "this", ".", "awsFacts", ".", "availableVpcs", ",", "[", "'VpcId'", ",", "targetVPC", "]", ")", ".", "CidrBlock", ";", "done", "(", ")", ";", "}", "else", "{", "this", ".", "abort", "=", "true", ";", "done", "(", ")", ";", "}", "}", ")", ";", "}" ]
Ask user to select target Virtual Private Network
[ "Ask", "user", "to", "select", "target", "Virtual", "Private", "Network" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/aws-containers/prompts.js#L347-L381
train
jhipster/generator-jhipster
generators/aws-containers/prompts.js
askDeployNow
function askDeployNow() { if (this.abort) return null; const done = this.async(); const prompts = [ { type: 'confirm', name: 'deployNow', message: 'Would you like to deploy now?.', default: true } ]; return this.prompt(prompts).then(props => { this.deployNow = props.deployNow; done(); }); }
javascript
function askDeployNow() { if (this.abort) return null; const done = this.async(); const prompts = [ { type: 'confirm', name: 'deployNow', message: 'Would you like to deploy now?.', default: true } ]; return this.prompt(prompts).then(props => { this.deployNow = props.deployNow; done(); }); }
[ "function", "askDeployNow", "(", ")", "{", "if", "(", "this", ".", "abort", ")", "return", "null", ";", "const", "done", "=", "this", ".", "async", "(", ")", ";", "const", "prompts", "=", "[", "{", "type", ":", "'confirm'", ",", "name", ":", "'deployNow'", ",", "message", ":", "'Would you like to deploy now?.'", ",", "default", ":", "true", "}", "]", ";", "return", "this", ".", "prompt", "(", "prompts", ")", ".", "then", "(", "props", "=>", "{", "this", ".", "deployNow", "=", "props", ".", "deployNow", ";", "done", "(", ")", ";", "}", ")", ";", "}" ]
Ask user if they would like to deploy now?
[ "Ask", "user", "if", "they", "would", "like", "to", "deploy", "now?" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/aws-containers/prompts.js#L495-L511
train
jhipster/generator-jhipster
generators/aws-containers/lib/cloudFormation.js
_doesEventContainsNestedStackId
function _doesEventContainsNestedStackId(stack) { if (stack.ResourceType !== 'AWS::CloudFormation::Stack') { return false; } if (stack.ResourceStatusReason !== 'Resource creation Initiated') { return false; } if (stack.ResourceStatus !== 'CREATE_IN_PROGRESS') { return false; } if (_.isNil(stack.PhysicalResourceId)) { return false; } return _hasLabelNestedStackName(stack.PhysicalResourceId); }
javascript
function _doesEventContainsNestedStackId(stack) { if (stack.ResourceType !== 'AWS::CloudFormation::Stack') { return false; } if (stack.ResourceStatusReason !== 'Resource creation Initiated') { return false; } if (stack.ResourceStatus !== 'CREATE_IN_PROGRESS') { return false; } if (_.isNil(stack.PhysicalResourceId)) { return false; } return _hasLabelNestedStackName(stack.PhysicalResourceId); }
[ "function", "_doesEventContainsNestedStackId", "(", "stack", ")", "{", "if", "(", "stack", ".", "ResourceType", "!==", "'AWS::CloudFormation::Stack'", ")", "{", "return", "false", ";", "}", "if", "(", "stack", ".", "ResourceStatusReason", "!==", "'Resource creation Initiated'", ")", "{", "return", "false", ";", "}", "if", "(", "stack", ".", "ResourceStatus", "!==", "'CREATE_IN_PROGRESS'", ")", "{", "return", "false", ";", "}", "if", "(", "_", ".", "isNil", "(", "stack", ".", "PhysicalResourceId", ")", ")", "{", "return", "false", ";", "}", "return", "_hasLabelNestedStackName", "(", "stack", ".", "PhysicalResourceId", ")", ";", "}" ]
Check if the stack event contains the name a Nested Stack name. @param stack The StackEvent object. @returns {boolean} true if the object contain a Nested Stack name, false otherwise. @private
[ "Check", "if", "the", "stack", "event", "contains", "the", "name", "a", "Nested", "Stack", "name", "." ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/aws-containers/lib/cloudFormation.js#L266-L281
train
jhipster/generator-jhipster
generators/aws-containers/lib/cloudFormation.js
_formatStatus
function _formatStatus(status) { let statusColorFn = chalk.grey; if (_.endsWith(status, 'IN_PROGRESS')) { statusColorFn = chalk.yellow; } else if (_.endsWith(status, 'FAILED') || _.startsWith(status, 'DELETE')) { statusColorFn = chalk.red; } else if (_.endsWith(status, 'COMPLETE')) { statusColorFn = chalk.greenBright; } const sanitizedStatus = _.replace(status, '_', ' '); const paddedStatus = _.padEnd(sanitizedStatus, STACK_EVENT_STATUS_DISPLAY_LENGTH); return statusColorFn(paddedStatus); }
javascript
function _formatStatus(status) { let statusColorFn = chalk.grey; if (_.endsWith(status, 'IN_PROGRESS')) { statusColorFn = chalk.yellow; } else if (_.endsWith(status, 'FAILED') || _.startsWith(status, 'DELETE')) { statusColorFn = chalk.red; } else if (_.endsWith(status, 'COMPLETE')) { statusColorFn = chalk.greenBright; } const sanitizedStatus = _.replace(status, '_', ' '); const paddedStatus = _.padEnd(sanitizedStatus, STACK_EVENT_STATUS_DISPLAY_LENGTH); return statusColorFn(paddedStatus); }
[ "function", "_formatStatus", "(", "status", ")", "{", "let", "statusColorFn", "=", "chalk", ".", "grey", ";", "if", "(", "_", ".", "endsWith", "(", "status", ",", "'IN_PROGRESS'", ")", ")", "{", "statusColorFn", "=", "chalk", ".", "yellow", ";", "}", "else", "if", "(", "_", ".", "endsWith", "(", "status", ",", "'FAILED'", ")", "||", "_", ".", "startsWith", "(", "status", ",", "'DELETE'", ")", ")", "{", "statusColorFn", "=", "chalk", ".", "red", ";", "}", "else", "if", "(", "_", ".", "endsWith", "(", "status", ",", "'COMPLETE'", ")", ")", "{", "statusColorFn", "=", "chalk", ".", "greenBright", ";", "}", "const", "sanitizedStatus", "=", "_", ".", "replace", "(", "status", ",", "'_'", ",", "' '", ")", ";", "const", "paddedStatus", "=", "_", ".", "padEnd", "(", "sanitizedStatus", ",", "STACK_EVENT_STATUS_DISPLAY_LENGTH", ")", ";", "return", "statusColorFn", "(", "paddedStatus", ")", ";", "}" ]
returns a formatted status string ready to be displayed @param status @returns {*} a string @private
[ "returns", "a", "formatted", "status", "string", "ready", "to", "be", "displayed" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/aws-containers/lib/cloudFormation.js#L289-L302
train
jhipster/generator-jhipster
generators/aws-containers/lib/cloudFormation.js
_getStackLogLine
function _getStackLogLine(stack, indentation = 0) { const time = chalk.blue(`${stack.Timestamp.toLocaleTimeString()}`); const spacing = _.repeat('\t', indentation); const status = _formatStatus(stack.ResourceStatus); const stackName = chalk.grey(stack.StackName); const resourceType = chalk.bold(stack.ResourceType); return `${time} ${spacing}${status} ${resourceType}\t${stackName}`; }
javascript
function _getStackLogLine(stack, indentation = 0) { const time = chalk.blue(`${stack.Timestamp.toLocaleTimeString()}`); const spacing = _.repeat('\t', indentation); const status = _formatStatus(stack.ResourceStatus); const stackName = chalk.grey(stack.StackName); const resourceType = chalk.bold(stack.ResourceType); return `${time} ${spacing}${status} ${resourceType}\t${stackName}`; }
[ "function", "_getStackLogLine", "(", "stack", ",", "indentation", "=", "0", ")", "{", "const", "time", "=", "chalk", ".", "blue", "(", "`", "${", "stack", ".", "Timestamp", ".", "toLocaleTimeString", "(", ")", "}", "`", ")", ";", "const", "spacing", "=", "_", ".", "repeat", "(", "'\\t'", ",", "\\t", ")", ";", "indentation", "const", "status", "=", "_formatStatus", "(", "stack", ".", "ResourceStatus", ")", ";", "const", "stackName", "=", "chalk", ".", "grey", "(", "stack", ".", "StackName", ")", ";", "const", "resourceType", "=", "chalk", ".", "bold", "(", "stack", ".", "ResourceType", ")", ";", "}" ]
Generate an enriched string to display a CloudFormation Stack creation event. @param stack Stack event @param indentation level of indentation to display (between the date and the rest of the log) @returns {string} @private
[ "Generate", "an", "enriched", "string", "to", "display", "a", "CloudFormation", "Stack", "creation", "event", "." ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/aws-containers/lib/cloudFormation.js#L311-L319
train
jhipster/generator-jhipster
generators/docker-cli.js
loginToAws
function loginToAws(region, accountId, username, password) { const commandLine = `docker login --username AWS --password ${password} https://${accountId}.dkr.ecr.${region}.amazonaws.com`; return new Promise( (resolve, reject) => command(commandLine, (err, stdout) => { if (err) { reject(err); } resolve(stdout); }), { silent: true } ); }
javascript
function loginToAws(region, accountId, username, password) { const commandLine = `docker login --username AWS --password ${password} https://${accountId}.dkr.ecr.${region}.amazonaws.com`; return new Promise( (resolve, reject) => command(commandLine, (err, stdout) => { if (err) { reject(err); } resolve(stdout); }), { silent: true } ); }
[ "function", "loginToAws", "(", "region", ",", "accountId", ",", "username", ",", "password", ")", "{", "const", "commandLine", "=", "`", "${", "password", "}", "${", "accountId", "}", "${", "region", "}", "`", ";", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "command", "(", "commandLine", ",", "(", "err", ",", "stdout", ")", "=>", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "resolve", "(", "stdout", ")", ";", "}", ")", ",", "{", "silent", ":", "true", "}", ")", ";", "}" ]
Log docker to AWS. @param region @param accountId @param username @param password @returns {Promise}
[ "Log", "docker", "to", "AWS", "." ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/docker-cli.js#L119-L131
train
jhipster/generator-jhipster
generators/docker-cli.js
pushImage
function pushImage(repository) { const commandLine = `docker push ${repository}`; return new Promise((resolve, reject) => command(commandLine, (err, stdout) => { if (err) { reject(err); } resolve(stdout); }) ); }
javascript
function pushImage(repository) { const commandLine = `docker push ${repository}`; return new Promise((resolve, reject) => command(commandLine, (err, stdout) => { if (err) { reject(err); } resolve(stdout); }) ); }
[ "function", "pushImage", "(", "repository", ")", "{", "const", "commandLine", "=", "`", "${", "repository", "}", "`", ";", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "command", "(", "commandLine", ",", "(", "err", ",", "stdout", ")", "=>", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "resolve", "(", "stdout", ")", ";", "}", ")", ")", ";", "}" ]
Pushes the locally constructed Docker image to the supplied respository @param repository tag, for example: 111111111.dkr.ecr.us-east-1.amazonaws.com/sample @returns {Promise<any>}
[ "Pushes", "the", "locally", "constructed", "Docker", "image", "to", "the", "supplied", "respository" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/docker-cli.js#L138-L148
train
jhipster/generator-jhipster
generators/docker-utils.js
checkDocker
function checkDocker() { if (this.abort || this.skipChecks) return; const done = this.async(); shelljs.exec('docker -v', { silent: true }, (code, stdout, stderr) => { if (stderr) { this.log( chalk.red( 'Docker version 1.10.0 or later is not installed on your computer.\n' + ' Read http://docs.docker.com/engine/installation/#installation\n' ) ); this.abort = true; } else { const dockerVersion = stdout.split(' ')[2].replace(/,/g, ''); const dockerVersionMajor = dockerVersion.split('.')[0]; const dockerVersionMinor = dockerVersion.split('.')[1]; if (dockerVersionMajor < 1 || (dockerVersionMajor === 1 && dockerVersionMinor < 10)) { this.log( chalk.red( `${'Docker version 1.10.0 or later is not installed on your computer.\n' + ' Docker version found: '}${dockerVersion}\n` + ' Read http://docs.docker.com/engine/installation/#installation\n' ) ); this.abort = true; } else { this.log.ok('Docker is installed'); } } done(); }); }
javascript
function checkDocker() { if (this.abort || this.skipChecks) return; const done = this.async(); shelljs.exec('docker -v', { silent: true }, (code, stdout, stderr) => { if (stderr) { this.log( chalk.red( 'Docker version 1.10.0 or later is not installed on your computer.\n' + ' Read http://docs.docker.com/engine/installation/#installation\n' ) ); this.abort = true; } else { const dockerVersion = stdout.split(' ')[2].replace(/,/g, ''); const dockerVersionMajor = dockerVersion.split('.')[0]; const dockerVersionMinor = dockerVersion.split('.')[1]; if (dockerVersionMajor < 1 || (dockerVersionMajor === 1 && dockerVersionMinor < 10)) { this.log( chalk.red( `${'Docker version 1.10.0 or later is not installed on your computer.\n' + ' Docker version found: '}${dockerVersion}\n` + ' Read http://docs.docker.com/engine/installation/#installation\n' ) ); this.abort = true; } else { this.log.ok('Docker is installed'); } } done(); }); }
[ "function", "checkDocker", "(", ")", "{", "if", "(", "this", ".", "abort", "||", "this", ".", "skipChecks", ")", "return", ";", "const", "done", "=", "this", ".", "async", "(", ")", ";", "shelljs", ".", "exec", "(", "'docker -v'", ",", "{", "silent", ":", "true", "}", ",", "(", "code", ",", "stdout", ",", "stderr", ")", "=>", "{", "if", "(", "stderr", ")", "{", "this", ".", "log", "(", "chalk", ".", "red", "(", "'Docker version 1.10.0 or later is not installed on your computer.\\n'", "+", "\\n", ")", ")", ";", "' Read http://docs.docker.com/engine/installation/#installation\\n'", "}", "else", "\\n", "this", ".", "abort", "=", "true", ";", "}", ")", ";", "}" ]
Check that Docker exists. @param failOver flag
[ "Check", "that", "Docker", "exists", "." ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/docker-utils.js#L39-L71
train
jhipster/generator-jhipster
generators/docker-utils.js
checkImageExist
function checkImageExist(opts = { cwd: './', appConfig: null }) { if (this.abort) return; let imagePath = ''; this.warning = false; this.warningMessage = 'To generate the missing Docker image(s), please run:\n'; if (opts.appConfig.buildTool === 'maven') { imagePath = this.destinationPath(`${opts.cwd + opts.cwd}/target/docker`); this.dockerBuildCommand = './mvnw -Pprod verify jib:dockerBuild'; } else { imagePath = this.destinationPath(`${opts.cwd + opts.cwd}/build/docker`); this.dockerBuildCommand = './gradlew bootWar -Pprod jibDockerBuild'; } if (shelljs.ls(imagePath).length === 0) { this.warning = true; this.warningMessage += ` ${chalk.cyan(this.dockerBuildCommand)} in ${this.destinationPath(this.directoryPath + opts.cwd)}\n`; } }
javascript
function checkImageExist(opts = { cwd: './', appConfig: null }) { if (this.abort) return; let imagePath = ''; this.warning = false; this.warningMessage = 'To generate the missing Docker image(s), please run:\n'; if (opts.appConfig.buildTool === 'maven') { imagePath = this.destinationPath(`${opts.cwd + opts.cwd}/target/docker`); this.dockerBuildCommand = './mvnw -Pprod verify jib:dockerBuild'; } else { imagePath = this.destinationPath(`${opts.cwd + opts.cwd}/build/docker`); this.dockerBuildCommand = './gradlew bootWar -Pprod jibDockerBuild'; } if (shelljs.ls(imagePath).length === 0) { this.warning = true; this.warningMessage += ` ${chalk.cyan(this.dockerBuildCommand)} in ${this.destinationPath(this.directoryPath + opts.cwd)}\n`; } }
[ "function", "checkImageExist", "(", "opts", "=", "{", "cwd", ":", "'./'", ",", "appConfig", ":", "null", "}", ")", "{", "if", "(", "this", ".", "abort", ")", "return", ";", "let", "imagePath", "=", "''", ";", "this", ".", "warning", "=", "false", ";", "this", ".", "warningMessage", "=", "'To generate the missing Docker image(s), please run:\\n'", ";", "\\n", "if", "(", "opts", ".", "appConfig", ".", "buildTool", "===", "'maven'", ")", "{", "imagePath", "=", "this", ".", "destinationPath", "(", "`", "${", "opts", ".", "cwd", "+", "opts", ".", "cwd", "}", "`", ")", ";", "this", ".", "dockerBuildCommand", "=", "'./mvnw -Pprod verify jib:dockerBuild'", ";", "}", "else", "{", "imagePath", "=", "this", ".", "destinationPath", "(", "`", "${", "opts", ".", "cwd", "+", "opts", ".", "cwd", "}", "`", ")", ";", "this", ".", "dockerBuildCommand", "=", "'./gradlew bootWar -Pprod jibDockerBuild'", ";", "}", "}" ]
Check that a Docker image exists in a JHipster app. @param opts Options to pass. @property pwd JHipster app directory. default is './' @property appConfig Configuration for the current application
[ "Check", "that", "a", "Docker", "image", "exists", "in", "a", "JHipster", "app", "." ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/docker-utils.js#L80-L98
train
jhipster/generator-jhipster
cli/import-jdl.js
importJDL
function importJDL() { logger.info('The JDL is being parsed.'); const jdlImporter = new jhiCore.JDLImporter(this.jdlFiles, { databaseType: this.prodDatabaseType, applicationType: this.applicationType, applicationName: this.baseName, generatorVersion: packagejs.version, forceNoFiltering: this.options.force }); let importState = { exportedEntities: [], exportedApplications: [], exportedDeployments: [] }; try { importState = jdlImporter.import(); logger.debug(`importState exportedEntities: ${importState.exportedEntities.length}`); logger.debug(`importState exportedApplications: ${importState.exportedApplications.length}`); logger.debug(`importState exportedDeployments: ${importState.exportedDeployments.length}`); updateDeploymentState(importState); if (importState.exportedEntities.length > 0) { const entityNames = _.uniq(importState.exportedEntities.map(exportedEntity => exportedEntity.name)).join(', '); logger.info(`Found entities: ${chalk.yellow(entityNames)}.`); } else { logger.info(chalk.yellow('No change in entity configurations, no entities were updated.')); } logger.info('The JDL has been successfully parsed'); } catch (error) { logger.debug('Error:', error); if (error) { const errorName = `${error.name}:` || ''; const errorMessage = error.message || ''; logger.log(chalk.red(`${errorName} ${errorMessage}`)); } logger.error(`Error while parsing applications and entities from the JDL ${error}`, error); } return importState; }
javascript
function importJDL() { logger.info('The JDL is being parsed.'); const jdlImporter = new jhiCore.JDLImporter(this.jdlFiles, { databaseType: this.prodDatabaseType, applicationType: this.applicationType, applicationName: this.baseName, generatorVersion: packagejs.version, forceNoFiltering: this.options.force }); let importState = { exportedEntities: [], exportedApplications: [], exportedDeployments: [] }; try { importState = jdlImporter.import(); logger.debug(`importState exportedEntities: ${importState.exportedEntities.length}`); logger.debug(`importState exportedApplications: ${importState.exportedApplications.length}`); logger.debug(`importState exportedDeployments: ${importState.exportedDeployments.length}`); updateDeploymentState(importState); if (importState.exportedEntities.length > 0) { const entityNames = _.uniq(importState.exportedEntities.map(exportedEntity => exportedEntity.name)).join(', '); logger.info(`Found entities: ${chalk.yellow(entityNames)}.`); } else { logger.info(chalk.yellow('No change in entity configurations, no entities were updated.')); } logger.info('The JDL has been successfully parsed'); } catch (error) { logger.debug('Error:', error); if (error) { const errorName = `${error.name}:` || ''; const errorMessage = error.message || ''; logger.log(chalk.red(`${errorName} ${errorMessage}`)); } logger.error(`Error while parsing applications and entities from the JDL ${error}`, error); } return importState; }
[ "function", "importJDL", "(", ")", "{", "logger", ".", "info", "(", "'The JDL is being parsed.'", ")", ";", "const", "jdlImporter", "=", "new", "jhiCore", ".", "JDLImporter", "(", "this", ".", "jdlFiles", ",", "{", "databaseType", ":", "this", ".", "prodDatabaseType", ",", "applicationType", ":", "this", ".", "applicationType", ",", "applicationName", ":", "this", ".", "baseName", ",", "generatorVersion", ":", "packagejs", ".", "version", ",", "forceNoFiltering", ":", "this", ".", "options", ".", "force", "}", ")", ";", "let", "importState", "=", "{", "exportedEntities", ":", "[", "]", ",", "exportedApplications", ":", "[", "]", ",", "exportedDeployments", ":", "[", "]", "}", ";", "try", "{", "importState", "=", "jdlImporter", ".", "import", "(", ")", ";", "logger", ".", "debug", "(", "`", "${", "importState", ".", "exportedEntities", ".", "length", "}", "`", ")", ";", "logger", ".", "debug", "(", "`", "${", "importState", ".", "exportedApplications", ".", "length", "}", "`", ")", ";", "logger", ".", "debug", "(", "`", "${", "importState", ".", "exportedDeployments", ".", "length", "}", "`", ")", ";", "updateDeploymentState", "(", "importState", ")", ";", "if", "(", "importState", ".", "exportedEntities", ".", "length", ">", "0", ")", "{", "const", "entityNames", "=", "_", ".", "uniq", "(", "importState", ".", "exportedEntities", ".", "map", "(", "exportedEntity", "=>", "exportedEntity", ".", "name", ")", ")", ".", "join", "(", "', '", ")", ";", "logger", ".", "info", "(", "`", "${", "chalk", ".", "yellow", "(", "entityNames", ")", "}", "`", ")", ";", "}", "else", "{", "logger", ".", "info", "(", "chalk", ".", "yellow", "(", "'No change in entity configurations, no entities were updated.'", ")", ")", ";", "}", "logger", ".", "info", "(", "'The JDL has been successfully parsed'", ")", ";", "}", "catch", "(", "error", ")", "{", "logger", ".", "debug", "(", "'Error:'", ",", "error", ")", ";", "if", "(", "error", ")", "{", "const", "errorName", "=", "`", "${", "error", ".", "name", "}", "`", "||", "''", ";", "const", "errorMessage", "=", "error", ".", "message", "||", "''", ";", "logger", ".", "log", "(", "chalk", ".", "red", "(", "`", "${", "errorName", "}", "${", "errorMessage", "}", "`", ")", ")", ";", "}", "logger", ".", "error", "(", "`", "${", "error", "}", "`", ",", "error", ")", ";", "}", "return", "importState", ";", "}" ]
Imports the Applications and Entities defined in JDL The app .yo-rc.json files and entity json files are written to disk
[ "Imports", "the", "Applications", "and", "Entities", "defined", "in", "JDL", "The", "app", ".", "yo", "-", "rc", ".", "json", "files", "and", "entity", "json", "files", "are", "written", "to", "disk" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/cli/import-jdl.js#L61-L98
train
jhipster/generator-jhipster
generators/cleanup.js
cleanupOldFiles
function cleanupOldFiles(generator) { if (generator.isJhipsterVersionLessThan('3.2.0')) { // removeFile and removeFolder methods should be called here for files and folders to cleanup generator.removeFile(`${ANGULAR_DIR}components/form/uib-pager.config.js`); generator.removeFile(`${ANGULAR_DIR}components/form/uib-pagination.config.js`); } if (generator.isJhipsterVersionLessThan('5.0.0')) { generator.removeFile(`${ANGULAR_DIR}/app.route.ts`); generator.removeFile(`${ANGULAR_DIR}shared/auth/account.service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/auth/auth-jwt.service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/auth/auth-session.service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/auth/csrf.service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/auth/state-storage.service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/auth/user-route-access-service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/language/language.constants.ts`); generator.removeFile(`${ANGULAR_DIR}shared/language/language.helper.ts`); generator.removeFile(`${ANGULAR_DIR}shared/login/login-modal.service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/login/login.service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/model/base-entity.ts`); generator.removeFile(`${ANGULAR_DIR}shared/model/request-util.ts`); generator.removeFile(`${ANGULAR_DIR}shared/user/account.model.ts`); generator.removeFile(`${ANGULAR_DIR}shared/user/user.model.ts`); generator.removeFile(`${ANGULAR_DIR}shared/user/user.service.ts`); generator.removeFile(`${ANGULAR_DIR}admin/user-management/user-management-dialog.component.ts`); generator.removeFile(`${ANGULAR_DIR}admin/user-management/user-modal.service.ts`); generator.removeFile(`${ANGULAR_DIR}admin/user-management/user-modal.service.ts`); generator.removeFile(`${CLIENT_TEST_SRC_DIR}spec/app/shared/user/user.service.spec.ts`); generator.removeFile(`${CLIENT_TEST_SRC_DIR}spec/app/admin/user-management/user-management-dialog.component.spec.ts`); generator.removeFile(`${CLIENT_TEST_SRC_DIR}spec/entry.ts`); generator.removeFile(`${CLIENT_TEST_SRC_DIR}karma.conf.js`); } if (generator.isJhipsterVersionLessThan('5.8.0')) { generator.removeFile(`${ANGULAR_DIR}admin/metrics/metrics-modal.component.html`); generator.removeFile(`${ANGULAR_DIR}admin/metrics/metrics-modal.component.ts`); generator.removeFile(`${CLIENT_TEST_SRC_DIR}spec/app/admin/metrics/metrics-modal.component.spec.ts`); } }
javascript
function cleanupOldFiles(generator) { if (generator.isJhipsterVersionLessThan('3.2.0')) { // removeFile and removeFolder methods should be called here for files and folders to cleanup generator.removeFile(`${ANGULAR_DIR}components/form/uib-pager.config.js`); generator.removeFile(`${ANGULAR_DIR}components/form/uib-pagination.config.js`); } if (generator.isJhipsterVersionLessThan('5.0.0')) { generator.removeFile(`${ANGULAR_DIR}/app.route.ts`); generator.removeFile(`${ANGULAR_DIR}shared/auth/account.service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/auth/auth-jwt.service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/auth/auth-session.service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/auth/csrf.service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/auth/state-storage.service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/auth/user-route-access-service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/language/language.constants.ts`); generator.removeFile(`${ANGULAR_DIR}shared/language/language.helper.ts`); generator.removeFile(`${ANGULAR_DIR}shared/login/login-modal.service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/login/login.service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/model/base-entity.ts`); generator.removeFile(`${ANGULAR_DIR}shared/model/request-util.ts`); generator.removeFile(`${ANGULAR_DIR}shared/user/account.model.ts`); generator.removeFile(`${ANGULAR_DIR}shared/user/user.model.ts`); generator.removeFile(`${ANGULAR_DIR}shared/user/user.service.ts`); generator.removeFile(`${ANGULAR_DIR}admin/user-management/user-management-dialog.component.ts`); generator.removeFile(`${ANGULAR_DIR}admin/user-management/user-modal.service.ts`); generator.removeFile(`${ANGULAR_DIR}admin/user-management/user-modal.service.ts`); generator.removeFile(`${CLIENT_TEST_SRC_DIR}spec/app/shared/user/user.service.spec.ts`); generator.removeFile(`${CLIENT_TEST_SRC_DIR}spec/app/admin/user-management/user-management-dialog.component.spec.ts`); generator.removeFile(`${CLIENT_TEST_SRC_DIR}spec/entry.ts`); generator.removeFile(`${CLIENT_TEST_SRC_DIR}karma.conf.js`); } if (generator.isJhipsterVersionLessThan('5.8.0')) { generator.removeFile(`${ANGULAR_DIR}admin/metrics/metrics-modal.component.html`); generator.removeFile(`${ANGULAR_DIR}admin/metrics/metrics-modal.component.ts`); generator.removeFile(`${CLIENT_TEST_SRC_DIR}spec/app/admin/metrics/metrics-modal.component.spec.ts`); } }
[ "function", "cleanupOldFiles", "(", "generator", ")", "{", "if", "(", "generator", ".", "isJhipsterVersionLessThan", "(", "'3.2.0'", ")", ")", "{", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "}", "if", "(", "generator", ".", "isJhipsterVersionLessThan", "(", "'5.0.0'", ")", ")", "{", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "CLIENT_TEST_SRC_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "CLIENT_TEST_SRC_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "CLIENT_TEST_SRC_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "CLIENT_TEST_SRC_DIR", "}", "`", ")", ";", "}", "if", "(", "generator", ".", "isJhipsterVersionLessThan", "(", "'5.8.0'", ")", ")", "{", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "CLIENT_TEST_SRC_DIR", "}", "`", ")", ";", "}", "}" ]
Removes files that where generated in previous JHipster versions and therefore need to be removed. WARNING this only removes files created by the main generator. Each sub-generator should clean-up its own files: see the `cleanup` method in entity/index.js for cleaning up entities. @param {any} generator - reference to generator
[ "Removes", "files", "that", "where", "generated", "in", "previous", "JHipster", "versions", "and", "therefore", "need", "to", "be", "removed", "." ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/cleanup.js#L41-L78
train
jhipster/generator-jhipster
generators/utils.js
rewriteFile
function rewriteFile(args, generator) { args.path = args.path || process.cwd(); const fullPath = path.join(args.path, args.file); args.haystack = generator.fs.read(fullPath); const body = rewrite(args); generator.fs.write(fullPath, body); }
javascript
function rewriteFile(args, generator) { args.path = args.path || process.cwd(); const fullPath = path.join(args.path, args.file); args.haystack = generator.fs.read(fullPath); const body = rewrite(args); generator.fs.write(fullPath, body); }
[ "function", "rewriteFile", "(", "args", ",", "generator", ")", "{", "args", ".", "path", "=", "args", ".", "path", "||", "process", ".", "cwd", "(", ")", ";", "const", "fullPath", "=", "path", ".", "join", "(", "args", ".", "path", ",", "args", ".", "file", ")", ";", "args", ".", "haystack", "=", "generator", ".", "fs", ".", "read", "(", "fullPath", ")", ";", "const", "body", "=", "rewrite", "(", "args", ")", ";", "generator", ".", "fs", ".", "write", "(", "fullPath", ",", "body", ")", ";", "}" ]
Rewrite file with passed arguments @param {object} args argument object (containing path, file, haystack, etc properties) @param {object} generator reference to the generator
[ "Rewrite", "file", "with", "passed", "arguments" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/utils.js#L57-L64
train
jhipster/generator-jhipster
generators/utils.js
rewrite
function rewrite(args) { // check if splicable is already in the body text const re = new RegExp(args.splicable.map(line => `\\s*${escapeRegExp(line)}`).join('\n')); if (re.test(args.haystack)) { return args.haystack; } const lines = args.haystack.split('\n'); let otherwiseLineIndex = -1; lines.forEach((line, i) => { if (line.includes(args.needle)) { otherwiseLineIndex = i; } }); let spaces = 0; while (lines[otherwiseLineIndex].charAt(spaces) === ' ') { spaces += 1; } let spaceStr = ''; // eslint-disable-next-line no-cond-assign while ((spaces -= 1) >= 0) { spaceStr += ' '; } lines.splice(otherwiseLineIndex, 0, args.splicable.map(line => spaceStr + line).join('\n')); return lines.join('\n'); }
javascript
function rewrite(args) { // check if splicable is already in the body text const re = new RegExp(args.splicable.map(line => `\\s*${escapeRegExp(line)}`).join('\n')); if (re.test(args.haystack)) { return args.haystack; } const lines = args.haystack.split('\n'); let otherwiseLineIndex = -1; lines.forEach((line, i) => { if (line.includes(args.needle)) { otherwiseLineIndex = i; } }); let spaces = 0; while (lines[otherwiseLineIndex].charAt(spaces) === ' ') { spaces += 1; } let spaceStr = ''; // eslint-disable-next-line no-cond-assign while ((spaces -= 1) >= 0) { spaceStr += ' '; } lines.splice(otherwiseLineIndex, 0, args.splicable.map(line => spaceStr + line).join('\n')); return lines.join('\n'); }
[ "function", "rewrite", "(", "args", ")", "{", "const", "re", "=", "new", "RegExp", "(", "args", ".", "splicable", ".", "map", "(", "line", "=>", "`", "\\\\", "${", "escapeRegExp", "(", "line", ")", "}", "`", ")", ".", "join", "(", "'\\n'", ")", ")", ";", "\\n", "if", "(", "re", ".", "test", "(", "args", ".", "haystack", ")", ")", "{", "return", "args", ".", "haystack", ";", "}", "const", "lines", "=", "args", ".", "haystack", ".", "split", "(", "'\\n'", ")", ";", "\\n", "let", "otherwiseLineIndex", "=", "-", "1", ";", "lines", ".", "forEach", "(", "(", "line", ",", "i", ")", "=>", "{", "if", "(", "line", ".", "includes", "(", "args", ".", "needle", ")", ")", "{", "otherwiseLineIndex", "=", "i", ";", "}", "}", ")", ";", "let", "spaces", "=", "0", ";", "while", "(", "lines", "[", "otherwiseLineIndex", "]", ".", "charAt", "(", "spaces", ")", "===", "' '", ")", "{", "spaces", "+=", "1", ";", "}", "let", "spaceStr", "=", "''", ";", "while", "(", "(", "spaces", "-=", "1", ")", ">=", "0", ")", "{", "spaceStr", "+=", "' '", ";", "}", "}" ]
Rewrite using the passed argument object. @param {object} args arguments object (containing splicable, haystack, needle properties) to be used @returns {*} re-written file
[ "Rewrite", "using", "the", "passed", "argument", "object", "." ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/utils.js#L98-L130
train
jhipster/generator-jhipster
generators/utils.js
rewriteJSONFile
function rewriteJSONFile(filePath, rewriteFile, generator) { const jsonObj = generator.fs.readJSON(filePath); rewriteFile(jsonObj, generator); generator.fs.writeJSON(filePath, jsonObj, null, 2); }
javascript
function rewriteJSONFile(filePath, rewriteFile, generator) { const jsonObj = generator.fs.readJSON(filePath); rewriteFile(jsonObj, generator); generator.fs.writeJSON(filePath, jsonObj, null, 2); }
[ "function", "rewriteJSONFile", "(", "filePath", ",", "rewriteFile", ",", "generator", ")", "{", "const", "jsonObj", "=", "generator", ".", "fs", ".", "readJSON", "(", "filePath", ")", ";", "rewriteFile", "(", "jsonObj", ",", "generator", ")", ";", "generator", ".", "fs", ".", "writeJSON", "(", "filePath", ",", "jsonObj", ",", "null", ",", "2", ")", ";", "}" ]
Rewrite JSON file @param {string} filePath file path @param {function} rewriteFile rewriteFile function @param {object} generator reference to the generator
[ "Rewrite", "JSON", "file" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/utils.js#L152-L156
train
jhipster/generator-jhipster
generators/utils.js
copyWebResource
function copyWebResource(source, dest, regex, type, generator, opt = {}, template) { if (generator.enableTranslation) { generator.template(source, dest, generator, opt); } else { renderContent(source, generator, generator, opt, body => { body = body.replace(regex, ''); switch (type) { case 'html': body = replacePlaceholders(body, generator); break; case 'js': body = replaceTitle(body, generator); break; case 'jsx': body = replaceTranslation(body, generator); break; default: break; } generator.fs.write(dest, body); }); } }
javascript
function copyWebResource(source, dest, regex, type, generator, opt = {}, template) { if (generator.enableTranslation) { generator.template(source, dest, generator, opt); } else { renderContent(source, generator, generator, opt, body => { body = body.replace(regex, ''); switch (type) { case 'html': body = replacePlaceholders(body, generator); break; case 'js': body = replaceTitle(body, generator); break; case 'jsx': body = replaceTranslation(body, generator); break; default: break; } generator.fs.write(dest, body); }); } }
[ "function", "copyWebResource", "(", "source", ",", "dest", ",", "regex", ",", "type", ",", "generator", ",", "opt", "=", "{", "}", ",", "template", ")", "{", "if", "(", "generator", ".", "enableTranslation", ")", "{", "generator", ".", "template", "(", "source", ",", "dest", ",", "generator", ",", "opt", ")", ";", "}", "else", "{", "renderContent", "(", "source", ",", "generator", ",", "generator", ",", "opt", ",", "body", "=>", "{", "body", "=", "body", ".", "replace", "(", "regex", ",", "''", ")", ";", "switch", "(", "type", ")", "{", "case", "'html'", ":", "body", "=", "replacePlaceholders", "(", "body", ",", "generator", ")", ";", "break", ";", "case", "'js'", ":", "body", "=", "replaceTitle", "(", "body", ",", "generator", ")", ";", "break", ";", "case", "'jsx'", ":", "body", "=", "replaceTranslation", "(", "body", ",", "generator", ")", ";", "break", ";", "default", ":", "break", ";", "}", "generator", ".", "fs", ".", "write", "(", "dest", ",", "body", ")", ";", "}", ")", ";", "}", "}" ]
Copy web resources @param {string} source source @param {string} dest destination @param {regex} regex regex @param {string} type type of resource (html, js, etc) @param {object} generator reference to the generator @param {object} opt options @param {any} template template
[ "Copy", "web", "resources" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/utils.js#L169-L191
train
jhipster/generator-jhipster
generators/utils.js
getJavadoc
function getJavadoc(text, indentSize) { if (!text) { text = ''; } if (text.includes('"')) { text = text.replace(/"/g, '\\"'); } let javadoc = `${_.repeat(' ', indentSize)}/**`; const rows = text.split('\n'); for (let i = 0; i < rows.length; i++) { javadoc = `${javadoc}\n${_.repeat(' ', indentSize)} * ${rows[i]}`; } javadoc = `${javadoc}\n${_.repeat(' ', indentSize)} */`; return javadoc; }
javascript
function getJavadoc(text, indentSize) { if (!text) { text = ''; } if (text.includes('"')) { text = text.replace(/"/g, '\\"'); } let javadoc = `${_.repeat(' ', indentSize)}/**`; const rows = text.split('\n'); for (let i = 0; i < rows.length; i++) { javadoc = `${javadoc}\n${_.repeat(' ', indentSize)} * ${rows[i]}`; } javadoc = `${javadoc}\n${_.repeat(' ', indentSize)} */`; return javadoc; }
[ "function", "getJavadoc", "(", "text", ",", "indentSize", ")", "{", "if", "(", "!", "text", ")", "{", "text", "=", "''", ";", "}", "if", "(", "text", ".", "includes", "(", "'\"'", ")", ")", "{", "text", "=", "text", ".", "replace", "(", "/", "\"", "/", "g", ",", "'\\\\\"'", ")", ";", "}", "\\\\", "let", "javadoc", "=", "`", "${", "_", ".", "repeat", "(", "' '", ",", "indentSize", ")", "}", "`", ";", "const", "rows", "=", "text", ".", "split", "(", "'\\n'", ")", ";", "\\n", "for", "(", "let", "i", "=", "0", ";", "i", "<", "rows", ".", "length", ";", "i", "++", ")", "{", "javadoc", "=", "`", "${", "javadoc", "}", "\\n", "${", "_", ".", "repeat", "(", "' '", ",", "indentSize", ")", "}", "${", "rows", "[", "i", "]", "}", "`", ";", "}", "}" ]
Convert passed block of string to javadoc formatted string. @param {string} text text to convert to javadoc format @param {number} indentSize indent size @returns javadoc formatted string
[ "Convert", "passed", "block", "of", "string", "to", "javadoc", "formatted", "string", "." ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/utils.js#L356-L370
train
jhipster/generator-jhipster
generators/utils.js
buildEnumInfo
function buildEnumInfo(field, angularAppName, packageName, clientRootFolder) { const fieldType = field.fieldType; field.enumInstance = _.lowerFirst(fieldType); const enumInfo = { enumName: fieldType, enumValues: field.fieldValues.split(',').join(', '), enumInstance: field.enumInstance, enums: field.fieldValues.replace(/\s/g, '').split(','), angularAppName, packageName, clientRootFolder: clientRootFolder ? `${clientRootFolder}-` : '' }; return enumInfo; }
javascript
function buildEnumInfo(field, angularAppName, packageName, clientRootFolder) { const fieldType = field.fieldType; field.enumInstance = _.lowerFirst(fieldType); const enumInfo = { enumName: fieldType, enumValues: field.fieldValues.split(',').join(', '), enumInstance: field.enumInstance, enums: field.fieldValues.replace(/\s/g, '').split(','), angularAppName, packageName, clientRootFolder: clientRootFolder ? `${clientRootFolder}-` : '' }; return enumInfo; }
[ "function", "buildEnumInfo", "(", "field", ",", "angularAppName", ",", "packageName", ",", "clientRootFolder", ")", "{", "const", "fieldType", "=", "field", ".", "fieldType", ";", "field", ".", "enumInstance", "=", "_", ".", "lowerFirst", "(", "fieldType", ")", ";", "const", "enumInfo", "=", "{", "enumName", ":", "fieldType", ",", "enumValues", ":", "field", ".", "fieldValues", ".", "split", "(", "','", ")", ".", "join", "(", "', '", ")", ",", "enumInstance", ":", "field", ".", "enumInstance", ",", "enums", ":", "field", ".", "fieldValues", ".", "replace", "(", "/", "\\s", "/", "g", ",", "''", ")", ".", "split", "(", "','", ")", ",", "angularAppName", ",", "packageName", ",", "clientRootFolder", ":", "clientRootFolder", "?", "`", "${", "clientRootFolder", "}", "`", ":", "''", "}", ";", "return", "enumInfo", ";", "}" ]
Build an enum object @param {any} field : entity field @param {string} angularAppName @param {string} packageName
[ "Build", "an", "enum", "object" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/utils.js#L378-L391
train
jhipster/generator-jhipster
generators/utils.js
getAllJhipsterConfig
function getAllJhipsterConfig(generator, force) { let configuration = generator && generator.config ? generator.config.getAll() || {} : {}; if ((force || !configuration.baseName) && jhiCore.FileUtils.doesFileExist('.yo-rc.json')) { const yoRc = JSON.parse(fs.readFileSync('.yo-rc.json', { encoding: 'utf-8' })); configuration = yoRc['generator-jhipster']; // merge the blueprint config if available if (configuration.blueprint) { configuration = { ...configuration, ...yoRc[configuration.blueprint] }; } } if (!configuration.get || typeof configuration.get !== 'function') { configuration = { ...configuration, getAll: () => configuration, get: key => configuration[key], set: (key, value) => { configuration[key] = value; } }; } return configuration; }
javascript
function getAllJhipsterConfig(generator, force) { let configuration = generator && generator.config ? generator.config.getAll() || {} : {}; if ((force || !configuration.baseName) && jhiCore.FileUtils.doesFileExist('.yo-rc.json')) { const yoRc = JSON.parse(fs.readFileSync('.yo-rc.json', { encoding: 'utf-8' })); configuration = yoRc['generator-jhipster']; // merge the blueprint config if available if (configuration.blueprint) { configuration = { ...configuration, ...yoRc[configuration.blueprint] }; } } if (!configuration.get || typeof configuration.get !== 'function') { configuration = { ...configuration, getAll: () => configuration, get: key => configuration[key], set: (key, value) => { configuration[key] = value; } }; } return configuration; }
[ "function", "getAllJhipsterConfig", "(", "generator", ",", "force", ")", "{", "let", "configuration", "=", "generator", "&&", "generator", ".", "config", "?", "generator", ".", "config", ".", "getAll", "(", ")", "||", "{", "}", ":", "{", "}", ";", "if", "(", "(", "force", "||", "!", "configuration", ".", "baseName", ")", "&&", "jhiCore", ".", "FileUtils", ".", "doesFileExist", "(", "'.yo-rc.json'", ")", ")", "{", "const", "yoRc", "=", "JSON", ".", "parse", "(", "fs", ".", "readFileSync", "(", "'.yo-rc.json'", ",", "{", "encoding", ":", "'utf-8'", "}", ")", ")", ";", "configuration", "=", "yoRc", "[", "'generator-jhipster'", "]", ";", "if", "(", "configuration", ".", "blueprint", ")", "{", "configuration", "=", "{", "...", "configuration", ",", "...", "yoRc", "[", "configuration", ".", "blueprint", "]", "}", ";", "}", "}", "if", "(", "!", "configuration", ".", "get", "||", "typeof", "configuration", ".", "get", "!==", "'function'", ")", "{", "configuration", "=", "{", "...", "configuration", ",", "getAll", ":", "(", ")", "=>", "configuration", ",", "get", ":", "key", "=>", "configuration", "[", "key", "]", ",", "set", ":", "(", "key", ",", "value", ")", "=>", "{", "configuration", "[", "key", "]", "=", "value", ";", "}", "}", ";", "}", "return", "configuration", ";", "}" ]
Get all the generator configuration from the .yo-rc.json file @param {Generator} generator the generator instance to use @param {boolean} force force getting direct from file
[ "Get", "all", "the", "generator", "configuration", "from", "the", ".", "yo", "-", "rc", ".", "json", "file" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/utils.js#L417-L438
train
jhipster/generator-jhipster
generators/utils.js
getDBTypeFromDBValue
function getDBTypeFromDBValue(db) { if (constants.SQL_DB_OPTIONS.map(db => db.value).includes(db)) { return 'sql'; } return db; }
javascript
function getDBTypeFromDBValue(db) { if (constants.SQL_DB_OPTIONS.map(db => db.value).includes(db)) { return 'sql'; } return db; }
[ "function", "getDBTypeFromDBValue", "(", "db", ")", "{", "if", "(", "constants", ".", "SQL_DB_OPTIONS", ".", "map", "(", "db", "=>", "db", ".", "value", ")", ".", "includes", "(", "db", ")", ")", "{", "return", "'sql'", ";", "}", "return", "db", ";", "}" ]
Get DB type from DB value @param {string} db - db
[ "Get", "DB", "type", "from", "DB", "value" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/utils.js#L444-L449
train
jhipster/generator-jhipster
generators/entity/prompts.js
askForRelationship
function askForRelationship(done) { const context = this.context; const name = context.name; this.log(chalk.green('\nGenerating relationships to other entities\n')); const fieldNamesUnderscored = context.fieldNamesUnderscored; const prompts = [ { type: 'confirm', name: 'relationshipAdd', message: 'Do you want to add a relationship to another entity?', default: true }, { when: response => response.relationshipAdd === true, type: 'input', name: 'otherEntityName', validate: input => { if (!/^([a-zA-Z0-9_]*)$/.test(input)) { return 'Your other entity name cannot contain special characters'; } if (input === '') { return 'Your other entity name cannot be empty'; } if (jhiCore.isReservedKeyword(input, 'JAVA')) { return 'Your other entity name cannot contain a Java reserved keyword'; } if (input.toLowerCase() === 'user' && context.applicationType === 'microservice') { return "Your entity cannot have a relationship with User because it's a gateway entity"; } return true; }, message: 'What is the name of the other entity?' }, { when: response => response.relationshipAdd === true, type: 'input', name: 'relationshipName', validate: input => { if (!/^([a-zA-Z0-9_]*)$/.test(input)) { return 'Your relationship cannot contain special characters'; } if (input === '') { return 'Your relationship cannot be empty'; } if (input.charAt(0) === input.charAt(0).toUpperCase()) { return 'Your relationship cannot start with an upper case letter'; } if (input === 'id' || fieldNamesUnderscored.includes(_.snakeCase(input))) { return 'Your relationship cannot use an already existing field name'; } if (jhiCore.isReservedKeyword(input, 'JAVA')) { return 'Your relationship cannot contain a Java reserved keyword'; } return true; }, message: 'What is the name of the relationship?', default: response => _.lowerFirst(response.otherEntityName) }, { when: response => response.relationshipAdd === true, type: 'list', name: 'relationshipType', message: 'What is the type of the relationship?', choices: response => { const opts = [ { value: 'many-to-one', name: 'many-to-one' }, { value: 'many-to-many', name: 'many-to-many' }, { value: 'one-to-one', name: 'one-to-one' } ]; if (response.otherEntityName.toLowerCase() !== 'user') { opts.unshift({ value: 'one-to-many', name: 'one-to-many' }); } return opts; }, default: 0 }, { when: response => response.relationshipAdd === true && response.otherEntityName.toLowerCase() !== 'user' && (response.relationshipType === 'many-to-many' || response.relationshipType === 'one-to-one'), type: 'confirm', name: 'ownerSide', message: 'Is this entity the owner of the relationship?', default: false }, { when: response => context.databaseType === 'sql' && response.relationshipAdd === true && response.relationshipType === 'one-to-one' && (response.ownerSide === true || response.otherEntityName.toLowerCase() === 'user'), type: 'confirm', name: 'useJPADerivedIdentifier', message: 'Do you want to use JPA Derived Identifier - @MapsId?', default: false }, { when: response => response.relationshipAdd === true && (response.relationshipType === 'one-to-many' || ((response.relationshipType === 'many-to-many' || response.relationshipType === 'one-to-one') && response.otherEntityName.toLowerCase() !== 'user')), type: 'input', name: 'otherEntityRelationshipName', message: 'What is the name of this relationship in the other entity?', default: response => _.lowerFirst(name) }, { when: response => response.relationshipAdd === true && (response.relationshipType === 'many-to-one' || (response.relationshipType === 'many-to-many' && response.ownerSide === true) || (response.relationshipType === 'one-to-one' && response.ownerSide === true)), type: 'input', name: 'otherEntityField', message: response => `When you display this relationship on client-side, which field from '${ response.otherEntityName }' do you want to use? This field will be displayed as a String, so it cannot be a Blob`, default: 'id' }, { when: response => response.relationshipAdd === true && response.otherEntityName.toLowerCase() !== context.name.toLowerCase() && (response.relationshipType === 'many-to-one' || (response.relationshipType === 'many-to-many' && (response.ownerSide === true || response.otherEntityName.toLowerCase() === 'user')) || (response.relationshipType === 'one-to-one' && (response.ownerSide === true || response.otherEntityName.toLowerCase() === 'user'))), type: 'confirm', name: 'relationshipValidate', message: 'Do you want to add any validation rules to this relationship?', default: false }, { when: response => response.relationshipValidate === true, type: 'checkbox', name: 'relationshipValidateRules', message: 'Which validation rules do you want to add?', choices: [ { name: 'Required', value: 'required' } ], default: 0 } ]; this.prompt(prompts).then(props => { if (props.relationshipAdd) { const relationship = { relationshipName: props.relationshipName, otherEntityName: _.lowerFirst(props.otherEntityName), relationshipType: props.relationshipType, relationshipValidateRules: props.relationshipValidateRules, otherEntityField: props.otherEntityField, ownerSide: props.ownerSide, useJPADerivedIdentifier: props.useJPADerivedIdentifier, otherEntityRelationshipName: props.otherEntityRelationshipName }; if (props.otherEntityName.toLowerCase() === 'user') { relationship.ownerSide = true; relationship.otherEntityField = 'login'; relationship.otherEntityRelationshipName = _.lowerFirst(name); } fieldNamesUnderscored.push(_.snakeCase(props.relationshipName)); context.relationships.push(relationship); } logFieldsAndRelationships.call(this); if (props.relationshipAdd) { askForRelationship.call(this, done); } else { this.log('\n'); done(); } }); }
javascript
function askForRelationship(done) { const context = this.context; const name = context.name; this.log(chalk.green('\nGenerating relationships to other entities\n')); const fieldNamesUnderscored = context.fieldNamesUnderscored; const prompts = [ { type: 'confirm', name: 'relationshipAdd', message: 'Do you want to add a relationship to another entity?', default: true }, { when: response => response.relationshipAdd === true, type: 'input', name: 'otherEntityName', validate: input => { if (!/^([a-zA-Z0-9_]*)$/.test(input)) { return 'Your other entity name cannot contain special characters'; } if (input === '') { return 'Your other entity name cannot be empty'; } if (jhiCore.isReservedKeyword(input, 'JAVA')) { return 'Your other entity name cannot contain a Java reserved keyword'; } if (input.toLowerCase() === 'user' && context.applicationType === 'microservice') { return "Your entity cannot have a relationship with User because it's a gateway entity"; } return true; }, message: 'What is the name of the other entity?' }, { when: response => response.relationshipAdd === true, type: 'input', name: 'relationshipName', validate: input => { if (!/^([a-zA-Z0-9_]*)$/.test(input)) { return 'Your relationship cannot contain special characters'; } if (input === '') { return 'Your relationship cannot be empty'; } if (input.charAt(0) === input.charAt(0).toUpperCase()) { return 'Your relationship cannot start with an upper case letter'; } if (input === 'id' || fieldNamesUnderscored.includes(_.snakeCase(input))) { return 'Your relationship cannot use an already existing field name'; } if (jhiCore.isReservedKeyword(input, 'JAVA')) { return 'Your relationship cannot contain a Java reserved keyword'; } return true; }, message: 'What is the name of the relationship?', default: response => _.lowerFirst(response.otherEntityName) }, { when: response => response.relationshipAdd === true, type: 'list', name: 'relationshipType', message: 'What is the type of the relationship?', choices: response => { const opts = [ { value: 'many-to-one', name: 'many-to-one' }, { value: 'many-to-many', name: 'many-to-many' }, { value: 'one-to-one', name: 'one-to-one' } ]; if (response.otherEntityName.toLowerCase() !== 'user') { opts.unshift({ value: 'one-to-many', name: 'one-to-many' }); } return opts; }, default: 0 }, { when: response => response.relationshipAdd === true && response.otherEntityName.toLowerCase() !== 'user' && (response.relationshipType === 'many-to-many' || response.relationshipType === 'one-to-one'), type: 'confirm', name: 'ownerSide', message: 'Is this entity the owner of the relationship?', default: false }, { when: response => context.databaseType === 'sql' && response.relationshipAdd === true && response.relationshipType === 'one-to-one' && (response.ownerSide === true || response.otherEntityName.toLowerCase() === 'user'), type: 'confirm', name: 'useJPADerivedIdentifier', message: 'Do you want to use JPA Derived Identifier - @MapsId?', default: false }, { when: response => response.relationshipAdd === true && (response.relationshipType === 'one-to-many' || ((response.relationshipType === 'many-to-many' || response.relationshipType === 'one-to-one') && response.otherEntityName.toLowerCase() !== 'user')), type: 'input', name: 'otherEntityRelationshipName', message: 'What is the name of this relationship in the other entity?', default: response => _.lowerFirst(name) }, { when: response => response.relationshipAdd === true && (response.relationshipType === 'many-to-one' || (response.relationshipType === 'many-to-many' && response.ownerSide === true) || (response.relationshipType === 'one-to-one' && response.ownerSide === true)), type: 'input', name: 'otherEntityField', message: response => `When you display this relationship on client-side, which field from '${ response.otherEntityName }' do you want to use? This field will be displayed as a String, so it cannot be a Blob`, default: 'id' }, { when: response => response.relationshipAdd === true && response.otherEntityName.toLowerCase() !== context.name.toLowerCase() && (response.relationshipType === 'many-to-one' || (response.relationshipType === 'many-to-many' && (response.ownerSide === true || response.otherEntityName.toLowerCase() === 'user')) || (response.relationshipType === 'one-to-one' && (response.ownerSide === true || response.otherEntityName.toLowerCase() === 'user'))), type: 'confirm', name: 'relationshipValidate', message: 'Do you want to add any validation rules to this relationship?', default: false }, { when: response => response.relationshipValidate === true, type: 'checkbox', name: 'relationshipValidateRules', message: 'Which validation rules do you want to add?', choices: [ { name: 'Required', value: 'required' } ], default: 0 } ]; this.prompt(prompts).then(props => { if (props.relationshipAdd) { const relationship = { relationshipName: props.relationshipName, otherEntityName: _.lowerFirst(props.otherEntityName), relationshipType: props.relationshipType, relationshipValidateRules: props.relationshipValidateRules, otherEntityField: props.otherEntityField, ownerSide: props.ownerSide, useJPADerivedIdentifier: props.useJPADerivedIdentifier, otherEntityRelationshipName: props.otherEntityRelationshipName }; if (props.otherEntityName.toLowerCase() === 'user') { relationship.ownerSide = true; relationship.otherEntityField = 'login'; relationship.otherEntityRelationshipName = _.lowerFirst(name); } fieldNamesUnderscored.push(_.snakeCase(props.relationshipName)); context.relationships.push(relationship); } logFieldsAndRelationships.call(this); if (props.relationshipAdd) { askForRelationship.call(this, done); } else { this.log('\n'); done(); } }); }
[ "function", "askForRelationship", "(", "done", ")", "{", "const", "context", "=", "this", ".", "context", ";", "const", "name", "=", "context", ".", "name", ";", "this", ".", "log", "(", "chalk", ".", "green", "(", "'\\nGenerating relationships to other entities\\n'", ")", ")", ";", "\\n", "\\n", "const", "fieldNamesUnderscored", "=", "context", ".", "fieldNamesUnderscored", ";", "}" ]
ask question for a relationship creation
[ "ask", "question", "for", "a", "relationship", "creation" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/entity/prompts.js#L878-L1070
train
jhipster/generator-jhipster
generators/entity/prompts.js
logFieldsAndRelationships
function logFieldsAndRelationships() { const context = this.context; if (context.fields.length > 0 || context.relationships.length > 0) { this.log(chalk.red(chalk.white('\n================= ') + context.entityNameCapitalized + chalk.white(' ================='))); } if (context.fields.length > 0) { this.log(chalk.white('Fields')); context.fields.forEach(field => { const validationDetails = []; const fieldValidate = _.isArray(field.fieldValidateRules) && field.fieldValidateRules.length >= 1; if (fieldValidate === true) { if (field.fieldValidateRules.includes('required')) { validationDetails.push('required'); } if (field.fieldValidateRules.includes('unique')) { validationDetails.push('unique'); } if (field.fieldValidateRules.includes('minlength')) { validationDetails.push(`minlength='${field.fieldValidateRulesMinlength}'`); } if (field.fieldValidateRules.includes('maxlength')) { validationDetails.push(`maxlength='${field.fieldValidateRulesMaxlength}'`); } if (field.fieldValidateRules.includes('pattern')) { validationDetails.push(`pattern='${field.fieldValidateRulesPattern}'`); } if (field.fieldValidateRules.includes('min')) { validationDetails.push(`min='${field.fieldValidateRulesMin}'`); } if (field.fieldValidateRules.includes('max')) { validationDetails.push(`max='${field.fieldValidateRulesMax}'`); } if (field.fieldValidateRules.includes('minbytes')) { validationDetails.push(`minbytes='${field.fieldValidateRulesMinbytes}'`); } if (field.fieldValidateRules.includes('maxbytes')) { validationDetails.push(`maxbytes='${field.fieldValidateRulesMaxbytes}'`); } } this.log( chalk.red(field.fieldName) + chalk.white(` (${field.fieldType}${field.fieldTypeBlobContent ? ` ${field.fieldTypeBlobContent}` : ''}) `) + chalk.cyan(validationDetails.join(' ')) ); }); this.log(); } if (context.relationships.length > 0) { this.log(chalk.white('Relationships')); context.relationships.forEach(relationship => { const validationDetails = []; if (relationship.relationshipValidateRules && relationship.relationshipValidateRules.includes('required')) { validationDetails.push('required'); } this.log( `${chalk.red(relationship.relationshipName)} ${chalk.white(`(${_.upperFirst(relationship.otherEntityName)})`)} ${chalk.cyan( relationship.relationshipType )} ${chalk.cyan(validationDetails.join(' '))}` ); }); this.log(); } }
javascript
function logFieldsAndRelationships() { const context = this.context; if (context.fields.length > 0 || context.relationships.length > 0) { this.log(chalk.red(chalk.white('\n================= ') + context.entityNameCapitalized + chalk.white(' ================='))); } if (context.fields.length > 0) { this.log(chalk.white('Fields')); context.fields.forEach(field => { const validationDetails = []; const fieldValidate = _.isArray(field.fieldValidateRules) && field.fieldValidateRules.length >= 1; if (fieldValidate === true) { if (field.fieldValidateRules.includes('required')) { validationDetails.push('required'); } if (field.fieldValidateRules.includes('unique')) { validationDetails.push('unique'); } if (field.fieldValidateRules.includes('minlength')) { validationDetails.push(`minlength='${field.fieldValidateRulesMinlength}'`); } if (field.fieldValidateRules.includes('maxlength')) { validationDetails.push(`maxlength='${field.fieldValidateRulesMaxlength}'`); } if (field.fieldValidateRules.includes('pattern')) { validationDetails.push(`pattern='${field.fieldValidateRulesPattern}'`); } if (field.fieldValidateRules.includes('min')) { validationDetails.push(`min='${field.fieldValidateRulesMin}'`); } if (field.fieldValidateRules.includes('max')) { validationDetails.push(`max='${field.fieldValidateRulesMax}'`); } if (field.fieldValidateRules.includes('minbytes')) { validationDetails.push(`minbytes='${field.fieldValidateRulesMinbytes}'`); } if (field.fieldValidateRules.includes('maxbytes')) { validationDetails.push(`maxbytes='${field.fieldValidateRulesMaxbytes}'`); } } this.log( chalk.red(field.fieldName) + chalk.white(` (${field.fieldType}${field.fieldTypeBlobContent ? ` ${field.fieldTypeBlobContent}` : ''}) `) + chalk.cyan(validationDetails.join(' ')) ); }); this.log(); } if (context.relationships.length > 0) { this.log(chalk.white('Relationships')); context.relationships.forEach(relationship => { const validationDetails = []; if (relationship.relationshipValidateRules && relationship.relationshipValidateRules.includes('required')) { validationDetails.push('required'); } this.log( `${chalk.red(relationship.relationshipName)} ${chalk.white(`(${_.upperFirst(relationship.otherEntityName)})`)} ${chalk.cyan( relationship.relationshipType )} ${chalk.cyan(validationDetails.join(' '))}` ); }); this.log(); } }
[ "function", "logFieldsAndRelationships", "(", ")", "{", "const", "context", "=", "this", ".", "context", ";", "if", "(", "context", ".", "fields", ".", "length", ">", "0", "||", "context", ".", "relationships", ".", "length", ">", "0", ")", "{", "this", ".", "log", "(", "chalk", ".", "red", "(", "chalk", ".", "white", "(", "'\\n================= '", ")", "+", "\\n", "+", "context", ".", "entityNameCapitalized", ")", ")", ";", "}", "chalk", ".", "white", "(", "' ================='", ")", "if", "(", "context", ".", "fields", ".", "length", ">", "0", ")", "{", "this", ".", "log", "(", "chalk", ".", "white", "(", "'Fields'", ")", ")", ";", "context", ".", "fields", ".", "forEach", "(", "field", "=>", "{", "const", "validationDetails", "=", "[", "]", ";", "const", "fieldValidate", "=", "_", ".", "isArray", "(", "field", ".", "fieldValidateRules", ")", "&&", "field", ".", "fieldValidateRules", ".", "length", ">=", "1", ";", "if", "(", "fieldValidate", "===", "true", ")", "{", "if", "(", "field", ".", "fieldValidateRules", ".", "includes", "(", "'required'", ")", ")", "{", "validationDetails", ".", "push", "(", "'required'", ")", ";", "}", "if", "(", "field", ".", "fieldValidateRules", ".", "includes", "(", "'unique'", ")", ")", "{", "validationDetails", ".", "push", "(", "'unique'", ")", ";", "}", "if", "(", "field", ".", "fieldValidateRules", ".", "includes", "(", "'minlength'", ")", ")", "{", "validationDetails", ".", "push", "(", "`", "${", "field", ".", "fieldValidateRulesMinlength", "}", "`", ")", ";", "}", "if", "(", "field", ".", "fieldValidateRules", ".", "includes", "(", "'maxlength'", ")", ")", "{", "validationDetails", ".", "push", "(", "`", "${", "field", ".", "fieldValidateRulesMaxlength", "}", "`", ")", ";", "}", "if", "(", "field", ".", "fieldValidateRules", ".", "includes", "(", "'pattern'", ")", ")", "{", "validationDetails", ".", "push", "(", "`", "${", "field", ".", "fieldValidateRulesPattern", "}", "`", ")", ";", "}", "if", "(", "field", ".", "fieldValidateRules", ".", "includes", "(", "'min'", ")", ")", "{", "validationDetails", ".", "push", "(", "`", "${", "field", ".", "fieldValidateRulesMin", "}", "`", ")", ";", "}", "if", "(", "field", ".", "fieldValidateRules", ".", "includes", "(", "'max'", ")", ")", "{", "validationDetails", ".", "push", "(", "`", "${", "field", ".", "fieldValidateRulesMax", "}", "`", ")", ";", "}", "if", "(", "field", ".", "fieldValidateRules", ".", "includes", "(", "'minbytes'", ")", ")", "{", "validationDetails", ".", "push", "(", "`", "${", "field", ".", "fieldValidateRulesMinbytes", "}", "`", ")", ";", "}", "if", "(", "field", ".", "fieldValidateRules", ".", "includes", "(", "'maxbytes'", ")", ")", "{", "validationDetails", ".", "push", "(", "`", "${", "field", ".", "fieldValidateRulesMaxbytes", "}", "`", ")", ";", "}", "}", "this", ".", "log", "(", "chalk", ".", "red", "(", "field", ".", "fieldName", ")", "+", "chalk", ".", "white", "(", "`", "${", "field", ".", "fieldType", "}", "${", "field", ".", "fieldTypeBlobContent", "?", "`", "${", "field", ".", "fieldTypeBlobContent", "}", "`", ":", "''", "}", "`", ")", "+", "chalk", ".", "cyan", "(", "validationDetails", ".", "join", "(", "' '", ")", ")", ")", ";", "}", ")", ";", "this", ".", "log", "(", ")", ";", "}", "}" ]
Show the entity and it's fields and relationships in console
[ "Show", "the", "entity", "and", "it", "s", "fields", "and", "relationships", "in", "console" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/entity/prompts.js#L1075-L1137
train
jhipster/generator-jhipster
generators/aws-containers/aws-client.js
loadAWS
function loadAWS(generator) { return new Promise((resolve, reject) => { try { AWS = require('aws-sdk'); // eslint-disable-line ProgressBar = require('progress'); // eslint-disable-line ora = require('ora'); // eslint-disable-line } catch (e) { generator.log('Installing AWS dependencies'); let installCommand = 'yarn add [email protected] [email protected] [email protected]'; if (generator.config.get('clientPackageManager') === 'npm') { installCommand = 'npm install [email protected] [email protected] [email protected]'; } shelljs.exec(installCommand, { silent: false }, code => { if (code !== 0) { generator.error('Something went wrong while installing the dependencies\n'); reject(); } AWS = require('aws-sdk'); // eslint-disable-line ProgressBar = require('progress'); // eslint-disable-line ora = require('ora'); // eslint-disable-line }); } resolve(); }); }
javascript
function loadAWS(generator) { return new Promise((resolve, reject) => { try { AWS = require('aws-sdk'); // eslint-disable-line ProgressBar = require('progress'); // eslint-disable-line ora = require('ora'); // eslint-disable-line } catch (e) { generator.log('Installing AWS dependencies'); let installCommand = 'yarn add [email protected] [email protected] [email protected]'; if (generator.config.get('clientPackageManager') === 'npm') { installCommand = 'npm install [email protected] [email protected] [email protected]'; } shelljs.exec(installCommand, { silent: false }, code => { if (code !== 0) { generator.error('Something went wrong while installing the dependencies\n'); reject(); } AWS = require('aws-sdk'); // eslint-disable-line ProgressBar = require('progress'); // eslint-disable-line ora = require('ora'); // eslint-disable-line }); } resolve(); }); }
[ "function", "loadAWS", "(", "generator", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "try", "{", "AWS", "=", "require", "(", "'aws-sdk'", ")", ";", "ProgressBar", "=", "require", "(", "'progress'", ")", ";", "ora", "=", "require", "(", "'ora'", ")", ";", "}", "catch", "(", "e", ")", "{", "generator", ".", "log", "(", "'Installing AWS dependencies'", ")", ";", "let", "installCommand", "=", "'yarn add [email protected] [email protected] [email protected]'", ";", "if", "(", "generator", ".", "config", ".", "get", "(", "'clientPackageManager'", ")", "===", "'npm'", ")", "{", "installCommand", "=", "'npm install [email protected] [email protected] [email protected]'", ";", "}", "shelljs", ".", "exec", "(", "installCommand", ",", "{", "silent", ":", "false", "}", ",", "code", "=>", "{", "if", "(", "code", "!==", "0", ")", "{", "generator", ".", "error", "(", "'Something went wrong while installing the dependencies\\n'", ")", ";", "\\n", "}", "reject", "(", ")", ";", "AWS", "=", "require", "(", "'aws-sdk'", ")", ";", "ProgressBar", "=", "require", "(", "'progress'", ")", ";", "}", ")", ";", "}", "ora", "=", "require", "(", "'ora'", ")", ";", "}", ")", ";", "}" ]
Will load the aws-sdk npm dependency if it's not already loaded. @param generator the yeoman generator it'll be loaded in. @returns {Promise} The promise will succeed if the aws-sdk has been loaded and fails if it couldn't be installed.
[ "Will", "load", "the", "aws", "-", "sdk", "npm", "dependency", "if", "it", "s", "not", "already", "loaded", "." ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/aws-containers/aws-client.js#L73-L97
train
jhipster/generator-jhipster
generators/aws-containers/aws-client.js
initAwsStuff
function initAwsStuff(region = DEFAULT_REGION) { ec2 = new AWS.EC2({ region }); // ecr = new AWS.ECR({ region }); s3 = new AWS.S3(); sts = new AWS.STS(); SSM = new AwsSSM(region); ECR = new AwsECR(region); CF = new AwsCF(region); }
javascript
function initAwsStuff(region = DEFAULT_REGION) { ec2 = new AWS.EC2({ region }); // ecr = new AWS.ECR({ region }); s3 = new AWS.S3(); sts = new AWS.STS(); SSM = new AwsSSM(region); ECR = new AwsECR(region); CF = new AwsCF(region); }
[ "function", "initAwsStuff", "(", "region", "=", "DEFAULT_REGION", ")", "{", "ec2", "=", "new", "AWS", ".", "EC2", "(", "{", "region", "}", ")", ";", "s3", "=", "new", "AWS", ".", "S3", "(", ")", ";", "sts", "=", "new", "AWS", ".", "STS", "(", ")", ";", "SSM", "=", "new", "AwsSSM", "(", "region", ")", ";", "ECR", "=", "new", "AwsECR", "(", "region", ")", ";", "CF", "=", "new", "AwsCF", "(", "region", ")", ";", "}" ]
Init AWS stuff like ECR and whatnot. @param ecrConfig The config used to instanciate ECR
[ "Init", "AWS", "stuff", "like", "ECR", "and", "whatnot", "." ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/aws-containers/aws-client.js#L104-L113
train
jhipster/generator-jhipster
generators/aws-containers/aws-client.js
getDockerLogin
function getDockerLogin() { return spinner( new Promise((resolve, reject) => _getAuthorizationToken().then(authToken => sts .getCallerIdentity({}) .promise() .then(data => { const decoded = utils.decodeBase64(authToken.authorizationToken); const splitResult = decoded.split(':'); resolve({ username: splitResult[0], password: splitResult[1], accountId: data.Account }); }) .catch(() => reject(new Error("Couldn't retrieve the user informations"))) ) ) ); }
javascript
function getDockerLogin() { return spinner( new Promise((resolve, reject) => _getAuthorizationToken().then(authToken => sts .getCallerIdentity({}) .promise() .then(data => { const decoded = utils.decodeBase64(authToken.authorizationToken); const splitResult = decoded.split(':'); resolve({ username: splitResult[0], password: splitResult[1], accountId: data.Account }); }) .catch(() => reject(new Error("Couldn't retrieve the user informations"))) ) ) ); }
[ "function", "getDockerLogin", "(", ")", "{", "return", "spinner", "(", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "_getAuthorizationToken", "(", ")", ".", "then", "(", "authToken", "=>", "sts", ".", "getCallerIdentity", "(", "{", "}", ")", ".", "promise", "(", ")", ".", "then", "(", "data", "=>", "{", "const", "decoded", "=", "utils", ".", "decodeBase64", "(", "authToken", ".", "authorizationToken", ")", ";", "const", "splitResult", "=", "decoded", ".", "split", "(", "':'", ")", ";", "resolve", "(", "{", "username", ":", "splitResult", "[", "0", "]", ",", "password", ":", "splitResult", "[", "1", "]", ",", "accountId", ":", "data", ".", "Account", "}", ")", ";", "}", ")", ".", "catch", "(", "(", ")", "=>", "reject", "(", "new", "Error", "(", "\"Couldn't retrieve the user informations\"", ")", ")", ")", ")", ")", ")", ";", "}" ]
Retrieve decoded information to authenticate to Docker with AWS credentials. @returns {Promise} Returns a promise that resolves when the informations are retrieved.
[ "Retrieve", "decoded", "information", "to", "authenticate", "to", "Docker", "with", "AWS", "credentials", "." ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/aws-containers/aws-client.js#L213-L233
train
jhipster/generator-jhipster
generators/aws-containers/aws-client.js
_getAuthorizationToken
function _getAuthorizationToken() { return spinner( new Promise((resolve, reject) => ECR.sdk .getAuthorizationToken({}) .promise() .then(data => { if (!_.has(data, 'authorizationData.0')) { reject(new Error('No authorization data found.')); return; } resolve(data.authorizationData[0]); }) ) ); }
javascript
function _getAuthorizationToken() { return spinner( new Promise((resolve, reject) => ECR.sdk .getAuthorizationToken({}) .promise() .then(data => { if (!_.has(data, 'authorizationData.0')) { reject(new Error('No authorization data found.')); return; } resolve(data.authorizationData[0]); }) ) ); }
[ "function", "_getAuthorizationToken", "(", ")", "{", "return", "spinner", "(", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "ECR", ".", "sdk", ".", "getAuthorizationToken", "(", "{", "}", ")", ".", "promise", "(", ")", ".", "then", "(", "data", "=>", "{", "if", "(", "!", "_", ".", "has", "(", "data", ",", "'authorizationData.0'", ")", ")", "{", "reject", "(", "new", "Error", "(", "'No authorization data found.'", ")", ")", ";", "return", ";", "}", "resolve", "(", "data", ".", "authorizationData", "[", "0", "]", ")", ";", "}", ")", ")", ")", ";", "}" ]
Fetch Authentication token from AWS to authenticate with Docker @returns {Promise} Returns a promise that resolves when the informations are retrieved. @private
[ "Fetch", "Authentication", "token", "from", "AWS", "to", "authenticate", "with", "Docker" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/aws-containers/aws-client.js#L240-L255
train
jhipster/generator-jhipster
generators/aws-containers/aws-client.js
createS3Bucket
function createS3Bucket(bucketName, region = DEFAULT_REGION) { const createBuckerParams = { Bucket: bucketName }; return spinner( new Promise((resolve, reject) => s3 .headBucket({ Bucket: bucketName }) .promise() .catch(error => { if (error.code !== 'NotFound') { reject( new Error( `The S3 Bucket ${chalk.bold(bucketName)} in region ${chalk.bold( region )} already exists and you don't have access to it. Error code: ${chalk.bold(error.code)}` ) ); } }) .then(() => s3 .createBucket(createBuckerParams) .promise() .then(resolve) .catch(error => reject( new Error( `There was an error during the creation of the S3 Bucket ${chalk.bold( bucketName )} in region ${chalk.bold(region)}` ) ) ) ) ) ); }
javascript
function createS3Bucket(bucketName, region = DEFAULT_REGION) { const createBuckerParams = { Bucket: bucketName }; return spinner( new Promise((resolve, reject) => s3 .headBucket({ Bucket: bucketName }) .promise() .catch(error => { if (error.code !== 'NotFound') { reject( new Error( `The S3 Bucket ${chalk.bold(bucketName)} in region ${chalk.bold( region )} already exists and you don't have access to it. Error code: ${chalk.bold(error.code)}` ) ); } }) .then(() => s3 .createBucket(createBuckerParams) .promise() .then(resolve) .catch(error => reject( new Error( `There was an error during the creation of the S3 Bucket ${chalk.bold( bucketName )} in region ${chalk.bold(region)}` ) ) ) ) ) ); }
[ "function", "createS3Bucket", "(", "bucketName", ",", "region", "=", "DEFAULT_REGION", ")", "{", "const", "createBuckerParams", "=", "{", "Bucket", ":", "bucketName", "}", ";", "return", "spinner", "(", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "s3", ".", "headBucket", "(", "{", "Bucket", ":", "bucketName", "}", ")", ".", "promise", "(", ")", ".", "catch", "(", "error", "=>", "{", "if", "(", "error", ".", "code", "!==", "'NotFound'", ")", "{", "reject", "(", "new", "Error", "(", "`", "${", "chalk", ".", "bold", "(", "bucketName", ")", "}", "${", "chalk", ".", "bold", "(", "region", ")", "}", "${", "chalk", ".", "bold", "(", "error", ".", "code", ")", "}", "`", ")", ")", ";", "}", "}", ")", ".", "then", "(", "(", ")", "=>", "s3", ".", "createBucket", "(", "createBuckerParams", ")", ".", "promise", "(", ")", ".", "then", "(", "resolve", ")", ".", "catch", "(", "error", "=>", "reject", "(", "new", "Error", "(", "`", "${", "chalk", ".", "bold", "(", "bucketName", ")", "}", "${", "chalk", ".", "bold", "(", "region", ")", "}", "`", ")", ")", ")", ")", ")", ")", ";", "}" ]
Create a S3 Bucket in said region with said bucketBaseName. the bucketBaseName will be used to create a @param bucketName the name of the bucket to create. @param region the region to create the bucket in. @returns {Promise}
[ "Create", "a", "S3", "Bucket", "in", "said", "region", "with", "said", "bucketBaseName", ".", "the", "bucketBaseName", "will", "be", "used", "to", "create", "a" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/aws-containers/aws-client.js#L264-L303
train
jhipster/generator-jhipster
generators/aws-containers/aws-client.js
uploadTemplate
function uploadTemplate(bucketName, filename, path) { return spinner( new Promise((resolve, reject) => fs.stat(path, (error, stats) => { if (!stats) { reject(new Error(`File ${chalk.bold(path)} not found`)); } const upload = s3.upload( { Bucket: bucketName, Key: filename, Body: fs.createReadStream(path) }, { partSize: Math.max(stats.size, S3_MIN_PART_SIZE), queueSize: 1 } ); let bar; upload.on('httpUploadProgress', evt => { if (!bar && evt.total) { const total = evt.total / 1000000; bar = new ProgressBar('uploading [:bar] :percent :etas', { complete: '=', incomplete: ' ', width: 20, total, clear: true }); } const curr = evt.loaded / 1000000; bar.tick(curr - bar.curr); }); return upload .promise() .then(resolve) .catch(reject); }) ) ); }
javascript
function uploadTemplate(bucketName, filename, path) { return spinner( new Promise((resolve, reject) => fs.stat(path, (error, stats) => { if (!stats) { reject(new Error(`File ${chalk.bold(path)} not found`)); } const upload = s3.upload( { Bucket: bucketName, Key: filename, Body: fs.createReadStream(path) }, { partSize: Math.max(stats.size, S3_MIN_PART_SIZE), queueSize: 1 } ); let bar; upload.on('httpUploadProgress', evt => { if (!bar && evt.total) { const total = evt.total / 1000000; bar = new ProgressBar('uploading [:bar] :percent :etas', { complete: '=', incomplete: ' ', width: 20, total, clear: true }); } const curr = evt.loaded / 1000000; bar.tick(curr - bar.curr); }); return upload .promise() .then(resolve) .catch(reject); }) ) ); }
[ "function", "uploadTemplate", "(", "bucketName", ",", "filename", ",", "path", ")", "{", "return", "spinner", "(", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "fs", ".", "stat", "(", "path", ",", "(", "error", ",", "stats", ")", "=>", "{", "if", "(", "!", "stats", ")", "{", "reject", "(", "new", "Error", "(", "`", "${", "chalk", ".", "bold", "(", "path", ")", "}", "`", ")", ")", ";", "}", "const", "upload", "=", "s3", ".", "upload", "(", "{", "Bucket", ":", "bucketName", ",", "Key", ":", "filename", ",", "Body", ":", "fs", ".", "createReadStream", "(", "path", ")", "}", ",", "{", "partSize", ":", "Math", ".", "max", "(", "stats", ".", "size", ",", "S3_MIN_PART_SIZE", ")", ",", "queueSize", ":", "1", "}", ")", ";", "let", "bar", ";", "upload", ".", "on", "(", "'httpUploadProgress'", ",", "evt", "=>", "{", "if", "(", "!", "bar", "&&", "evt", ".", "total", ")", "{", "const", "total", "=", "evt", ".", "total", "/", "1000000", ";", "bar", "=", "new", "ProgressBar", "(", "'uploading [:bar] :percent :etas'", ",", "{", "complete", ":", "'='", ",", "incomplete", ":", "' '", ",", "width", ":", "20", ",", "total", ",", "clear", ":", "true", "}", ")", ";", "}", "const", "curr", "=", "evt", ".", "loaded", "/", "1000000", ";", "bar", ".", "tick", "(", "curr", "-", "bar", ".", "curr", ")", ";", "}", ")", ";", "return", "upload", ".", "promise", "(", ")", ".", "then", "(", "resolve", ")", ".", "catch", "(", "reject", ")", ";", "}", ")", ")", ")", ";", "}" ]
Upload the template in the S3Bucket @param bucketName S3 Bucket name to upload the template into @param filename Name to give to the file in the Bucket @param path Path to the file @returns {Promise}
[ "Upload", "the", "template", "in", "the", "S3Bucket" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/aws-containers/aws-client.js#L312-L353
train
jhipster/generator-jhipster
generators/docker-prompts.js
askForApplicationType
function askForApplicationType() { if (this.regenerate) return; const done = this.async(); const prompts = [ { type: 'list', name: 'deploymentApplicationType', message: 'Which *type* of application would you like to deploy?', choices: [ { value: 'monolith', name: 'Monolithic application' }, { value: 'microservice', name: 'Microservice application' } ], default: 'monolith' } ]; this.prompt(prompts).then(props => { this.deploymentApplicationType = props.deploymentApplicationType; done(); }); }
javascript
function askForApplicationType() { if (this.regenerate) return; const done = this.async(); const prompts = [ { type: 'list', name: 'deploymentApplicationType', message: 'Which *type* of application would you like to deploy?', choices: [ { value: 'monolith', name: 'Monolithic application' }, { value: 'microservice', name: 'Microservice application' } ], default: 'monolith' } ]; this.prompt(prompts).then(props => { this.deploymentApplicationType = props.deploymentApplicationType; done(); }); }
[ "function", "askForApplicationType", "(", ")", "{", "if", "(", "this", ".", "regenerate", ")", "return", ";", "const", "done", "=", "this", ".", "async", "(", ")", ";", "const", "prompts", "=", "[", "{", "type", ":", "'list'", ",", "name", ":", "'deploymentApplicationType'", ",", "message", ":", "'Which *type* of application would you like to deploy?'", ",", "choices", ":", "[", "{", "value", ":", "'monolith'", ",", "name", ":", "'Monolithic application'", "}", ",", "{", "value", ":", "'microservice'", ",", "name", ":", "'Microservice application'", "}", "]", ",", "default", ":", "'monolith'", "}", "]", ";", "this", ".", "prompt", "(", "prompts", ")", ".", "then", "(", "props", "=>", "{", "this", ".", "deploymentApplicationType", "=", "props", ".", "deploymentApplicationType", ";", "done", "(", ")", ";", "}", ")", ";", "}" ]
Ask For Application Type
[ "Ask", "For", "Application", "Type" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/docker-prompts.js#L42-L70
train
jhipster/generator-jhipster
generators/docker-prompts.js
askForPath
function askForPath() { if (this.regenerate) return; const done = this.async(); const deploymentApplicationType = this.deploymentApplicationType; let messageAskForPath; if (deploymentApplicationType === 'monolith') { messageAskForPath = 'Enter the root directory where your applications are located'; } else { messageAskForPath = 'Enter the root directory where your gateway(s) and microservices are located'; } const prompts = [ { type: 'input', name: 'directoryPath', message: messageAskForPath, default: this.directoryPath || '../', validate: input => { const path = this.destinationPath(input); if (shelljs.test('-d', path)) { const appsFolders = getAppFolders.call(this, input, deploymentApplicationType); if (appsFolders.length === 0) { return deploymentApplicationType === 'monolith' ? `No monolith found in ${path}` : `No microservice or gateway found in ${path}`; } return true; } return `${path} is not a directory or doesn't exist`; } } ]; this.prompt(prompts).then(props => { this.directoryPath = props.directoryPath; // Patch the path if there is no trailing "/" if (!this.directoryPath.endsWith('/')) { this.log(chalk.yellow(`The path "${this.directoryPath}" does not end with a trailing "/", adding it anyway.`)); this.directoryPath += '/'; } this.appsFolders = getAppFolders.call(this, this.directoryPath, deploymentApplicationType); // Removing registry from appsFolders, using reverse for loop for (let i = this.appsFolders.length - 1; i >= 0; i--) { if (this.appsFolders[i] === 'jhipster-registry' || this.appsFolders[i] === 'registry') { this.appsFolders.splice(i, 1); } } this.log(chalk.green(`${this.appsFolders.length} applications found at ${this.destinationPath(this.directoryPath)}\n`)); done(); }); }
javascript
function askForPath() { if (this.regenerate) return; const done = this.async(); const deploymentApplicationType = this.deploymentApplicationType; let messageAskForPath; if (deploymentApplicationType === 'monolith') { messageAskForPath = 'Enter the root directory where your applications are located'; } else { messageAskForPath = 'Enter the root directory where your gateway(s) and microservices are located'; } const prompts = [ { type: 'input', name: 'directoryPath', message: messageAskForPath, default: this.directoryPath || '../', validate: input => { const path = this.destinationPath(input); if (shelljs.test('-d', path)) { const appsFolders = getAppFolders.call(this, input, deploymentApplicationType); if (appsFolders.length === 0) { return deploymentApplicationType === 'monolith' ? `No monolith found in ${path}` : `No microservice or gateway found in ${path}`; } return true; } return `${path} is not a directory or doesn't exist`; } } ]; this.prompt(prompts).then(props => { this.directoryPath = props.directoryPath; // Patch the path if there is no trailing "/" if (!this.directoryPath.endsWith('/')) { this.log(chalk.yellow(`The path "${this.directoryPath}" does not end with a trailing "/", adding it anyway.`)); this.directoryPath += '/'; } this.appsFolders = getAppFolders.call(this, this.directoryPath, deploymentApplicationType); // Removing registry from appsFolders, using reverse for loop for (let i = this.appsFolders.length - 1; i >= 0; i--) { if (this.appsFolders[i] === 'jhipster-registry' || this.appsFolders[i] === 'registry') { this.appsFolders.splice(i, 1); } } this.log(chalk.green(`${this.appsFolders.length} applications found at ${this.destinationPath(this.directoryPath)}\n`)); done(); }); }
[ "function", "askForPath", "(", ")", "{", "if", "(", "this", ".", "regenerate", ")", "return", ";", "const", "done", "=", "this", ".", "async", "(", ")", ";", "const", "deploymentApplicationType", "=", "this", ".", "deploymentApplicationType", ";", "let", "messageAskForPath", ";", "if", "(", "deploymentApplicationType", "===", "'monolith'", ")", "{", "messageAskForPath", "=", "'Enter the root directory where your applications are located'", ";", "}", "else", "{", "messageAskForPath", "=", "'Enter the root directory where your gateway(s) and microservices are located'", ";", "}", "const", "prompts", "=", "[", "{", "type", ":", "'input'", ",", "name", ":", "'directoryPath'", ",", "message", ":", "messageAskForPath", ",", "default", ":", "this", ".", "directoryPath", "||", "'../'", ",", "validate", ":", "input", "=>", "{", "const", "path", "=", "this", ".", "destinationPath", "(", "input", ")", ";", "if", "(", "shelljs", ".", "test", "(", "'-d'", ",", "path", ")", ")", "{", "const", "appsFolders", "=", "getAppFolders", ".", "call", "(", "this", ",", "input", ",", "deploymentApplicationType", ")", ";", "if", "(", "appsFolders", ".", "length", "===", "0", ")", "{", "return", "deploymentApplicationType", "===", "'monolith'", "?", "`", "${", "path", "}", "`", ":", "`", "${", "path", "}", "`", ";", "}", "return", "true", ";", "}", "return", "`", "${", "path", "}", "`", ";", "}", "}", "]", ";", "this", ".", "prompt", "(", "prompts", ")", ".", "then", "(", "props", "=>", "{", "this", ".", "directoryPath", "=", "props", ".", "directoryPath", ";", "if", "(", "!", "this", ".", "directoryPath", ".", "endsWith", "(", "'/'", ")", ")", "{", "this", ".", "log", "(", "chalk", ".", "yellow", "(", "`", "${", "this", ".", "directoryPath", "}", "`", ")", ")", ";", "this", ".", "directoryPath", "+=", "'/'", ";", "}", "this", ".", "appsFolders", "=", "getAppFolders", ".", "call", "(", "this", ",", "this", ".", "directoryPath", ",", "deploymentApplicationType", ")", ";", "for", "(", "let", "i", "=", "this", ".", "appsFolders", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "if", "(", "this", ".", "appsFolders", "[", "i", "]", "===", "'jhipster-registry'", "||", "this", ".", "appsFolders", "[", "i", "]", "===", "'registry'", ")", "{", "this", ".", "appsFolders", ".", "splice", "(", "i", ",", "1", ")", ";", "}", "}", "this", ".", "log", "(", "chalk", ".", "green", "(", "`", "${", "this", ".", "appsFolders", ".", "length", "}", "${", "this", ".", "destinationPath", "(", "this", ".", "directoryPath", ")", "}", "\\n", "`", ")", ")", ";", "done", "(", ")", ";", "}", ")", ";", "}" ]
Ask For Path
[ "Ask", "For", "Path" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/docker-prompts.js#L108-L163
train
jhipster/generator-jhipster
generators/docker-prompts.js
askForApps
function askForApps() { if (this.regenerate) return; const done = this.async(); const messageAskForApps = 'Which applications do you want to include in your configuration?'; const prompts = [ { type: 'checkbox', name: 'chosenApps', message: messageAskForApps, choices: this.appsFolders, default: this.defaultAppsFolders, validate: input => (input.length === 0 ? 'Please choose at least one application' : true) } ]; this.prompt(prompts).then(props => { this.appsFolders = props.chosenApps; loadConfigs.call(this); done(); }); }
javascript
function askForApps() { if (this.regenerate) return; const done = this.async(); const messageAskForApps = 'Which applications do you want to include in your configuration?'; const prompts = [ { type: 'checkbox', name: 'chosenApps', message: messageAskForApps, choices: this.appsFolders, default: this.defaultAppsFolders, validate: input => (input.length === 0 ? 'Please choose at least one application' : true) } ]; this.prompt(prompts).then(props => { this.appsFolders = props.chosenApps; loadConfigs.call(this); done(); }); }
[ "function", "askForApps", "(", ")", "{", "if", "(", "this", ".", "regenerate", ")", "return", ";", "const", "done", "=", "this", ".", "async", "(", ")", ";", "const", "messageAskForApps", "=", "'Which applications do you want to include in your configuration?'", ";", "const", "prompts", "=", "[", "{", "type", ":", "'checkbox'", ",", "name", ":", "'chosenApps'", ",", "message", ":", "messageAskForApps", ",", "choices", ":", "this", ".", "appsFolders", ",", "default", ":", "this", ".", "defaultAppsFolders", ",", "validate", ":", "input", "=>", "(", "input", ".", "length", "===", "0", "?", "'Please choose at least one application'", ":", "true", ")", "}", "]", ";", "this", ".", "prompt", "(", "prompts", ")", ".", "then", "(", "props", "=>", "{", "this", ".", "appsFolders", "=", "props", ".", "chosenApps", ";", "loadConfigs", ".", "call", "(", "this", ")", ";", "done", "(", ")", ";", "}", ")", ";", "}" ]
Ask For Apps
[ "Ask", "For", "Apps" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/docker-prompts.js#L168-L191
train
jhipster/generator-jhipster
generators/docker-prompts.js
askForClustersMode
function askForClustersMode() { if (this.regenerate) return; const clusteredDbApps = []; this.appConfigs.forEach((appConfig, index) => { if (appConfig.prodDatabaseType === 'mongodb' || appConfig.prodDatabaseType === 'couchbase') { clusteredDbApps.push(this.appsFolders[index]); } }); if (clusteredDbApps.length === 0) return; const done = this.async(); const prompts = [ { type: 'checkbox', name: 'clusteredDbApps', message: 'Which applications do you want to use with clustered databases (only available with MongoDB and Couchbase)?', choices: clusteredDbApps, default: this.clusteredDbApps } ]; this.prompt(prompts).then(props => { this.clusteredDbApps = props.clusteredDbApps; setClusteredApps.call(this); done(); }); }
javascript
function askForClustersMode() { if (this.regenerate) return; const clusteredDbApps = []; this.appConfigs.forEach((appConfig, index) => { if (appConfig.prodDatabaseType === 'mongodb' || appConfig.prodDatabaseType === 'couchbase') { clusteredDbApps.push(this.appsFolders[index]); } }); if (clusteredDbApps.length === 0) return; const done = this.async(); const prompts = [ { type: 'checkbox', name: 'clusteredDbApps', message: 'Which applications do you want to use with clustered databases (only available with MongoDB and Couchbase)?', choices: clusteredDbApps, default: this.clusteredDbApps } ]; this.prompt(prompts).then(props => { this.clusteredDbApps = props.clusteredDbApps; setClusteredApps.call(this); done(); }); }
[ "function", "askForClustersMode", "(", ")", "{", "if", "(", "this", ".", "regenerate", ")", "return", ";", "const", "clusteredDbApps", "=", "[", "]", ";", "this", ".", "appConfigs", ".", "forEach", "(", "(", "appConfig", ",", "index", ")", "=>", "{", "if", "(", "appConfig", ".", "prodDatabaseType", "===", "'mongodb'", "||", "appConfig", ".", "prodDatabaseType", "===", "'couchbase'", ")", "{", "clusteredDbApps", ".", "push", "(", "this", ".", "appsFolders", "[", "index", "]", ")", ";", "}", "}", ")", ";", "if", "(", "clusteredDbApps", ".", "length", "===", "0", ")", "return", ";", "const", "done", "=", "this", ".", "async", "(", ")", ";", "const", "prompts", "=", "[", "{", "type", ":", "'checkbox'", ",", "name", ":", "'clusteredDbApps'", ",", "message", ":", "'Which applications do you want to use with clustered databases (only available with MongoDB and Couchbase)?'", ",", "choices", ":", "clusteredDbApps", ",", "default", ":", "this", ".", "clusteredDbApps", "}", "]", ";", "this", ".", "prompt", "(", "prompts", ")", ".", "then", "(", "props", "=>", "{", "this", ".", "clusteredDbApps", "=", "props", ".", "clusteredDbApps", ";", "setClusteredApps", ".", "call", "(", "this", ")", ";", "done", "(", ")", ";", "}", ")", ";", "}" ]
Ask For Clusters Mode
[ "Ask", "For", "Clusters", "Mode" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/docker-prompts.js#L196-L225
train
jhipster/generator-jhipster
generators/docker-prompts.js
askForMonitoring
function askForMonitoring() { if (this.regenerate) return; const done = this.async(); const prompts = [ { type: 'list', name: 'monitoring', message: 'Do you want to setup monitoring for your applications ?', choices: [ { value: 'no', name: 'No' }, { value: 'elk', name: this.deploymentApplicationType === 'monolith' ? 'Yes, for logs and metrics with the JHipster Console (based on ELK)' : 'Yes, for logs and metrics with the JHipster Console (based on ELK and Zipkin)' }, { value: 'prometheus', name: 'Yes, for metrics only with Prometheus' } ], default: this.monitoring ? this.monitoring : 'no' } ]; this.prompt(prompts).then(props => { this.monitoring = props.monitoring; done(); }); }
javascript
function askForMonitoring() { if (this.regenerate) return; const done = this.async(); const prompts = [ { type: 'list', name: 'monitoring', message: 'Do you want to setup monitoring for your applications ?', choices: [ { value: 'no', name: 'No' }, { value: 'elk', name: this.deploymentApplicationType === 'monolith' ? 'Yes, for logs and metrics with the JHipster Console (based on ELK)' : 'Yes, for logs and metrics with the JHipster Console (based on ELK and Zipkin)' }, { value: 'prometheus', name: 'Yes, for metrics only with Prometheus' } ], default: this.monitoring ? this.monitoring : 'no' } ]; this.prompt(prompts).then(props => { this.monitoring = props.monitoring; done(); }); }
[ "function", "askForMonitoring", "(", ")", "{", "if", "(", "this", ".", "regenerate", ")", "return", ";", "const", "done", "=", "this", ".", "async", "(", ")", ";", "const", "prompts", "=", "[", "{", "type", ":", "'list'", ",", "name", ":", "'monitoring'", ",", "message", ":", "'Do you want to setup monitoring for your applications ?'", ",", "choices", ":", "[", "{", "value", ":", "'no'", ",", "name", ":", "'No'", "}", ",", "{", "value", ":", "'elk'", ",", "name", ":", "this", ".", "deploymentApplicationType", "===", "'monolith'", "?", "'Yes, for logs and metrics with the JHipster Console (based on ELK)'", ":", "'Yes, for logs and metrics with the JHipster Console (based on ELK and Zipkin)'", "}", ",", "{", "value", ":", "'prometheus'", ",", "name", ":", "'Yes, for metrics only with Prometheus'", "}", "]", ",", "default", ":", "this", ".", "monitoring", "?", "this", ".", "monitoring", ":", "'no'", "}", "]", ";", "this", ".", "prompt", "(", "prompts", ")", ".", "then", "(", "props", "=>", "{", "this", ".", "monitoring", "=", "props", ".", "monitoring", ";", "done", "(", ")", ";", "}", ")", ";", "}" ]
Ask For Monitoring
[ "Ask", "For", "Monitoring" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/docker-prompts.js#L230-L265
train
jhipster/generator-jhipster
generators/docker-prompts.js
askForConsoleOptions
function askForConsoleOptions() { if (this.regenerate) return; if (this.monitoring !== 'elk') return; const done = this.async(); const prompts = [ { type: 'checkbox', name: 'consoleOptions', message: 'You have selected the JHipster Console which is based on the ELK stack and additional technologies, which one do you want to use ?', choices: [ { value: 'curator', name: 'Curator, to help you curate and manage your Elasticsearch indices' } ], default: this.monitoring } ]; if (this.deploymentApplicationType === 'microservice') { prompts[0].choices.push({ value: 'zipkin', name: 'Zipkin, for distributed tracing (only compatible with JHipster >= v4.2.0)' }); } this.prompt(prompts).then(props => { this.consoleOptions = props.consoleOptions; done(); }); }
javascript
function askForConsoleOptions() { if (this.regenerate) return; if (this.monitoring !== 'elk') return; const done = this.async(); const prompts = [ { type: 'checkbox', name: 'consoleOptions', message: 'You have selected the JHipster Console which is based on the ELK stack and additional technologies, which one do you want to use ?', choices: [ { value: 'curator', name: 'Curator, to help you curate and manage your Elasticsearch indices' } ], default: this.monitoring } ]; if (this.deploymentApplicationType === 'microservice') { prompts[0].choices.push({ value: 'zipkin', name: 'Zipkin, for distributed tracing (only compatible with JHipster >= v4.2.0)' }); } this.prompt(prompts).then(props => { this.consoleOptions = props.consoleOptions; done(); }); }
[ "function", "askForConsoleOptions", "(", ")", "{", "if", "(", "this", ".", "regenerate", ")", "return", ";", "if", "(", "this", ".", "monitoring", "!==", "'elk'", ")", "return", ";", "const", "done", "=", "this", ".", "async", "(", ")", ";", "const", "prompts", "=", "[", "{", "type", ":", "'checkbox'", ",", "name", ":", "'consoleOptions'", ",", "message", ":", "'You have selected the JHipster Console which is based on the ELK stack and additional technologies, which one do you want to use ?'", ",", "choices", ":", "[", "{", "value", ":", "'curator'", ",", "name", ":", "'Curator, to help you curate and manage your Elasticsearch indices'", "}", "]", ",", "default", ":", "this", ".", "monitoring", "}", "]", ";", "if", "(", "this", ".", "deploymentApplicationType", "===", "'microservice'", ")", "{", "prompts", "[", "0", "]", ".", "choices", ".", "push", "(", "{", "value", ":", "'zipkin'", ",", "name", ":", "'Zipkin, for distributed tracing (only compatible with JHipster >= v4.2.0)'", "}", ")", ";", "}", "this", ".", "prompt", "(", "prompts", ")", ".", "then", "(", "props", "=>", "{", "this", ".", "consoleOptions", "=", "props", ".", "consoleOptions", ";", "done", "(", ")", ";", "}", ")", ";", "}" ]
Ask For Console Options
[ "Ask", "For", "Console", "Options" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/docker-prompts.js#L270-L302
train
jhipster/generator-jhipster
generators/docker-prompts.js
askForServiceDiscovery
function askForServiceDiscovery() { if (this.regenerate) return; const done = this.async(); const serviceDiscoveryEnabledApps = []; this.appConfigs.forEach((appConfig, index) => { if (appConfig.serviceDiscoveryType) { serviceDiscoveryEnabledApps.push({ baseName: appConfig.baseName, serviceDiscoveryType: appConfig.serviceDiscoveryType }); } }); if (serviceDiscoveryEnabledApps.length === 0) { this.serviceDiscoveryType = false; done(); return; } if (serviceDiscoveryEnabledApps.every(app => app.serviceDiscoveryType === 'consul')) { this.serviceDiscoveryType = 'consul'; this.log(chalk.green('Consul detected as the service discovery and configuration provider used by your apps')); done(); } else if (serviceDiscoveryEnabledApps.every(app => app.serviceDiscoveryType === 'eureka')) { this.serviceDiscoveryType = 'eureka'; this.log(chalk.green('JHipster registry detected as the service discovery and configuration provider used by your apps')); done(); } else { this.log(chalk.yellow('Unable to determine the service discovery and configuration provider to use from your apps configuration.')); this.log('Your service discovery enabled apps:'); serviceDiscoveryEnabledApps.forEach(app => { this.log(` -${app.baseName} (${app.serviceDiscoveryType})`); }); const prompts = [ { type: 'list', name: 'serviceDiscoveryType', message: 'Which Service Discovery registry and Configuration server would you like to use ?', choices: [ { value: 'eureka', name: 'JHipster Registry' }, { value: 'consul', name: 'Consul' }, { value: false, name: 'No Service Discovery and Configuration' } ], default: 'eureka' } ]; this.prompt(prompts).then(props => { this.serviceDiscoveryType = props.serviceDiscoveryType; done(); }); } }
javascript
function askForServiceDiscovery() { if (this.regenerate) return; const done = this.async(); const serviceDiscoveryEnabledApps = []; this.appConfigs.forEach((appConfig, index) => { if (appConfig.serviceDiscoveryType) { serviceDiscoveryEnabledApps.push({ baseName: appConfig.baseName, serviceDiscoveryType: appConfig.serviceDiscoveryType }); } }); if (serviceDiscoveryEnabledApps.length === 0) { this.serviceDiscoveryType = false; done(); return; } if (serviceDiscoveryEnabledApps.every(app => app.serviceDiscoveryType === 'consul')) { this.serviceDiscoveryType = 'consul'; this.log(chalk.green('Consul detected as the service discovery and configuration provider used by your apps')); done(); } else if (serviceDiscoveryEnabledApps.every(app => app.serviceDiscoveryType === 'eureka')) { this.serviceDiscoveryType = 'eureka'; this.log(chalk.green('JHipster registry detected as the service discovery and configuration provider used by your apps')); done(); } else { this.log(chalk.yellow('Unable to determine the service discovery and configuration provider to use from your apps configuration.')); this.log('Your service discovery enabled apps:'); serviceDiscoveryEnabledApps.forEach(app => { this.log(` -${app.baseName} (${app.serviceDiscoveryType})`); }); const prompts = [ { type: 'list', name: 'serviceDiscoveryType', message: 'Which Service Discovery registry and Configuration server would you like to use ?', choices: [ { value: 'eureka', name: 'JHipster Registry' }, { value: 'consul', name: 'Consul' }, { value: false, name: 'No Service Discovery and Configuration' } ], default: 'eureka' } ]; this.prompt(prompts).then(props => { this.serviceDiscoveryType = props.serviceDiscoveryType; done(); }); } }
[ "function", "askForServiceDiscovery", "(", ")", "{", "if", "(", "this", ".", "regenerate", ")", "return", ";", "const", "done", "=", "this", ".", "async", "(", ")", ";", "const", "serviceDiscoveryEnabledApps", "=", "[", "]", ";", "this", ".", "appConfigs", ".", "forEach", "(", "(", "appConfig", ",", "index", ")", "=>", "{", "if", "(", "appConfig", ".", "serviceDiscoveryType", ")", "{", "serviceDiscoveryEnabledApps", ".", "push", "(", "{", "baseName", ":", "appConfig", ".", "baseName", ",", "serviceDiscoveryType", ":", "appConfig", ".", "serviceDiscoveryType", "}", ")", ";", "}", "}", ")", ";", "if", "(", "serviceDiscoveryEnabledApps", ".", "length", "===", "0", ")", "{", "this", ".", "serviceDiscoveryType", "=", "false", ";", "done", "(", ")", ";", "return", ";", "}", "if", "(", "serviceDiscoveryEnabledApps", ".", "every", "(", "app", "=>", "app", ".", "serviceDiscoveryType", "===", "'consul'", ")", ")", "{", "this", ".", "serviceDiscoveryType", "=", "'consul'", ";", "this", ".", "log", "(", "chalk", ".", "green", "(", "'Consul detected as the service discovery and configuration provider used by your apps'", ")", ")", ";", "done", "(", ")", ";", "}", "else", "if", "(", "serviceDiscoveryEnabledApps", ".", "every", "(", "app", "=>", "app", ".", "serviceDiscoveryType", "===", "'eureka'", ")", ")", "{", "this", ".", "serviceDiscoveryType", "=", "'eureka'", ";", "this", ".", "log", "(", "chalk", ".", "green", "(", "'JHipster registry detected as the service discovery and configuration provider used by your apps'", ")", ")", ";", "done", "(", ")", ";", "}", "else", "{", "this", ".", "log", "(", "chalk", ".", "yellow", "(", "'Unable to determine the service discovery and configuration provider to use from your apps configuration.'", ")", ")", ";", "this", ".", "log", "(", "'Your service discovery enabled apps:'", ")", ";", "serviceDiscoveryEnabledApps", ".", "forEach", "(", "app", "=>", "{", "this", ".", "log", "(", "`", "${", "app", ".", "baseName", "}", "${", "app", ".", "serviceDiscoveryType", "}", "`", ")", ";", "}", ")", ";", "const", "prompts", "=", "[", "{", "type", ":", "'list'", ",", "name", ":", "'serviceDiscoveryType'", ",", "message", ":", "'Which Service Discovery registry and Configuration server would you like to use ?'", ",", "choices", ":", "[", "{", "value", ":", "'eureka'", ",", "name", ":", "'JHipster Registry'", "}", ",", "{", "value", ":", "'consul'", ",", "name", ":", "'Consul'", "}", ",", "{", "value", ":", "false", ",", "name", ":", "'No Service Discovery and Configuration'", "}", "]", ",", "default", ":", "'eureka'", "}", "]", ";", "this", ".", "prompt", "(", "prompts", ")", ".", "then", "(", "props", "=>", "{", "this", ".", "serviceDiscoveryType", "=", "props", ".", "serviceDiscoveryType", ";", "done", "(", ")", ";", "}", ")", ";", "}", "}" ]
Ask For Service Discovery
[ "Ask", "For", "Service", "Discovery" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/docker-prompts.js#L307-L371
train
jhipster/generator-jhipster
generators/docker-prompts.js
askForAdminPassword
function askForAdminPassword() { if (this.regenerate || this.serviceDiscoveryType !== 'eureka') return; const done = this.async(); const prompts = [ { type: 'input', name: 'adminPassword', message: 'Enter the admin password used to secure the JHipster Registry', default: 'admin', validate: input => (input.length < 5 ? 'The password must have at least 5 characters' : true) } ]; this.prompt(prompts).then(props => { this.adminPassword = props.adminPassword; this.adminPasswordBase64 = getBase64Secret(this.adminPassword); done(); }); }
javascript
function askForAdminPassword() { if (this.regenerate || this.serviceDiscoveryType !== 'eureka') return; const done = this.async(); const prompts = [ { type: 'input', name: 'adminPassword', message: 'Enter the admin password used to secure the JHipster Registry', default: 'admin', validate: input => (input.length < 5 ? 'The password must have at least 5 characters' : true) } ]; this.prompt(prompts).then(props => { this.adminPassword = props.adminPassword; this.adminPasswordBase64 = getBase64Secret(this.adminPassword); done(); }); }
[ "function", "askForAdminPassword", "(", ")", "{", "if", "(", "this", ".", "regenerate", "||", "this", ".", "serviceDiscoveryType", "!==", "'eureka'", ")", "return", ";", "const", "done", "=", "this", ".", "async", "(", ")", ";", "const", "prompts", "=", "[", "{", "type", ":", "'input'", ",", "name", ":", "'adminPassword'", ",", "message", ":", "'Enter the admin password used to secure the JHipster Registry'", ",", "default", ":", "'admin'", ",", "validate", ":", "input", "=>", "(", "input", ".", "length", "<", "5", "?", "'The password must have at least 5 characters'", ":", "true", ")", "}", "]", ";", "this", ".", "prompt", "(", "prompts", ")", ".", "then", "(", "props", "=>", "{", "this", ".", "adminPassword", "=", "props", ".", "adminPassword", ";", "this", ".", "adminPasswordBase64", "=", "getBase64Secret", "(", "this", ".", "adminPassword", ")", ";", "done", "(", ")", ";", "}", ")", ";", "}" ]
Ask For Admin Password
[ "Ask", "For", "Admin", "Password" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/docker-prompts.js#L376-L396
train