Builds the brief module info from file
549568
def getBriefModuleInfoFromFile(fileName):
    """"""
    modInfo = BriefModuleInfo()
    _cdmpyparser.getBriefModuleInfoFromFile(modInfo, fileName)
    modInfo.flush()
    return modInfo
234231
def get_module_doc(module, config=default_config, already_met=None):
    """"""
    # Avoid recursion loops (init)
    if already_met is None:
        already_met = set()

    if config.exclude_module:
        for ex in config.exclude_module:
            if ex.match(module.__name__):
                return None

    # Force load submodules into module's dict
    if hasattr(module, '__path__'):
        subm = [
            modname for importer, modname, ispkg
            in pkgutil.iter_modules(module.__path__)
        ]
        __import__(module.__name__, fromlist=subm)

    # We don't want to include imported items,
    # so we parse the code to blacklist them.

    # Be sure to parse .py and not .pyc file on Python 2.X
    if hasattr(module, '__file__'):
        module_file = module.__file__
    else:
        module_file = inspect.getsourcefile(module)
    path, ext = os.path.splitext(module_file)
    if ext == '.pyc':
        module_file = path + '.py'

    try:
        code = open(module_file).read()
        body = ast.parse(code).body
    except SyntaxError:
        code = open(module_file).read().encode('utf-8')
        body = ast.parse(code).body

    imported = []
    for node in body:
        if isinstance(node, (ast.Import, ast.ImportFrom)):
            imported.extend([n.name for n in node.names])

    nested_doc = []
    module_dict = module.__dict__

    for item in dir(module):
        if item not in imported and item in module_dict.keys():
            # Avoid recursion loops
            if id(item) in already_met:
                continue
            already_met.add(id(item))

            appended = None
            if isinstance(module_dict[item], types.ModuleType):
                appended = get_module_doc(module_dict[item], config, already_met)  # noqa
            elif isinstance(module_dict[item], type):
                appended = get_class_doc(module_dict[item], config)
            elif isinstance(module_dict[item], types.FunctionType):
                appended = get_function_doc(module_dict[item], config)
            if appended is not None:
                nested_doc.append(appended)

    return _doc_object(module, 'module', nested_doc, config)
165740
function buildDocs() {
  return Promise.resolve()
    .then(() => new Promise((resolve, reject) => {
      Metalsmith(__dirname)
        .source('./source/docs')
        .destination('./docs')
        .clean(true)
        .use(Markdown())
        .metadata({
          version: __version
        })
        .use(Layouts({
          engine: 'handlebars',
          directory: './source/layouts',
          rename: false
        }))
        // Update {{version}} in content since it's not processed with Handlebars
        .use((files, metalsmith, done) => {
          Object.keys(files).forEach((key) => {
            let file = files[key];

            file.contents = new Buffer(
              file.contents
                .toString()
                .replace(/\{\{version\}\}/g, __version)
            );
          });

          done();
        })
        .build((err) => {
          if(err) {
            reject(err);
            return;
          }
          console.log(Chalk.green('Docs generated! 📚'));

          resolve();
        });
    }));
}
499418
function buildTree(index, api) {
  const modules = {};

  const dependency = (module, parent) => {
    const filepath = api.resolve(module, parent);
    if (modules[filepath] != null) {
      return modules[filepath];
    }

    const src = api.getFileContents(module, parent, "utf8");
    const basic = api.parser(src);
    const [nestedImports, hasMemory] = parseImports(basic, api);

    const deps = {};

    Object.keys(nestedImports).forEach(mod => {
      if (mod.indexOf(".") === 0) {
        const dep = dependency(mod, filepath);
        deps[mod] = dep;
      }
    });

    const patched = inferImportTypes(basic, deps, api);
    const ast = api.semantics(patched);

    api.validate(ast, {
      lines: src.split("\n"),
      filename: module.split("/").pop(),
    });

    const result = {
      ast,
      deps,
      filepath,
      hasMemory,
    };
    modules[filepath] = result;

    return result;
  };

  const root = dependency(index, null);

  return {
    root,
    modules,
  };
}
1178124
def _build(verbose=False):
    

    if verbose:
        print(
            _format("Building LEX/YACC modules for MOF compiler in: {0}",
                    _tabdir))

    _yacc(verbose)
    _lex(verbose)
