Builds the client templates.

    We dont need to run special compilers so just enter the virtualenv and
    build. Python will already find its own MSVC for python compilers.
322134
def BuildTemplates(self):
    
    if args.config:
      build_args = [
          "--verbose", "--config", args.config, "build", "--output",
          args.output_dir
      ]
    else:
      build_args = ["--verbose", "build", "--output", args.output_dir]
    subprocess.check_call([self.grr_client_build64] + build_args)
    if args.build_32:
      subprocess.check_call([self.grr_client_build32] + build_args)
37746
def build(template)
      path = options[:directory] || Dir.pwd
      project = options[:project] || File.basename(path)
      
      skeleton = Builder.new(project,template,path)
      skeleton.build
    end
426938
def MakeExecutableTemplate(self, output_file=None):
    """"""
    super(WindowsClientBuilder,
          self).MakeExecutableTemplate(output_file=output_file)

    self.MakeBuildDirectory()
    self.BuildWithPyInstaller()

    # Get any dll's that pyinstaller forgot:
    for module in EnumMissingModules():
      logging.info("Copying additional dll %s.", module)
      shutil.copy(module, self.output_dir)

    self.BuildNanny()

    # Generate a prod and a debug version of nanny executable.
    shutil.copy(
        os.path.join(self.output_dir, "GRRservice.exe"),
        os.path.join(self.output_dir, "dbg_GRRservice.exe"))
    with open(os.path.join(self.output_dir, "GRRservice.exe"), "r+") as fd:
      build.SetPeSubsystem(fd, console=False)
    with open(os.path.join(self.output_dir, "dbg_GRRservice.exe"), "r+") as fd:
      build.SetPeSubsystem(fd, console=True)

    # Generate a prod and a debug version of client executable.
    shutil.copy(
        os.path.join(self.output_dir, "grr-client.exe"),
        os.path.join(self.output_dir, "dbg_grr-client.exe"))
    with open(os.path.join(self.output_dir, "grr-client.exe"), "r+") as fd:
      build.SetPeSubsystem(fd, console=False)
    with open(os.path.join(self.output_dir, "dbg_grr-client.exe"), "r+") as fd:
      build.SetPeSubsystem(fd, console=True)

    self.MakeZip(self.output_dir, self.template_file)
1336540
def _buildTemplates(self):
        

        c_mydict = build_class_json(self.ontospy_graph.all_classes)
        JSON_DATA_CLASSES = json.dumps(c_mydict)


        extra_context = {
                        "ontograph": self.ontospy_graph,
         'JSON_DATA_CLASSES' : JSON_DATA_CLASSES,
                        }

        # Ontology - MAIN PAGE
        contents = self._renderTemplate("misc/sigmajs.html", extraContext=extra_context)
        FILE_NAME = "index.html"
        main_url = self._save2File(contents, FILE_NAME, self.output_path)

        return main_url
503969
def build(self, outpath, structure=None):
        
        if not os.path.exists(outpath):
            return False

        opts = {'scaffold': self}

        if structure is not None:
            xstruct = structure
        else:
            xstruct = self.structure()

        if zipfile.is_zipfile(self.source()):
            zfile = zipfile.ZipFile(self.source(), 'r')
        else:
            zfile = None
            base = os.path.dirname(self.source())

        # build the structure information
        # noinspection PyShadowingNames
        def build_level(root, xlevel):
            # ignore the entry
            if xlevel.get('enabled', 'True') == 'False':
                return

            # create a folder
            if xlevel.tag == 'folder':
                name = makotext.render(xlevel.get('name'), opts)
                dirname = os.path.join(root, name)
                if not os.path.exists(dirname):
                    os.mkdir(dirname)

                for xchild in xlevel:
                    build_level(dirname, xchild)

            # create a file
            elif xlevel.tag == 'file':
                name = makotext.render(xlevel.get('name'), opts)
                fname = os.path.join(root, name)

                # create from a template
                templ = xlevel.get('templ')
                if templ:
                    if zfile:
                        templ_str = zfile.read('templ/{0}'.format(templ))
                    else:
                        templ_path = os.path.join(base, 'templ', templ)
                        templ_str = open(templ_path, 'r').read()

                    rendered = makotext.render(templ_str, opts)
                    rendered = rendered.replace('\r\n', '\r')

                    f = open(fname, 'w')
                    f.write(rendered)
                    f.close()

                # create a blank file
                else:
                    f = open(fname, 'w')
                    f.close()

        for xlevel in xstruct:
            build_level(outpath, xlevel)

        if zfile:
            zfile.close()
        return True
