Compile all sources in a given target to object files.
429973
def execute(self):
    """"""

    def is_cc(source):
      _, ext = os.path.splitext(source)
      return ext in self.get_options().cc_extensions

    targets = self.context.targets(self.is_cpp)

    # Compile source files to objects.
    with self.invalidated(targets, invalidate_dependents=True) as invalidation_check:
      obj_mapping = self.context.products.get('objs')
      for vt in invalidation_check.all_vts:
        for source in vt.target.sources_relative_to_buildroot():
          if is_cc(source):
            if not vt.valid:
              with self.context.new_workunit(name='cpp-compile', labels=[WorkUnitLabel.MULTITOOL]):
                # TODO: Parallelise the compilation.
                # TODO: Only recompile source files that have changed since the
                #       object file was last written. Also use the output from
                #       gcc -M to track dependencies on headers.
                self._compile(vt.target, vt.results_dir, source)
            objpath = self._objpath(vt.target, vt.results_dir, source)
            obj_mapping.add(vt.target, vt.results_dir).append(objpath)
752546
def main():
    """"""
    desc = 'Generate files to benchmark'
    parser = argparse.ArgumentParser(description=desc)
    parser.add_argument(
        '--src',
        dest='src_dir',
        default='src',
        help='The directory containing the templates'
    )
    parser.add_argument(
        '--out',
        dest='out_dir',
        default='generated',
        help='The output directory'
    )
    parser.add_argument(
        '--seed',
        dest='seed',
        default='13',
        help='The random seed (to ensure consistent regeneration)'
    )

    args = parser.parse_args()

    random.seed(int(args.seed))

    mkdir_p(args.out_dir)

    for template in templates_in(args.src_dir):
        modes = template.modes()

        n_range = template.range()
        for n_value in n_range:
            base = template.instantiate(n_value)
            for mode in modes:
                write_file(
                    os.path.join(
                        args.out_dir,
                        out_filename(template, n_value, mode)
                    ),
                    mode.convert_from(base)
                )
        write_file(
            os.path.join(args.out_dir, '{0}.json'.format(template.name)),
            json.dumps({
                'files': {
                    n: {
                        m.identifier: out_filename(template, n, m)
                        for m in modes
                    } for n in n_range
                },
                'name': template.name,
                'x_axis_label': template.property('x_axis_label'),
                'desc': template.property('desc'),
                'modes': {m.identifier: m.description() for m in modes}
            })
        )
178506
def compile_protos():
  """"""
  # If there's no makefile, we're likely installing from an sdist,
  # so there's no need to compile the protos (they should be already
  # compiled).
  if not os.path.exists(os.path.join(THIS_DIRECTORY, "makefile.py")):
    return

  # Only compile protobufs if we're inside GRR source tree.
  subprocess.check_call(
      ["python", "makefile.py", "--clean"], cwd=THIS_DIRECTORY)
1244461
def cpp_lib_builder(build_context, target):
    """"""
    yprint(build_context.conf, 'Build CppLib', target)
    workspace_dir = build_context.get_workspace('CppLib', target.name)
    workspace_src_dir = join(workspace_dir, 'src')
    rmtree(workspace_src_dir)
    link_cpp_artifacts(build_context, target, workspace_src_dir, False)
    buildenv_workspace = build_context.conf.host_to_buildenv_path(
        workspace_src_dir)
    objects = compile_cc(
        build_context, target.compiler_config, target.props.in_buildenv,
        get_source_files(target, build_context), workspace_src_dir,
        buildenv_workspace, target.props.cmd_env)
    for obj_file in objects:
        target.artifacts.add(AT.object, obj_file)
1020629
def output_files(self):
        """"""
        for dep in self.subgraph.successors(self.address):
            dep_rule = self.subgraph.node[dep]['target_obj']
            for out_file in dep_rule.output_files:
                yield out_file
60942
def add_targets_to_INSTALLED_FILES(target, source, env):
    
    global _INSTALLED_FILES, _UNIQUE_INSTALLED_FILES
    _INSTALLED_FILES.extend(target)

    _UNIQUE_INSTALLED_FILES = None
    return (target, source)