422780
function docsBuild(file, info) {
  console.log(`Processing file: ${file}\n`)
  const vueObj = vueDocgen.parse(file)

  let compDataObj = {
    "api": {},
    "version": '',
  }

  // calculate associated component names and paths
  const vueCompName = path.basename(file,'.vue')
  const vueCompDir = path.dirname(file)
  const vueCompFilePath = vueCompDir + path.sep + vueCompName
  const BASE_VERSION = '0.0.0'
  let latestMdDoc = null, latestMdVer = BASE_VERSION

  // Determine version of current raw vue component based on its associated package.json file
  const currentDir = path.dirname(file) + path.sep
  const readmeFilePath = `${currentDir}README.md`
  const examplesFilePath = `${currentDir}EXAMPLES.md`
  const compDataHistoryFilePath = `${currentDir}build${path.sep}component-data.json`
  let compDataHistory = {"name": `${vueCompName}`, "versions": []}
  const currentVer = info.version
  compDataObj.version = currentVer

  // create data objects for component properties, events, methods, and slots
  const apiProm = new Promise((resolve, reject) => { resolve(buildAPIs(vueObj)) })
  .then( api => { 
    console.log(`Completed API data object for ${vueCompName}\n`)
    console.log(`${util.inspect(api)}`)
    Object.assign(compDataObj.api, api) 
  })
  .catch( err => { console.log(`Error while trying to create API objects:\n${err}`) })

  // After all promises complete, add new component data object to history of component
  // If current version is in history array, replace that element with current 
  Promise.all([apiProm])
  .then(() => {
    let currVersionIdx = -1
    currVersionIdx = compDataHistory.versions.findIndex((element) => {
      return element.version === compDataObj.version
    })
    currVersionIdx == -1 ? 
      compDataHistory.versions.unshift(compDataObj) :
      compDataHistory.versions[currVersionIdx] = compDataObj

    return fs.outputJSON(compDataHistoryFilePath, compDataHistory, {spaces: '\t'})
  })
  .catch( err => {
    console.log(`Problem saving component history for ${vueCompName}:\n${err}`)
    process.exit(1)
  })
}
275357
def build_info():
    '''
    
    '''
    ret = {'info': []}
    out = __salt__['cmd.run']('{0} -V'.format(__detect_os()))

    for i in out.splitlines():
        if i.startswith('configure argument'):
            ret['build arguments'] = re.findall(r"(?:[^\s]*'.*')|(?:[^\s]+)", i)[2:]
            continue

        ret['info'].append(i)

    return ret
813900
function makeModule(index) {

		var stored, src, srcPath, relpath;

		// Prepare module
		var module  = new Module({
			 uid:    index
			,req:    []
			,path:   index
			,relpath: null
			,isNodeModule: false
			,isAsyncModule: arequirePath === index
			,arequirePath:  arequirePath
			,index:  index
		});

		if(~module.path.indexOf('/node_modules/')) module.isNodeModule = true;

		relpath = path.relative(process.cwd(), module.path);
		relpath = !/^\./.test(relpath) ? './' + relpath : relpath;
		module.relpath = relpath;

		debug('makeModule for %s', relpath);

		// Check for stored version of this path
		stored = _.find(modules, function(p) {
			return module.path === p.path;
		});
		if(stored) {
			debug('allready stored : return (absolute path match)');
			return stored;
		}

		// Read source
		src           = fs.readFileSync(module.path, 'utf8');
		module.mtime  = fs.statSync(module.path).mtime;
		module.uid    = getUID({src: src, path:module.path, options: options});

		// Check for stored version with same uid
		stored = _.find(modules, function(p) {
			return module.uid  === p.uid;
		});
		if(stored) {
			debug('allready stored : return (md5 hash match)');
			return stored;
		}

		// Save module
		modules.push(module);

		// Do not parse ?
		module.notparsed = _.find(noparse, function(np) {
			if(np instanceof RegExp) {
				return np.test(module.path);
			} else if ('string'   == typeof np) {
				return minimatch(module.path, np);
			} else if ('function' == typeof np) {
				return np(module.path, module);
			} else {
				return false;
			}
		});

		// Parse
		if(module.notparsed) {
			debug('  no parse');
		} else {
			debug('  run parse');
			src = parse(src, module, makeModule, options);
		}

		// Store the module source :
		module.source = src;


		// Return the module object

		debug('end %s', relpath);
		return module;
	}