1128633
def BuildService(self, cls):
    

    # CallMethod needs to operate with an instance of the Service class. This
    # internal wrapper function exists only to be able to pass the service
    # instance to the method that does the real CallMethod work.
    def _WrapCallMethod(srvc, method_descriptor,
                        rpc_controller, request, callback):
      return self._CallMethod(srvc, method_descriptor,
                       rpc_controller, request, callback)
    self.cls = cls
    cls.CallMethod = _WrapCallMethod
    cls.GetDescriptor = staticmethod(lambda: self.descriptor)
    cls.GetDescriptor.__doc__ = "Returns the service descriptor."
    cls.GetRequestClass = self._GetRequestClass
    cls.GetResponseClass = self._GetResponseClass
    for method in self.descriptor.methods:
      setattr(cls, method.name, self._GenerateNonImplementedMethod(method))
362547
def build_from_template(file)
      context = @options[:context] || {}

      template = IO.read(file)
      eruby = Erubis::Eruby.new(template)
      string = eruby.evaluate(context)
      build_from_string(string, File.dirname(file))
    end
739732
def generate(env):
    """"""
    try:
        env['BUILDERS']['MSVSProject']
    except KeyError:
        env['BUILDERS']['MSVSProject'] = projectBuilder

    try:
        env['BUILDERS']['MSVSSolution']
    except KeyError:
        env['BUILDERS']['MSVSSolution'] = solutionBuilder

    env['MSVSPROJECTCOM'] = projectAction
    env['MSVSSOLUTIONCOM'] = solutionAction

    if SCons.Script.call_stack:
        # XXX Need to find a way to abstract this; the build engine
        # shouldn't depend on anything in SCons.Script.
        env['MSVSSCONSCRIPT'] = SCons.Script.call_stack[0].sconscript
    else:
        global default_MSVS_SConscript
        if default_MSVS_SConscript is None:
            default_MSVS_SConscript = env.File('SConstruct')
        env['MSVSSCONSCRIPT'] = default_MSVS_SConscript

    env['MSVSSCONS'] = '"%s" -c "%s"' % (python_executable, getExecScriptMain(env))
    env['MSVSSCONSFLAGS'] = '-C "${MSVSSCONSCRIPT.dir.get_abspath()}" -f ${MSVSSCONSCRIPT.name}'
    env['MSVSSCONSCOM'] = '$MSVSSCONS $MSVSSCONSFLAGS'
    env['MSVSBUILDCOM'] = '$MSVSSCONSCOM "$MSVSBUILDTARGET"'
    env['MSVSREBUILDCOM'] = '$MSVSSCONSCOM "$MSVSBUILDTARGET"'
    env['MSVSCLEANCOM'] = '$MSVSSCONSCOM -c "$MSVSBUILDTARGET"'

    # Set-up ms tools paths for default version
    msvc_setup_env_once(env)

    if 'MSVS_VERSION' in env:
        version_num, suite = msvs_parse_version(env['MSVS_VERSION'])
    else:
        (version_num, suite) = (7.0, None) # guess at a default
    if 'MSVS' not in env:
        env['MSVS'] = {}
    if (version_num < 7.0):
        env['MSVS']['PROJECTSUFFIX']  = '.dsp'
        env['MSVS']['SOLUTIONSUFFIX'] = '.dsw'
    elif (version_num < 10.0):
        env['MSVS']['PROJECTSUFFIX']  = '.vcproj'
        env['MSVS']['SOLUTIONSUFFIX'] = '.sln'
    else:
        env['MSVS']['PROJECTSUFFIX']  = '.vcxproj'
        env['MSVS']['SOLUTIONSUFFIX'] = '.sln'

    if (version_num >= 10.0):
        env['MSVSENCODING'] = 'utf-8'
    else:
        env['MSVSENCODING'] = 'Windows-1252'

    env['GET_MSVSPROJECTSUFFIX']  = GetMSVSProjectSuffix
    env['GET_MSVSSOLUTIONSUFFIX']  = GetMSVSSolutionSuffix
    env['MSVSPROJECTSUFFIX']  = '${GET_MSVSPROJECTSUFFIX}'
    env['MSVSSOLUTIONSUFFIX']  = '${GET_MSVSSOLUTIONSUFFIX}'
    env['SCONS_HOME'] = os.environ.get('SCONS_HOME')
