var includeFiles = extns.map(function(extn) { if (options.includeSubdirs) { return path.join(options.jadeDir, '**', extn); } else { return path.join(options.jadeDir, extn); } });
.each(function(doc) { if (doc.docType === 'directive') { //dash-case for directives doc.humanName = doc.name.replace(/([A-Z])/g, function($1) { return '-'+$1.toLowerCase(); }); } else if (doc.docType === 'readme') { doc.content = doc.content.replace(/<code>/g, '<code ng-non-bindable>'); doc.humanName = component.name; } else { doc.humanName = doc.name; } var repository = config.get('buildConfig').repository; doc.githubUrl = repository + '/tree/master/' + path.relative(config.basePath, doc.file); doc.githubEditUrl = repository + '/edit/master/' + path.relative(config.basePath, doc.file); doc.url = path.join(component.url, doc.docType, doc.name); doc.outputPath = path.join( _.template(docOutputFolder, { component: component, doc: doc }), 'index.html' ); renderedDocs.push(doc); component.docs.push(doc); })
var Installer = function(conf){ var c = ['jquery','angular','angular-animate', 'angular-resource','angular-touch','angular-cookies', 'angular-route','angular-sanitize','angular-aria', 'bootstrap', 'open-sans-fontface','google-code-prettify', 'font-awesome', 'lunr.js','marked']; this.config = { outputFolder:conf.outputFolder, cssFolder:path.join(conf.outputFolder,'css'), jsFolder:path.join(conf.outputFolder,'js'), fontsFolder:path.join(conf.outputFolder,'fonts'), fontFolder:path.join(conf.outputFolder,'font'), imagesFolder:path.join(conf.outputFolder,'images'), localFolder:path.resolve(__dirname,'../../client'), userJs:conf.defaultDeployment?(conf.defaultDeployment.scripts ||[]):[], userFonts:conf.defaultDeployment?(conf.defaultDeployment.fonts ||[]):[], userCss:conf.defaultDeployment?(conf.defaultDeployment.stylesheets ||[]):[], userMisc:conf.defaultDeployment?(conf.defaultDeployment.misc ||[]):[], userIncludeJs:conf.includeJs?(conf.includeJs||[]):[], userIncludeCss:conf.includeCss?(conf.includeCss||[]):[] }; this.config.packages = (conf && conf.packages)? [].concat(conf.packages,c):c; };
var gpaths = config.files.map(function(fileName) { fileName = fileName.trim(); if (fileName.substr(0,1) == '!') { return "!" + path.join(basePath, fileName.substr(1)); } else { return path.join(basePath, fileName); } });
let gpaths = json.files.map((fileName) => { fileName = fileName.trim(); if (fileName.substr(0, 1) === '!') { return '!' + path.join(exampleDirName, fileName.substr(1)); } else { return path.join(exampleDirName, fileName); } });
options.styles = _.map(options.styles, function(file) { var fileName = path.normalize(file); if (/^((https?:)?\/\/)/.test(file)) { return file; } else { fstreams.push(streamFile(file, path.join('css', path.dirname(fileName)), fakeDest)); return path.join('css', fileName); } });
.config(function(readFilesProcessor, writeFilesProcessor, checkAnchorLinksProcessor) { readFilesProcessor.basePath = path.join(projectPath, 'dist'); readFilesProcessor.sourceFiles = ['angular-material.js']; writeFilesProcessor.outputFolder = path.join(projectPath, 'dist/docs'); // Don't use checkAnchorLinksProcessor checkAnchorLinksProcessor.checkDoc = function() { return false; }; })
var gpaths = config.files.map(function(fileName) { fileName = fileName.trim(); if (fileName.substr(0,1) == '!') { return "!" + path.join(basePath, fileName.substr(1)); } else { includeSpec = includeSpec || /.*\.spec.(ts|js)$/.test(fileName); return path.join(basePath, fileName); } });
create: function(config) { var currentVersion = config.get('currentVersion'); var docsBase = path.join(config.get('basePath'), config.get('rendering.outputFolder'), 'docs'); var versionDir = path.join(docsBase, currentVersion); // create the folders for the current version mkdirp.sync(versionDir); }
function getLinkInfoImpl(url, title, currentDoc) { var linkInfo = {url: url, type: 'url', valid: true, title: title || url}; if (!url) { throw new Error('Invalid url'); } var docs = getDocFromAlias(url, currentDoc); // Give each disambiguator a chance to reduce the number of ambiguous docs docs = getLinkInfoImpl.disambiguators.reduce(function(docs, disambiguator) { return disambiguator(url, title, currentDoc, docs); }, docs); if (!getLinkInfoImpl.useFirstAmbiguousLink && docs.length > 1) { linkInfo.valid = false; linkInfo.errorType = 'ambiguous'; linkInfo.error = 'Ambiguous link: "' + url + '".\n' + docs.reduce(function(msg, doc) { return msg + '\n "' + doc.id + '" (' + doc.docType + ') : (' + doc.path + ' / ' + doc.fileInfo.relativePath + ')'; }, 'Matching docs: '); } else if (docs.length >= 1) { linkInfo.url = docs[0].path; linkInfo.title = title || encodeCodeBlock(docs[0].name, true); linkInfo.type = 'doc'; if (getLinkInfoImpl.relativeLinks && currentDoc && currentDoc.path) { var currentFolder = path.dirname(currentDoc.path); var docFolder = path.dirname(linkInfo.url); var relativeFolder = path.relative(path.join('/', currentFolder), path.join('/', docFolder)); linkInfo.url = path.join(relativeFolder, path.basename(linkInfo.url)); log.debug(currentDoc.path, docs[0].path, linkInfo.url); } } else if (url.indexOf('#') > 0) { var pathAndHash = url.split('#'); linkInfo = getLinkInfoImpl(pathAndHash[0], title, currentDoc); linkInfo.url = linkInfo.url + '#' + pathAndHash[1]; return linkInfo; } else if (url.indexOf('/') === -1 && url.indexOf('#') !== 0) { linkInfo.valid = false; linkInfo.errorType = 'missing'; linkInfo.error = 'Invalid link (does not match any doc): "' + url + '"'; } else { linkInfo.title = title || ((url.indexOf('#') === 0) ? url.substring(1) : path.basename(url, '.html')); } return linkInfo; };
_.each(jsPaths, function(jsPath){ var libPath = path.join(nodeModules, jsPath), flattenedLibPath = path.join(flattenedNodeModules, jsPath); if (fs.existsSync(libPath)) { defaultScripts.push(libPath); } else if (fs.existsSync(flattenedLibPath)) { defaultScripts.push(flattenedLibPath); } else { console.error('Could not find ' + jsPath); } });
reader.docs.forEach(function(doc){ // this hack is here because on OSX angular.module and angular.Module map to the same file. var id = doc.id.replace('angular.Module', 'angular.IModule').replace(':', '.'), file = path.join(fakeDest, 'partials', doc.section, id + '.html'), dir = path.join(fakeDest, 'partials', doc.section); docsStream.push(new File({ base: fakeDest, cwd: fakeDest, path: file, contents: new Buffer(doc.html(), 'utf8') })); });
process: function(doc, originatingDoc, title) { var url; if (doc && doc.path) { title = title || doc.name; if (originatingDoc && originatingDoc.path) { url = path.relative(path.join('/', originatingDoc.path), path.join('/', doc.path)); } else { url = doc.path; } return '<a href="' + url + '">' + title + '</a>'; } else { return doc; } }
return function getLinkInfoImpl(url, title, currentDoc) { var linkInfo = { url: url, type: 'url', valid: true, title: title || url }; if ( !url ) { throw new Error('Invalid url'); } var docs = getDocFromAlias(url, currentDoc); if ( docs.length > 1 ) { linkInfo.valid = false; linkInfo.error = 'Ambiguous link: "' + url + '".\n' + docs.reduce(function(msg, doc) { return msg + '\n "' + doc.id + '" ('+ doc.docType + ') : (' + doc.area + ')'; }, 'Matching docs: '); } else if ( docs.length === 1 ) { linkInfo.url = docs[0].path; linkInfo.title = title || encodeCodeBlock(docs[0].name, true); linkInfo.type = 'doc'; if ( getLinkInfoImpl.relativeLinks && currentDoc && currentDoc.path ) { linkInfo.url = path.relative(path.join('/', currentDoc.path), path.join('/', linkInfo.url)); } } else if ( url.indexOf('#') > 0 ) { var pathAndHash = url.split('#'); linkInfo = getLinkInfoImpl(pathAndHash[0], title, currentDoc); linkInfo.url = linkInfo.url + '#' + pathAndHash[1]; return linkInfo; } else if ( url.indexOf('/') === -1 && url.indexOf('#') !== 0 ) { linkInfo.valid = false; linkInfo.error = 'Invalid link (does not match any doc): "' + url + '"'; } else { linkInfo.title = title || (( url.indexOf('#') === 0 ) ? url.substring(1) : path.basename(url, '.html')); } return linkInfo; };
grunt.registerTask('update-bower-json', function () { var currentTag = semver.clean( util.getVersion() ); var taggedReleaseDir = path.join(path.resolve(process.cwd()), 'dist', 'release', currentTag); // Get the list of files from the release directory var releaseFiles = fs.readdirSync(taggedReleaseDir) // Filter out the bower.json and package.json file, if it's there already .filter(function (f) { return !/^bower\.json$/.test(f) && !/^package\.json$/.test(f); }); // Copy a README file copyIntoRelease(taggedReleaseDir, 'misc/publish/README.md'); // Copy a CHANGELOG file copyIntoRelease(taggedReleaseDir, 'CHANGELOG.md'); // Copy a index.js file copyIntoRelease(taggedReleaseDir, 'misc/publish/index.js'); var bowerJsonFile = path.join(taggedReleaseDir, 'bower.json'); var pkgJsonFile = path.join(taggedReleaseDir, 'package.json'); var json = { 'name': 'angular-ui-grid', 'description': pkg.description, 'main': bwr.main, 'ignore': [], 'dependencies': { 'angular': '>=1.4.0 1.7.x' }, 'repository': pkg.repository, 'homepage': 'http://ui-grid.info', 'bugs': { url : 'https://github.com/angular-ui/ui-grid/issues' }, 'keywords': pkg.keywords, 'license': pkg.license }; fs.writeFileSync(bowerJsonFile, JSON.stringify(json, null, 2)); // For package.json json.version = currentTag; json.main = pkg.main; json.files = releaseFiles; fs.writeFileSync(pkgJsonFile, JSON.stringify(json, null, 2)); });
function resolveShredOptions(shredOptions) { var DOCS_FOLDER = '../../public/docs'; var so = _.defaults({}, shredOptions, { // read files from any subdir under here examplesDir: path.join(DOCS_FOLDER, "_examples"), // shredded files get copied here with same subdir structure. fragmentsDir: path.join(DOCS_FOLDER, "_fragments"), // whether to include subdirectories when shredding. includeSubdirs: true }); so.examplesDir = path.resolve(so.examplesDir); so.fragmentsDir = path.resolve(so.fragmentsDir); return so; }
exec('git rev-parse --abbrev-ref HEAD', function (error, stdout, stderror) { if (error) { log(colors.yellow(stderror)); log(colors.yellow('Using \'master\' ' + 'branch as branch could not be determined.')); } else { gitBranch = stdout.trim(); } if (argv['include-git-branch']) { var cwd = process.cwd().split('/').pop(); pathPrefix = path.join(cwd, gitBranch) + '/'; outputFolder = path.join(outputFolder, pathPrefix); } cb(); });
getPath: function(doc) { var docPath = path.dirname(doc.fileInfo.relativePath); if (doc.fileInfo.baseName !== 'index') { docPath = path.join(docPath, doc.fileInfo.baseName); } return docPath; },
}).then(function() { var mdOvrPath = path.join(_shredOptions.fragmentsDir, '**/*.ovr.*'); var fileNames = globby.sync([mdOvrPath], { ignore: ["**/node_modules/**"] }); var errs = []; fileNames.forEach(function(fileName) { console.log('comparing: ' + fileName); var origFileName = fileName.replace('.ovr.', '.'); var origSource = fs.readFileSync(origFileName, 'utf8').replace(/\r\n/g, '\n'); var expectedSource = fs.readFileSync(fileName, 'utf8').replace(/\r\n/g, '\n'); var diffs = JsDiff.diffLines(expectedSource, origSource); errs = []; diffs.forEach(function(diff) { if (diff.added) { errs.add(' added: --->' + diff.value); } else if (diff.removed) { errs.add(' removed: -->' + diff.value); } }); if (errs.length) { errs.unshift('File: ' + origFileName + '\n'); } expect(errs.length).toEqual(0, '\n' + errs.join('')); }); done(); }).catch(function(e){
// config has // files: [] - optional array of globs - defaults to all js, ts, html, json, css and md files (with certain files removed) // description: optional string - description of this plunker - defaults to the title in the index.html page. // tags: [] - optional array of strings // main: string - filename of what will become index.html in the plunker - defaults to index.html function buildPlunkerFrom(configFileName, basePath, destPath) { // replace ending 'plnkr.json' with 'plnkr.no-link.html' to create output file name; var outputFileName = configFileName.substr(0, configFileName.length - 'plnkr.json'.length) + 'plnkr.no-link.html'; var altFileName; if (destPath && destPath.length > 0) { var partPath = path.dirname(path.relative(basePath, outputFileName)); var altFileName = path.join(destPath, partPath, path.basename(outputFileName)).replace('.no-link.', '.'); } try { var config = initConfigAndCollectFileNames(configFileName); var postData = createPostData(config); addPlunkerFiles(config, postData); var html = createPlunkerHtml(postData); fs.writeFileSync(outputFileName, html, 'utf-8'); if (altFileName) { var altDirName = path.dirname(altFileName); if (!fs.existsSync(altDirName)) { mkdirp.sync(altDirName); } fs.writeFileSync(altFileName, html, 'utf-8'); } } catch (e) { // if we fail delete the outputFile if it exists because it is an old one. if (existsSync(outputFileName)) { fs.unlinkSync(outputFileName); } if (altFileName && existsSync(altFileName)) { fs.unlinkSync(altFileName); } throw e; } }
gulp.task('demos', function(done) { var demoVersion = argv['demo-version'] || 'nightly'; if (demoVersion != 'nightly' && !semver.valid(demoVersion)) { console.log('Usage: gulp docs --doc-version=(nightly|versionName)'); return process.exit(1); } var config = dgeni.loadConfig(path.join(__dirname, '/config/demos/demos.config.js')); config.set('currentVersion', demoVersion); config.set('dist', buildConfig.dist); config.set( 'rendering.outputFolder', argv.dist ? argv.dist : path.resolve(__dirname, buildConfig.dist, 'ionic-demo') ); dgeni.generator(config)().then(function() { gutil.log('Demos for', gutil.colors.cyan(demoVersion), 'generated!'); gutil.log('Building ionic into demo folder...'); cp.spawn('gulp', [ 'build', IS_RELEASE_BUILD ? '--release' : '--no-release', '--dist=' + config.rendering.outputFolder + '/' + config.rendering.contentsFolder + '/ionic' ]) .on('exit', done); }); });
module.exports = function(config) { config.set('currentVersion', process.env.DOC_VERSION || 'nightly'); config = basePackage(config); config.set('logging.level', 'info'); config.prepend('rendering.templateFolders', [ path.resolve(__dirname, 'templates') ]); config.set('basePath', __dirname); config.set('source.projectPath', '.'); config.set('rendering.outputFolder', '../tmp/ionic-site'); var versionData = require('./generate-versions')(config); config.set('versionData', versionData); config.set('rendering.contentsFolder', path.join('docs', versionData.current.folder)); config.set('processing.api-docs', { outputPath: 'api/${docType}/${name}/index.md', path: 'api/${docType}/${name}', moduleOutputPath: 'api/module/${name}/index.md', modulePath: 'api/module/${name}' }); config.append('rendering.filters', [ require('./filters/capital') ]); config.set('source.files', [ { pattern: 'js/**/*.js', basePath: basePath } ]); config.append('processing.inlineTagDefinitions', [ require('./inline-tag-defs/link') ]); config.append('processing.tagDefinitions', require('./tag-defs')); //Don't conflict with the jekyll tags config.set('rendering.nunjucks.config.tags', { blockStart: '<@', blockEnd: '@>', variableStart: '<$', variableEnd: '$>', commentStart: '<#', commentEnd: '#>' }); config.append('processing.processors', [ require('./processors/latest-version'), require('./processors/keywords'), require('./processors/pages-data'), require('./processors/index-page'), require('./processors/version-data') ]); return config; };
_.forEach(docs, function(doc) { var linkInfo; // Only check specified output files if ( checkDoc(doc) ) { // Make the path to the doc relative to the webRoot var docPath = path.join(webRoot, doc.path); // Parse out all link hrefs, names and ids linkInfo = extractLinks(doc.renderedContent); linkInfo.path = docPath; linkInfo.outputPath = doc.outputPath; allDocs.push(linkInfo); _.forEach(pathVariants, function(pathVariant) { var docPathVariant = docPath + pathVariant; // The straight doc path is a valid reference allValidReferences[docPathVariant] = true; // The path with a trailing hash is valid allValidReferences[docPathVariant + '#'] = true; // The path referencing each name/id in the doc is valid _.forEach(linkInfo.names, function(name) { allValidReferences[docPathVariant + '#' + name] = true; }); }); } });
// globs is an array of globs function zipExamples(sourceDirName, outputDirName) { var gpath = path.join(sourceDirName, '**/*zipconfig.json'); var configFileNames = globby.sync([gpath], { ignore: ['**/node_modules/**'] }); configFileNames.forEach(function(configFileName) { zipExample(configFileName, sourceDirName, outputDirName); }); }
function _insertExampleFragments(enclosedByName, eltId, $, div) { const fragDir = path.join(dartPkgConfigInfo.ngIoDartApiDocPath, '../../../_fragments/_api'); const exList = div.find('p:contains("{@example")'); exList.each((i, elt) => { const text = $(elt).text(); log.debug(`Found example: ${enclosedByName} ${eltId}`, text); const matches = text.match(/{@example\s+([^\s]+)(\s+region=[\'\"]?(\w+)[\'\"]?)?\s*}/); if (!matches) { log.warn(enclosedByName, eltId, 'has an invalidly formed @example tag:', text); return true; } const exRelPath = matches[1]; const region = matches[3]; const dir = path.dirname(exRelPath) const extn = path.extname(exRelPath); const baseName = path.basename(exRelPath, extn); const fileNameNoExt = baseName + (region ? `-${region}` : '') const exFragPath = path.resolve(fragDir, dir, `${fileNameNoExt}${extn}.md`); if (!fs.existsSync(exFragPath)) { log.warn('Fragment not found:', exFragPath); return true; } $(elt).empty(); const md = fs.readFileSync(exFragPath, 'utf8'); const codeElt = _extractAndWrapInCodeTags(md); $(elt).html(codeElt); log.silly('Fragment code in html:', $(elt).html()); }); }
/** * Run Protractor End-to-End Tests for Doc Samples * * Flags * --filter to filter/select _example app subdir names * e.g. --filter=foo // all example apps with 'foo' in their folder names. * * --setup run yarn install, copy boilerplate and update webdriver * e.g. --setup * * --local to use the locally built Angular packages, rather than versions from npm * Must be used in conjunction with --setup as this is when the packages are copied. * e.g. --setup --local * * --shard to shard the specs into groups to allow you to run them in parallel * e.g. --shard=0/2 // the even specs: 0, 2, 4, etc * e.g. --shard=1/2 // the odd specs: 1, 3, 5, etc * e.g. --shard=1/3 // the second of every three specs: 1, 4, 7, etc */ function runE2e() { if (argv.setup) { // Run setup. console.log('runE2e: setup boilerplate'); const installPackagesCommand = `example-use-${argv.local ? 'local' : 'npm'}`; const addBoilerplateCommand = `boilerplate:add${argv.ivy ? ':ivy' : ''}`; shelljs.exec(`yarn ${installPackagesCommand}`, {cwd: AIO_PATH}); shelljs.exec(`yarn ${addBoilerplateCommand}`, {cwd: AIO_PATH}); } const outputFile = path.join(AIO_PATH, './protractor-results.txt'); return Promise.resolve() .then(() => findAndRunE2eTests(argv.filter, outputFile, argv.shard)) .then((status) => { reportStatus(status, outputFile); if (status.failed.length > 0) { return Promise.reject('Some test suites failed'); } }) .catch(function(e) { console.log(e); process.exitCode = 1; }); }
Container.prototype.create = function(id, parent) { if (parent && id[0] == '.') { // resolve relative component ID id = path.join(path.dirname(parent.id), id); } var psource = parent ? this._sources[parent._hs] : undefined; // built-ins switch (id) { case '!container': return new InjectedContainer(this, psource && psource.namespace); } id = this.resolve(id, parent); var spec = this._specs[id]; if (!spec) { // No specification is registered with the given ID. Attempt to register // the specification by loading its corresponding module. this._loadSpec(id); } spec = this._specs[id]; if (!spec) { // After attemting auto-loading, the component ID is still unregistered, // which is a terminal condition. throw new Error('Unable to create object "' + id + '" required by: ' + (parent && parent.id || 'unknown')); } var obj = spec.create(this); this.emit('create', obj, spec); return obj; }
_.forEach(defaultScripts, function (script, i) { var fileName = path.normalize(script).split('/').pop(); if (scriptNames.indexOf(fileName) === -1) { fstreams.push(streamFile(script, 'js', fakeDest)); options.scripts.splice(i, 0, path.join('js', fileName)); } });
Container.prototype.create = function(id, parent) { if (parent && id[0] == '.') { // resolve relative component ID id = path.join(path.dirname(parent.id), id); } // built-ins switch (id) { case '!container': // TODO: Get the source prefix and pass it here. Isolate introspected specs // to the prefix. return new InjectedContainer(this); } id = this.resolve(id, parent && parent.id); var spec = this._specs[id]; if (!spec) { // No specification is registered with the given ID. Attempt to register // the specification by loading its corresponding module. this._loadSpec(id); } spec = this._specs[id]; if (!spec) { // After attemting auto-loading, the component ID is still unregistered, // which is a terminal condition. throw new Error("Unable to create object '" + id + "'"); } var obj = spec.create(this); this.emit('create', obj, spec); return obj; }
function apiEntryJadeTemplate(baseHrefDepth, $breadcrumbs, $mainDiv) { const baseHref = path.join(...Array(baseHrefDepth).fill('..')); // TODO/investigate: for some reason $breadcrumbs.html() is missing the <ol></ol>. We add it back in the template below. const breadcrumbs = _indentedEltHtml($breadcrumbs, 6, (line) => !line.match(/^\s*$/)); const mainDivHtml = _indentedEltHtml($mainDiv, 4); // WARNING: since the following is Jade, indentation is significant. const result = ` extends ${baseHref}/../../../_layout-dart-api include ${baseHref}/../_util-fns block head-extra // generated Dart API page template: head-extra //- <base> is required because all the links in dartdoc generated pages are "pseudo-absolute" base(href="${baseHref}") block breadcrumbs // generated Dart API page template: breadcrumbs ol.breadcrumbs.gt-separated.hidden-xs ${breadcrumbs} block main-content // generated Dart API page template: main-content: start div.dart-api-entry-main ${mainDivHtml} // generated Dart API page template: main-content: end `; return result; }