1094409
public void compile(final CCTask task, final File outputDir, final String[] sourceFiles, String[] args,
      final String[] endArgs, final boolean relentless, final CommandLineCompilerConfiguration config,
      final ProgressMonitor monitor) throws BuildException {
    BuildException exc = null;
    //
    // determine length of executable name and args
    //
    String command = getCommandWithPath(config);
    if (config.isUseCcache()) {
      // Replace the command with "ccache" and push the old compiler
      // command into the args.
      final String compilerCommand = command;
      command = CCACHE_CMD;
      args = ObjectArrays.concat(compilerCommand, args);
    }
    int baseLength = command.length() + args.length + endArgs.length;
    if (this.libtool) {
      baseLength += 8;
    }
    for (final String arg : args) {
      baseLength += arg.length();
    }
    for (final String endArg : endArgs) {
      baseLength += endArg.length();
    }
    if (baseLength > getMaximumCommandLength()) {
      throw new BuildException("Command line is over maximum length without specifying source file");
    }
    //
    // typically either 1 or Integer.MAX_VALUE
    //
    final int maxInputFilesPerCommand = getMaximumInputFilesPerCommand();
    final int argumentCountPerInputFile = getArgumentCountPerInputFile();
    for (int sourceIndex = 0; sourceIndex < sourceFiles.length;) {
      int cmdLength = baseLength;
      int firstFileNextExec;
      for (firstFileNextExec = sourceIndex; firstFileNextExec < sourceFiles.length
          && firstFileNextExec - sourceIndex < maxInputFilesPerCommand; firstFileNextExec++) {
        cmdLength += getTotalArgumentLengthForInputFile(outputDir, sourceFiles[firstFileNextExec]);
        if (cmdLength >= getMaximumCommandLength()) {
          break;
        }
      }
      if (firstFileNextExec == sourceIndex) {
        throw new BuildException("Extremely long file name, can't fit on command line");
      }

      ArrayList<String> commandlinePrefix = new ArrayList<>();
      if (this.libtool) {
        commandlinePrefix.add("libtool");
      }
      if((this.fortifyID !=null) && (!this.fortifyID.equals("")))
      {// If FortifyID attribute was set, run the Fortify framework

        commandlinePrefix.add("sourceanalyzer");
        commandlinePrefix.add("-b");
        commandlinePrefix.add(this.fortifyID);
      }
      commandlinePrefix.add(command);
      Collections.addAll(commandlinePrefix, args);

      int retval = 0;
      for (int j = sourceIndex; j < firstFileNextExec; j++) {
        ArrayList<String> commandlineSuffix = new ArrayList<>();

        for (int k = 0; k < argumentCountPerInputFile; k++) {
          commandlineSuffix.add(getInputFileArgument(outputDir, sourceFiles[j], k));
        }
        Collections.addAll(commandlineSuffix, endArgs);

        ArrayList<String> commandline = new ArrayList<>(commandlinePrefix);
        commandline.addAll(commandlineSuffix);
        final int ret = runCommand(task, workDir,
            commandline.toArray(new String[commandline.size()]));
        if (ret != 0) { retval = ret; }
      }
      if (monitor != null) {
        final String[] fileNames = new String[firstFileNextExec - sourceIndex];

        System.arraycopy(sourceFiles, sourceIndex + 0, fileNames, 0, fileNames.length);
        monitor.progress(fileNames);
      }
      //
      // if the process returned a failure code and
      // we aren't holding an exception from an earlier
      // interation
      if (retval != 0 && exc == null) {
        //
        // construct the exception
        //
        exc = new BuildException(getCommandWithPath(config) + " failed with return code " + retval, task.getLocation());

        //
        // and throw it now unless we are relentless
        //
        if (!relentless) {
          throw exc;
        }
      }
      sourceIndex = firstFileNextExec;
    }
    //
    // if the compiler returned a failure value earlier
    // then throw an exception
    if (exc != null) {
      throw exc;
    }
  }
139109
def jarSources(target, source, env, for_signature):
    """"""
    try:
        env['JARCHDIR']
    except KeyError:
        jarchdir_set = False
    else:
        jarchdir_set = True
        jarchdir = env.subst('$JARCHDIR', target=target, source=source)
        if jarchdir:
            jarchdir = env.fs.Dir(jarchdir)
    result = []
    for src in source:
        contents = src.get_text_contents()
        if contents[:16] != "Manifest-Version":
            if jarchdir_set:
                _chdir = jarchdir
            else:
                try:
                    _chdir = src.attributes.java_classdir
                except AttributeError:
                    _chdir = None
            if _chdir:
                # If we are changing the dir with -C, then sources should
                # be relative to that directory.
                src = SCons.Subst.Literal(src.get_path(_chdir))
                result.append('-C')
                result.append(_chdir)
            result.append(src)
    return result
812356
function(files, options) {
    verbose.writeln('Using srcPrefix: ' + options.srcPrefix)
    verbose.writeln('Using destPrefix: ' + options.destPrefix)

    // Build the file list
    files = convert(files)

    // Copy files
    if (!copy(files, options)) {
      fail.warn('Nothing was copied for the "' + this.target + '" target')
    }

    // Report if any dependencies have not been copied
    ensure(files, options)
  }