74416
def RepackTemplates(self,
                      repack_configs,
                      templates,
                      output_dir,
                      config=None,
                      sign=False,
                      signed_template=False):
    """"""
    pool = multiprocessing.Pool(processes=10)
    results = []
    bulk_sign_installers = False
    for repack_config in repack_configs:
      for template in templates:
        repack_args = ["grr_client_build"]
        if config:
          repack_args.extend(["--config", config])

        repack_args.extend([
            "--secondary_configs", repack_config, "repack", "--template",
            template, "--output_dir",
            self.GetOutputDir(output_dir, repack_config)
        ])

        # We only sign exes and rpms at the moment. The others will raise if we
        # try to ask for signing.
        passwd = None

        if sign:
          if template.endswith(".exe.zip"):
            # This is for osslsigncode only.
            if platform.system() != "Windows":
              passwd = self.GetWindowsPassphrase()
              repack_args.append("--sign")
            else:
              bulk_sign_installers = True
            if signed_template:
              repack_args.append("--signed_template")
          elif template.endswith(".rpm.zip"):
            bulk_sign_installers = True

        print("Calling %s" % " ".join(repack_args))
        results.append(
            pool.apply_async(SpawnProcess, (repack_args,), dict(passwd=passwd)))

        # Also build debug if it's windows.
        if template.endswith(".exe.zip"):
          debug_args = []
          debug_args.extend(repack_args)
          debug_args.append("--debug_build")
          print("Calling %s" % " ".join(debug_args))
          results.append(
              pool.apply_async(SpawnProcess, (debug_args,),
                               dict(passwd=passwd)))

    try:
      pool.close()
      # Workaround to handle keyboard kills
      # http://stackoverflow.com/questions/1408356/keyboard-interrupts-with-pythons-multiprocessing-pool
      # get will raise if the child raises.
      for result_obj in results:
        result_obj.get(9999)
      pool.join()
    except KeyboardInterrupt:
      print("parent received control-c")
      pool.terminate()
    except ErrorDuringRepacking:
      pool.terminate()
      raise

    if bulk_sign_installers:
      to_sign = {}
      for root, _, files in os.walk(output_dir):
        for f in files:
          if f.endswith(".exe"):
            to_sign.setdefault("windows", []).append(os.path.join(root, f))
          elif f.endswith(".rpm"):
            to_sign.setdefault("rpm", []).append(os.path.join(root, f))
      if to_sign.get("windows"):
        signer = repacking.TemplateRepacker().GetSigner([
            "ClientBuilder Context",
            "Platform:%s" % platform.system(), "Target:Windows"
        ])
        signer.SignFiles(to_sign.get("windows"))
      if to_sign.get("rpm"):
        signer = repacking.TemplateRepacker().GetSigner([
            "ClientBuilder Context",
            "Platform:%s" % platform.system(), "Target:Linux", "Target:LinuxRpm"
        ])
        signer.AddSignatureToRPMs(to_sign.get("rpm"))
573446
def build(context, provider, **kwargs):  # pylint: disable=unused-argument
    """"""
    session = get_session(provider.region)
    options = kwargs.get('options', {})
    context_dict = {}
    context_dict['artifact_key_prefix'] = "%s-%s-" % (options['namespace'], options['name'])  # noqa
    default_param_name = "%shash" % context_dict['artifact_key_prefix']

    if options.get('build_output'):
        build_output = os.path.join(
            options['path'],
            options['build_output']
        )
    else:
        build_output = options['path']

    context_dict['artifact_bucket_name'] = RxrefLookup.handle(
        kwargs.get('artifact_bucket_rxref_lookup'),
        provider=provider,
        context=context
    )

    if options.get('pre_build_steps'):
        run_commands(options['pre_build_steps'], options['path'])

    context_dict['hash'] = get_hash_of_files(
        root_path=options['path'],
        directories=options.get('source_hashing', {}).get('directories')
    )

    # Now determine if the current staticsite has already been deployed
    if options.get('source_hashing', {}).get('enabled', True):
        context_dict['hash_tracking_parameter'] = options.get(
            'source_hashing', {}).get('parameter', default_param_name)

        ssm_client = session.client('ssm')

        try:
            old_parameter_value = ssm_client.get_parameter(
                Name=context_dict['hash_tracking_parameter']
            )['Parameter']['Value']
        except ssm_client.exceptions.ParameterNotFound:
            old_parameter_value = None
    else:
        context_dict['hash_tracking_disabled'] = True
        old_parameter_value = None

    context_dict['current_archive_filename'] = (
        context_dict['artifact_key_prefix'] + context_dict['hash'] + '.zip'
    )
    if old_parameter_value:
        context_dict['old_archive_filename'] = (
            context_dict['artifact_key_prefix'] + old_parameter_value + '.zip'
        )

    if old_parameter_value == context_dict['hash']:
        LOGGER.info("staticsite: skipping build; app hash %s already deployed "
                    "in this environment",
                    context_dict['hash'])
        context_dict['deploy_is_current'] = True
        return context_dict

    if does_s3_object_exist(context_dict['artifact_bucket_name'],
                            context_dict['current_archive_filename'],
                            session):
        context_dict['app_directory'] = download_and_extract_to_mkdtemp(
            context_dict['artifact_bucket_name'],
            context_dict['current_archive_filename'], session
        )
    else:
        if options.get('build_steps'):
            LOGGER.info('staticsite: executing build commands')
            run_commands(options['build_steps'], options['path'])
        zip_and_upload(build_output, context_dict['artifact_bucket_name'],
                       context_dict['current_archive_filename'], session)
        context_dict['app_directory'] = build_output

    context_dict['deploy_is_current'] = False
    return context_dict