687567
function optimizeModules () {
			grunt.log.write("Optimizing...");

			var mainModuleOverride = {
				// Specify a callback to be called for writing down app root modules content.
				// The callback wraps modules content into several nested 'require' calls (one for each layer modules)
				onBuildWrite: function (moduleName, modulePath, contents) {
					if (contents.indexOf("require(") < 0) { return contents; }
					if (modules.indexOf(moduleName) < 0) { return contents; }
					var start = "", end = "";
					layers.forEach(function (l) {
						start += "require([\"" + l.name + "\"], function () {\n";
						end += "\n});";
					});
					return contents.replace("require(", start + "require(") + end;
				}
			};
			function writeGenericCss (moduleName, modulePath, content) {
				grunt.verbose.writeln('Combining ' + moduleName + ' into ' + genericCssPath);
				var genericCssContent;
				if (file.exists(genericCssPath)) {
					genericCssContent = file.readFile(genericCssPath);
				}
				genericCssContent = genericCssContent ? genericCssContent + "\n" + content : content;
				file.saveFile(genericCssPath, genericCssContent);
				// remove original css
				file.deleteFile(modulePath);
			}
			// See https://github.com/jrburke/r.js/blob/master/build/example.build.js
			var config = lang.extend({}, requireConfig, {
				isOptimizeStage: true,
				optimize: options.optimizeJs,
				optimizeCss: options.optimizeCss,
				appDir: buildDir,
				dir: outputDir,
				baseUrl: "./",
				logLevel: 2, // WARN
				removeCombined: true,
				//skipDirOptimize: false,
				skipDirOptimize: true,
				keepBuildDir: false,
				locale: options.bundledLocale,
				preserveLicenseComments: options.preserveLicenseComments,
				generateSourceMaps: options.generateSourceMaps,
				writeGenericCss: writeGenericCss,
				// Custom parameter for xcss.js: path from 'generic.css' to baseDir
				genericCssToRootPath: genericCssToRootPath,
				// Pragmas for rjs plugins:
				pragmas: {
					optimize: true,
					build: true
				},
				pragmasOnSave: {
					optimizeSave: true
				},
				modules: [
					// here we'll combine layer modules and app root modules
				]
			});
			if (options.requireConfigOutput) {
				config = lang.extendEx(config, options.requireConfigOutput, {deep: true});
			}

			// Initialize config.modules - root modules to optimize
			// First we're adding "layer modules" (built on the previous step)
			var excludedLayers = options.ignoreModules;
			layers.forEach(function (l) {
				config.modules.push({
					name: l.name,
					exclude: excludedLayers.slice()
				});
				excludedLayers.push(l.name);
			});
			// then add root application modules (main.js and so on)
			modules.forEach(function (m) {
				config.modules.push({
					name: m,
					exclude: excludedLayers,
					override: mainModuleOverride
				});
			});
			// options for particular layers
			if (options.layerOverrides) {
				config.modules.forEach(function (layer) {
					var name = layer.name;
					var overrides = options.layerOverrides[name];
					if (overrides) {
						// convert task's format into rjs format:
						if (overrides.optimizeJs) {
							overrides.optimize = overrides.optimizeJs;
						}
						if (layer.override) {
							layer.override = lang.extendEx(layer.override, overrides, {deep: true});
						} else {
							layer.override = overrides;
						}
					}
				});
			}

			requirejs.optimize(
				config,
				lang.safeCallback(optimizeBootModules),
				lang.errorCallback
			);
		}
180040
def _build_module_list(source_module, index_filename, ignore_modules):
    ''''''
    out = []
    dirs_with_init = set()
    module_prefix = '' if source_module == '.' else source_module

    for root, _, filenames in walk('.'):
        root = root[2:]
        module_root = root.replace('/', '.')
        file_names = [filename[:-3] for filename in filenames if filename.endswith('.py')]

        for filename in file_names:
            if filename == '__init__':
                dirs_with_init.add(root)
                module_name = '.'.join([module_prefix, module_root]) if module_root else source_module
            elif not root:
                module_name = '.'.join([module_prefix, filename])
            else:
                module_name = '.'.join([module_prefix, root.replace('/', '.'), filename])

            if module_name.startswith('.'):
                module_name = module_name[1:]

            if module_name in ignore_modules:
                print 'Ignored file: {}{}.py'.format('{}/'.format(root), filename)
                continue

            if root and root not in dirs_with_init:
                print 'No __init__.py, skipping: {}{}.py'.format('{}/'.format(root), filename)
                continue

            source_name = '{}.py'.format(filename)
            if root:
                source_name = '{}/{}'.format(root, source_name)

            if filename == '__init__':
                output_name = '{}.md'.format(index_filename)
            else:
                output_name = '{}.md'.format(filename)
            if root:
                output_name = '{}/{}'.format(root, output_name)

            out.append({
                'directory': root,
                'file': filename,
                'module': module_name,
                'output': output_name,
                'source': source_name
            })

    return out