1265457
def copy_files(source_files, target_directory, source_directory=None):
    """"""
    try:
        os.makedirs(target_directory)
    except:     # TODO: specific exception?
        pass
    for f in source_files:
        source = os.path.join(source_directory, f) if source_directory else f
        target = os.path.join(target_directory, f)
        shutil.copy2(source, target)
641260
def targets_to_stage(self, source_targets, ps):
        """"""

        result = []

        # Traverse the dependencies, if needed.
        if ps.get('install-dependencies') == ['on']:
            source_targets = self.collect_targets(source_targets)

        # Filter the target types, if needed.
        included_types = ps.get('install-type')
        for r in source_targets:
            ty = r.type()
            if ty:
                # Do not stage searched libs.
                if ty != "SEARCHED_LIB":
                    if included_types:
                        if self.include_type(ty, included_types):
                            result.append(r)
                    else:
                        result.append(r)
            elif not included_types:
                # Don't install typeless target if there is an explicit list of
                # allowed types.
                result.append(r)

        return result
971183
void compileBatch(String []files, boolean isMake)
    throws ClassNotFoundException
  {
    try {
      JavaCompilerUtil compiler = JavaCompilerUtil.create(getClassLoader());
      compiler.setClassDir(_classDir);
      compiler.setSourceDir(_sourceDir);
      if (_encoding != null)
        compiler.setEncoding(_encoding);
      compiler.setArgs(_args);
      compiler.setCompileParent(! isMake);
      compiler.setSourceExtension(_sourceExt);
      if (_compiler != null)
        compiler.setCompiler(_compiler);

      //LineMap lineMap = new LineMap(javaFile.getNativePath());
      // The context path is obvious from the browser url
      //lineMap.add(name.replace('.', '/') + _sourceExt, 1, 1);
          
      compiler.compileBatch(files);
    } catch (Exception e) {
      getClassLoader().addDependency(AlwaysModified.create());

      // Compile errors are wrapped in a special ClassNotFound class
      // so the server can give a nice error message
      throw new CompileClassNotFound(e);
    }
  }
1014113
private void compile(AssetInfo asset, File source, File target) throws ServiceException {
        File watched = watchedAssets.get(asset);
        if (watched == null) {
            if (isDevMode()) {
                new Thread(() -> {
                    try {
                        // avoid recursive compiles
                        if (isDevMode())
                            watchedAssets.put(asset, target);
                        doCompile(asset, source, target);
                    }
                    catch (Exception ex) {
                        logger.severeException(ex.getMessage(), ex);
                    }
                }).start();
            }
            else {
                doCompile(asset, source, target);
            }
        }
    }
419381
def _jars_to_directories(self, target):
    
    files = set()
    jar_import_products = self.context.products.get_data(JarImportProducts)
    imports = jar_import_products.imports(target)
    for coordinate, jar in imports:
      files.add(self._extract_jar(coordinate, jar))
    return files
1038375
function merge(target, ...sources) {
  let targetObject = target;

  if (!isObj(target)) {
    targetObject = {};
  }

  // for all the sources provided merge them with
  // the target object
  sources.forEach((s) => {
    // before merging check the source is an object
    if (isObj(s)) {
      targetObject = mergeObject(targetObject, s);
    }
  });

  return targetObject;
}
708854
function buildEntryCompiler(name, deps, opts) {
    var ourDeps = deps
        .filter(R.compose(R.eq(name), R.last, R.prop("level")))
        .distinct(R.prop("id"));

    return ourDeps.aggregate({ externals: [], files: [] }, function (res, row) {
        if (row.external) {
            res.externals.push(row.id);
        } else if (row.entry) {
            res.files.push(row.id);
        }
        return res;
    }).map(function (res) {
        var compiler = opts.browserify(R.mixin(cleanOpts(opts), { deps: depsStream(ourDeps) }));

        R.each(compiler.external.bind(compiler), res.externals);
        R.each(compiler.add.bind(compiler), res.files);

        return { name: name, compiler: compiler };
    }).single();
}
287012
def all_referenced_targets(self, result):
        """"""
        if __debug__:
            from .property import Property
            assert is_iterable_typed(result, (VirtualTarget, Property))
        # Find directly referenced targets.
        deps = self.build_properties().dependency()
        all_targets = self.sources_ + deps

        # Find other subvariants.
        r = []
        for e in all_targets:
            if not e in result:
                result.add(e)
                if isinstance(e, property.Property):
                    t = e.value
                else:
                    t = e

                # FIXME: how can this be?
                cs = t.creating_subvariant()
                if cs:
                    r.append(cs)
        r = unique(r)
        for s in r:
            if s != self:
                s.all_referenced_targets(result)