402527
def compile(source, options = {})
      source  = prepare_source(source)
      options = prepare_options(options)
      snippet = compilation_snippet \
        method:    "compile#{ "Client" if options[:client] }",
        arguments: [source, options],
        locals:    options.fetch(:locals, {}),
        options:   options
      result  = @execjs.eval(snippet)
      process_result(source, result, options)
    rescue ExecJS::ProgramError => e
      raise engine::CompilationError, e.message
    end
107190
protected function installTemplates()
    {
        $path = $this->getCodeDir() . '/client/templates';
        if (file_exists($path))
        {
            $ts = Eresus_Template_Service::getInstance();
            $it = new DirectoryIterator($path);
            foreach ($it as $fileInfo)
            {
                /** @var DirectoryIterator $fileInfo */
                if (!$fileInfo->isDot())
                {
                    $ts->install($fileInfo->getPathname(), $this->getName());
                }
            }
        }
    }
1025703
def build(self, sources=None, headers=None):
        ''' 
        '''
        tempdir = None
        strings, files = separate_sources(sources)
        if len(strings) or headers:
            # TODO: remove tempdir
            tempdir = tmpdir()

        temp_list = [tmpfile(x, tempdir, '.c') for x in strings]

        if headers:
            for n, s in headers.items():
                (Path(tempdir) / n).write_text(s)

        cmd = self.command_list(files + temp_list)
        if tempdir:
            cmd += ['-I' + tempdir]
        self.proc = Proc(cmd).call()
#        for x in temp_list:
#            os.remove(x)

        if not self.ok:
            raise AvrGccCompileError(cmd, sources, self.error_text)
92700
def supports(cls, template_file=None):
        
        if anytemplate.compat.IS_PYTHON_3:
            cls._priority = 99
            return False  # Always as it's not ported to python 3.

        return super(Engine, cls).supports(template_file=template_file)
1214589
def convert_to_template(name, kwargs=None, call=None):
    '''
    
    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The convert_to_template action must be called with '
            '-a or --action.'
        )

    vm_ref = salt.utils.vmware.get_mor_by_property(_get_si(), vim.VirtualMachine, name)

    if vm_ref.config.template:
        raise SaltCloudSystemExit(
            '{0} already a template'.format(
                name
            )
        )

    try:
        vm_ref.MarkAsTemplate()
    except Exception as exc:
        log.error(
            'Error while converting VM to template %s: %s',
            name, exc,
            # Show the traceback if the debug logging level is enabled
            exc_info_on_loglevel=logging.DEBUG
        )
        return 'failed to convert to teamplate'

    return '{0} converted to template'.format(name)
475184
def create_templates(self, templates):
        
        count = 0
        for template in templates:
            if not self.template_exists_db(template):
                name, location, description, language = template
                text = self.open_file(location)
                html_content = self.get_html_content(text)
                data = {
                    'name': utils.camel_to_snake(name).upper(),
                    'html_content': html_content,
                    'content': self.text_version(html_content),
                    'subject': self.get_subject(text),
                    'description': description,
                    'language': language
                }
                if models.EmailTemplate.objects.create(**data):
                    count += 1
        return count
529934
def build(self, client, pull=False, usecache=True):
        
        stage = staging.StagedFile(self.sourceimage, self.sourcepath, self.destpath,
                                   cache_from=self.cache_from)
        stage.stage(self.baseimage, self.buildname)