239809
function(str){
    var match = str.split(':');

    var module_id = match[0];
    var module_instance = match[1];

    var instance = [];

    if(this.sid && this.options.instance_through) instance.push(this.sid);
    if(this.instance && this.options.instance_through) instance.push(this.instance);
    if(module_instance) instance.push(module_instance);

    var info = {
      filename: mid.path(module_id, this.options),
      instance: instance.join('-')
    };

    return info;
  }
271715
def create_module_file(package, module, opts):
    """"""
    if not opts.noheadings:
        text = format_heading(1, '%s module' % module)
    else:
        text = ''
    # text += format_heading(2, ':mod:`%s` Module' % module)
    text += format_directive(module, package)
    write_file(makename(package, module), text, opts)
1060304
def string_build(self, data, modname="", path=None):
        """"""
        module = self._data_build(data, modname, path)
        module.file_bytes = data.encode("utf-8")
        return self._post_build(module, "utf-8")
460315
function parseModule(fileInfo) {

    var moduleName = file2modulename(fileInfo.relativePath);
    var sourceFile = new SourceFile(moduleName, fileInfo.content);
    var comments = [];
    var moduleTree;
    var parser = new Parser(sourceFile);

    // Configure the parser
    parser.handleComment = function(range) {
      comments.push({ range: range });
    };
    traceurOptions.setFromObject(service.traceurOptions);

    try {
      // Parse the file as a module, attaching the comments
      moduleTree = parser.parseModule();
      attachComments(moduleTree, comments);
    } catch(ex) {
      // HACK: sometime traceur crashes for various reasons including
      // Not Yet Implemented (NYI)!
      log.error(ex.stack);
      moduleTree = {};
    }
    log.debug(moduleName);
    moduleTree.moduleName = moduleName;

    // We return the module AST but also a collection of all the comments
    // since it can be helpful to iterate through them without having to
    // traverse the AST again
    return {
      moduleTree: moduleTree,
      comments: comments
    };
  }
206704
def build_from_info(cls, info):
        
        info = deepcopy(info)
        terms = []
        for term_info in info['terms']:
            terms.append(Term.build_from_info(term_info))
        return cls(*terms)
215592
def build_specfile_filesection(spec, files):
    
    str  = '%files\n'

    if 'X_RPM_DEFATTR' not in spec:
        spec['X_RPM_DEFATTR'] = '(-,root,root)'

    str = str + '%%defattr %s\n' % spec['X_RPM_DEFATTR']

    supported_tags = {
        'PACKAGING_CONFIG'           : '%%config %s',
        'PACKAGING_CONFIG_NOREPLACE' : '%%config(noreplace) %s',
        'PACKAGING_DOC'              : '%%doc %s',
        'PACKAGING_UNIX_ATTR'        : '%%attr %s',
        'PACKAGING_LANG_'            : '%%lang(%s) %s',
        'PACKAGING_X_RPM_VERIFY'     : '%%verify %s',
        'PACKAGING_X_RPM_DIR'        : '%%dir %s',
        'PACKAGING_X_RPM_DOCDIR'     : '%%docdir %s',
        'PACKAGING_X_RPM_GHOST'      : '%%ghost %s', }

    for file in files:
        # build the tagset
        tags = {}
        for k in list(supported_tags.keys()):
            try:
                v = file.GetTag(k)
                if v:
                    tags[k] = v
            except AttributeError:
                pass

        # compile the tagset
        str = str + SimpleTagCompiler(supported_tags, mandatory=0).compile( tags )

        str = str + ' '
        str = str + file.GetTag('PACKAGING_INSTALL_LOCATION')
        str = str + '\n\n'

    return str
884491
def build_napalm_ansible_module_docs(app):
    """"""

    # Add script to clone napalm-ansible repo
    status = subprocess.call(
        "./build-ansible-module-docs.sh", stdout=sys.stdout, stderr=sys.stderr
    )

    if status != 0:
        print("Something bad happened when processing the Ansible modules.")
        sys.exit(-1)

    env = Environment(loader=FileSystemLoader("."))

    modules_dir = "./integrations/ansible/modules/source"
    module_files = glob("{0}/*.json".format(modules_dir))
    for module_file in module_files:
        with open(module_file, "r") as f:
            module = module_file.split("/")[-1].split(".")[0]
            data = json.loads(f.read())
            data["name"] = module

        module_dir = "./integrations/ansible/modules/{0}".format(module)

        try:
            os.stat(module_dir)
        except Exception:
            os.mkdir(module_dir)

        template_file = env.get_template("ansible-module.j2")
        rendered_template = template_file.render(**data)

        with open("{0}/index.rst".format(module_dir), "w") as f:
            f.write(rendered_template)