Generate a c7n-org gcp projects config file
494867
def main(output):
    

    client = Session().client('cloudresourcemanager', 'v1', 'projects')

    results = []
    for page in client.execute_paged_query('list', {}):
        for project in page.get('projects', []):

            if project['lifecycleState'] != 'ACTIVE':
                continue

            project_info = {
                'project_id': project['projectId'],
                'name': project['name'],
            }

            if 'labels' in project:
                project_info['tags'] = [
                    'label:%s:%s' % (k, v) for k, v in project.get('labels', {}).items()]
            results.append(project_info)

    output.write(
        yaml.safe_dump({'projects': results}, default_flow_style=False))
231029
def generate(env):
    """"""
    static_obj, shared_obj = SCons.Tool.createObjBuilders(env)

    if 'CXX' not in env:
        env['CXX']    = env.Detect(compilers) or compilers[0]

    cxx.generate(env)

    # platform specific settings
    if env['PLATFORM'] == 'aix':
        env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS -mminimal-toc')
        env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1
        env['SHOBJSUFFIX'] = '$OBJSUFFIX'
    elif env['PLATFORM'] == 'hpux':
        env['SHOBJSUFFIX'] = '.pic.o'
    elif env['PLATFORM'] == 'sunos':
        env['SHOBJSUFFIX'] = '.pic.o'
    # determine compiler version
    version = gcc.detect_version(env, env['CXX'])
    if version:
        env['CXXVERSION'] = version
585221
def GenerateDPKGFiles(self, template_path):
    """"""

    # Rename the generated binaries to the correct name.
    template_binary_dir = os.path.join(template_path, "dist/debian/grr-client")
    package_name = config.CONFIG.Get(
        "ClientBuilder.package_name", context=self.context)
    target_binary_dir = os.path.join(
        template_path, "dist/debian/%s%s" %
        (package_name,
         config.CONFIG.Get("ClientBuilder.target_dir", context=self.context)))
    if package_name == "grr-client":
      # Need to rename the template path or the move will fail.
      shutil.move(template_binary_dir, "%s-template" % template_binary_dir)
      template_binary_dir = "%s-template" % template_binary_dir

    utils.EnsureDirExists(os.path.dirname(target_binary_dir))
    shutil.move(template_binary_dir, target_binary_dir)

    shutil.move(
        os.path.join(target_binary_dir, "grr-client"),
        os.path.join(
            target_binary_dir,
            config.CONFIG.Get("Client.binary_name", context=self.context)))

    deb_in_dir = os.path.join(template_path, "dist/debian/debian.in/")

    self.GenerateDirectory(deb_in_dir, os.path.join(
        template_path, "dist/debian"), [("grr-client", package_name)])

    # Generate directories for the /usr/sbin link.
    utils.EnsureDirExists(
        os.path.join(template_path, "dist/debian/%s/usr/sbin" % package_name))

    if config.CONFIG.Get("Client.fleetspeak_enabled", context=self.context):
      self._GenerateFleetspeakConfig(template_path)
      shutil.rmtree(deb_in_dir)
      shutil.rmtree(os.path.join(template_path, "dist", "fleetspeak"))
      return

    # Generate the nanny template. This only exists from client version 3.1.2.5
    # onwards.
    if config.CONFIG["Template.version_numeric"] >= 3125:
      self.GenerateFile(
          os.path.join(target_binary_dir, "nanny.sh.in"),
          os.path.join(target_binary_dir, "nanny.sh"))

    # Generate the upstart template.
    self.GenerateFile(
        os.path.join(template_path, "dist/debian/upstart.in/grr-client.conf"),
        os.path.join(template_path, "dist/debian/%s.upstart" % package_name))

    # Generate the initd template. The init will not run if it detects upstart
    # is present.
    self.GenerateFile(
        os.path.join(template_path, "dist/debian/initd.in/grr-client"),
        os.path.join(template_path, "dist/debian/%s.init" % package_name))

    # Generate the systemd unit file.
    self.GenerateFile(
        os.path.join(template_path,
                     "dist/debian/systemd.in/grr-client.service"),
        os.path.join(template_path, "dist/debian/%s.service" % package_name))

    # Clean up the template dirs.
    shutil.rmtree(deb_in_dir)
    shutil.rmtree(os.path.join(template_path, "dist/debian/upstart.in"))
    shutil.rmtree(os.path.join(template_path, "dist/debian/initd.in"))
    shutil.rmtree(os.path.join(template_path, "dist/debian/systemd.in"))
587609
def generate(env):
    """"""
    static_obj, shared_obj = SCons.Tool.createObjBuilders(env)

    for suffix in ASSuffixes:
        static_obj.add_action(suffix, SCons.Defaults.ASAction)
        static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter)

    for suffix in ASPPSuffixes:
        static_obj.add_action(suffix, SCons.Defaults.ASPPAction)
        static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter)

    env['AS']        = 'nasm'
    env['ASFLAGS']   = SCons.Util.CLVar('')
    env['ASPPFLAGS'] = '$ASFLAGS'
    env['ASCOM']     = '$AS $ASFLAGS -o $TARGET $SOURCES'
    env['ASPPCOM']   = '$CC $ASPPFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -c -o $TARGET $SOURCES'
650099
def generate(env):
    """"""
    SCons.Tool.cc.generate(env)

    env['CC'] = env.Detect(compilers) or 'clang'
    if env['PLATFORM'] in ['cygwin', 'win32']:
        env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS')
    else:
        env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS -fPIC')
    # determine compiler version
    if env['CC']:
        #pipe = SCons.Action._subproc(env, [env['CC'], '-dumpversion'],
        pipe = SCons.Action._subproc(env, [env['CC'], '--version'],
                                     stdin='devnull',
                                     stderr='devnull',
                                     stdout=subprocess.PIPE)
        if pipe.wait() != 0: return
        # clang -dumpversion is of no use
        line = pipe.stdout.readline()
        if sys.version_info[0] > 2:
            line = line.decode()
        match = re.search(r'clang +version +([0-9]+(?:\.[0-9]+)+)', line)
        if match:
            env['CCVERSION'] = match.group(1)
1310213
def _make_cmake(config_info):
    """"""
    configure_args = ["-DCMAKE_EXPORT_COMPILE_COMMANDS=ON"]
    cmake_args = {}

    options, option_fns = _make_all_options()

    def _add_value(value, key):
        args_key, args_value = _EX_ARG_FNS[key](value)
        cmake_args[args_key] = args_value

    devpipeline_core.toolsupport.args_builder(
        "cmake",
        config_info,
        options,
        lambda v, key: configure_args.extend(option_fns[key](v)),
    )
    devpipeline_core.toolsupport.args_builder(
        "cmake", config_info, _EX_ARGS, _add_value
    )
    cmake = CMake(cmake_args, config_info, configure_args)
    build_type = config_info.config.get("cmake.build_type")
    if build_type:
        cmake.set_build_type(build_type)
    return devpipeline_build.make_simple_builder(cmake, config_info)
38025
def generate_python_config(self):
        
        python_config = PYTHON_CONFIG.copy()

        # Server options
        cmd = self.get_option('advanced/command_launch')
        host = self.get_option('advanced/host')
        port = self.get_option('advanced/port')

        # Pycodestyle
        cs_exclude = self.get_option('pycodestyle/exclude').split(',')
        cs_filename = self.get_option('pycodestyle/filename').split(',')
        cs_select = self.get_option('pycodestyle/select').split(',')
        cs_ignore = self.get_option('pycodestyle/ignore').split(',')
        cs_max_line_length = self.get_option('pycodestyle/max_line_length')

        pycodestyle = {
            'enabled': self.get_option('pycodestyle'),
            'exclude': [exclude.strip() for exclude in cs_exclude],
            'filename': [filename.strip() for filename in cs_filename],
            'select': [select.strip() for select in cs_select],
            'ignore': [ignore.strip() for ignore in cs_ignore],
            'hangClosing': False,
            'maxLineLength': cs_max_line_length
        }

        # Linting - Pyflakes
        pyflakes = {
            'enabled': self.get_option('pyflakes')
        }

        # Pydocstyle
        convention = self.get_option('pydocstyle/convention')

        if convention == 'Custom':
            ds_ignore = self.get_option('pydocstyle/ignore').split(',')
            ds_select = self.get_option('pydocstyle/select').split(',')
            ds_add_ignore = []
            ds_add_select = []
        else:
            ds_ignore = []
            ds_select = []
            ds_add_ignore = self.get_option('pydocstyle/ignore').split(',')
            ds_add_select = self.get_option('pydocstyle/select').split(',')

        pydocstyle = {
            'enabled': self.get_option('pydocstyle'),
            'convention': convention,
            'addIgnore': [ignore.strip() for ignore in ds_add_ignore],
            'addSelect': [select.strip() for select in ds_add_select],
            'ignore': [ignore.strip() for ignore in ds_ignore],
            'select': [select.strip() for select in ds_select],
            'match': self.get_option('pydocstyle/match'),
            'matchDir': self.get_option('pydocstyle/match_dir')
        }

        # Code completion
        jedi_completion = {
            'enabled': self.get_option('code_completion'),
            'include_params': False
        }

        jedi_signature_help = {
            'enabled': self.get_option('jedi_signature_help')
        }

        jedi_definition = {
            'enabled': self.get_option('jedi_definition'),
            'follow_imports': self.get_option('jedi_definition/follow_imports')
        }

        # Advanced
        external_server = self.get_option('advanced/external')

        # Setup options in json
        python_config['cmd'] = cmd
        if host in self.LOCALHOST:
            python_config['args'] = '--host {host} --port {port} --tcp'
        else:
            python_config['args'] = ''
        python_config['external'] = external_server
        python_config['host'] = host
        python_config['port'] = port

        plugins = python_config['configurations']['pyls']['plugins']
        plugins['pycodestyle'] = pycodestyle
        plugins['pyflakes'] = pyflakes
        plugins['pydocstyle'] = pydocstyle
        plugins['jedi_completion'] = jedi_completion
        plugins['jedi_signature_help'] = jedi_signature_help
        plugins['preload']['modules'] = self.get_option('preload_modules')
        plugins['jedi_definition'] = jedi_definition

        return python_config
567878
def run_config(self, project, run=None, entity=None):
        
        query = gql('''
        query Model($name: String!, $entity: String!, $run: String!) {
            model(name: $name, entityName: $entity) {
                bucket(name: $run) {
                    config
                    commit
                    patch
                    files(names: ["wandb-metadata.json"]) {
                        edges {
                            node {
                                url
                            }
                        }
                    }
                }
            }
        }
        ''')

        response = self.gql(query, variable_values={
            'name': project, 'run': run, 'entity': entity
        })
        if response['model'] == None:
            raise ValueError("Run {}/{}/{} not found".format(entity, project, run) )
        run = response['model']['bucket']
        commit = run['commit']
        patch = run['patch']
        config = json.loads(run['config'] or '{}')
        if len(run['files']['edges']) > 0:
            url = run['files']['edges'][0]['node']['url']
            res = requests.get(url)
            res.raise_for_status()
            metadata = res.json()
        else:
            metadata = {}
        return (commit, config, patch, metadata)
205517
def create_config_files(ctx, opts, api_key):
    """"""
    # pylint: disable=unused-argument
    config_reader = opts.get_config_reader()
    creds_reader = opts.get_creds_reader()
    has_config = config_reader.has_default_file()
    has_creds = creds_reader.has_default_file()

    if has_config and has_creds:
        create = False
    else:
        click.echo()
        create = click.confirm(
            "No default config file(s) found, do you want to create them?"
        )

    click.echo()
    if not create:
        click.secho(
            "For reference here are your default config file locations:", fg="yellow"
        )
    else:
        click.secho(
            "Great! Let me just create your default configs for you now ...", fg="green"
        )

    configs = (
        ConfigValues(reader=config_reader, present=has_config, mode=None, data={}),
        ConfigValues(
            reader=creds_reader,
            present=has_creds,
            mode=stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IWGRP,
            data={"api_key": api_key},
        ),
    )

    has_errors = False
    for config in configs:
        click.echo(
            "%(name)s config file: %(filepath)s ... "
            % {
                "name": click.style(config.reader.config_name.capitalize(), bold=True),
                "filepath": click.style(
                    config.reader.get_default_filepath(), fg="magenta"
                ),
            },
            nl=False,
        )

        if not config.present and create:
            try:
                ok = config.reader.create_default_file(
                    data=config.data, mode=config.mode
                )
            except (OSError, IOError) as exc:
                ok = False
                error_message = exc.strerror
                has_errors = True

            if ok:
                click.secho("CREATED", fg="green")
            else:
                click.secho("ERROR", fg="red")
                click.secho(
                    "The following error occurred while trying to "
                    "create the file: %(message)s"
                    % {"message": click.style(error_message, fg="red")}
                )
            continue

        click.secho("EXISTS" if config.present else "NOT CREATED", fg="yellow")

    return create, has_errors
517394
def _get_files_project(sample, upload_config):
    
    out = [{"path": sample["provenance"]["programs"]}]
    if os.path.exists(tz.get_in(["provenance", "data"], sample) or ""):
        out.append({"path": sample["provenance"]["data"]})
    for fname in ["bcbio-nextgen.log", "bcbio-nextgen-commands.log"]:
        if os.path.exists(os.path.join(log.get_log_dir(sample["config"]), fname)):
            out.append({"path": os.path.join(log.get_log_dir(sample["config"]), fname),
                        "type": "external_command_log",
                        "ext": ""})

    if "summary" in sample and sample["summary"].get("project"):
        out.append({"path": sample["summary"]["project"]})
    if "summary" in sample and sample["summary"].get("metadata"):
        out.append({"path": sample["summary"]["metadata"]})
    mixup_check = tz.get_in(["summary", "mixup_check"], sample)
    if mixup_check:
        out.append({"path": sample["summary"]["mixup_check"],
                    "type": "directory", "ext": "mixup_check"})

    report = os.path.join(dd.get_work_dir(sample), "report")
    if utils.file_exists(report):
        out.append({"path": report,
                    "type": "directory", "ext": "report"})

    multiqc = tz.get_in(["summary", "multiqc"], sample)
    if multiqc:
        out.extend(_flatten_file_with_secondary(multiqc, "multiqc"))

    if sample.get("seqcluster", {}):
        out.append({"path": sample["seqcluster"].get("out_dir"),
                    "type": "directory", "ext": "seqcluster"})

    if sample.get("mirge", {}):
        for fn in sample["mirge"]:
            out.append({"path": fn,
                        "dir": "mirge"})

    if sample.get("report", None):
        out.append({"path": os.path.dirname(sample["report"]),
                    "type": "directory", "ext": "seqclusterViz"})

    for x in sample.get("variants", []):
        if "pop_db" in x:
            out.append({"path": x["pop_db"],
                        "type": "sqlite",
                        "variantcaller": x["variantcaller"]})
    for x in sample.get("variants", []):
        if "population" in x:
            pop_db = tz.get_in(["population", "db"], x)
            if pop_db:
                out.append({"path": pop_db,
                            "type": "sqlite",
                            "variantcaller": x["variantcaller"]})
            suffix = "-annotated-decomposed" if tz.get_in(("population", "decomposed"), x) else "-annotated"
            vcfs = _get_project_vcf(x, suffix)
            out.extend([_add_batch(f, sample) for f in vcfs])
    for x in sample.get("variants", []):
        if x.get("validate") and x["validate"].get("grading_summary"):
            out.append({"path": x["validate"]["grading_summary"]})
            break
    sv_project = set([])
    for svcall in sample.get("sv", []):
        if svcall.get("variantcaller") == "seq2c":
            if svcall.get("calls_all") and svcall["calls_all"] not in sv_project:
                out.append({"path": svcall["coverage_all"], "batch": "seq2c", "ext": "coverage", "type": "tsv"})
                out.append({"path": svcall["read_mapping"], "batch": "seq2c", "ext": "read_mapping", "type": "txt"})
                out.append({"path": svcall["calls_all"], "batch": "seq2c", "ext": "calls", "type": "tsv"})
                sv_project.add(svcall["calls_all"])
    if "coverage" in sample:
        cov_db = tz.get_in(["coverage", "summary"], sample)
        if cov_db:
            out.append({"path": cov_db, "type": "sqlite", "ext": "coverage"})
        all_coverage = tz.get_in(["coverage", "all"], sample)
        if all_coverage:
            out.append({"path": all_coverage, "type": "bed", "ext": "coverage"})

    if dd.get_mirna_counts(sample):
        out.append({"path": dd.get_mirna_counts(sample)})
    if dd.get_isomir_counts(sample):
        out.append({"path": dd.get_isomir_counts(sample)})
    if dd.get_novel_mirna_counts(sample):
        out.append({"path": dd.get_novel_mirna_counts(sample)})
    if dd.get_novel_isomir_counts(sample):
        out.append({"path": dd.get_novel_isomir_counts(sample)})
    if dd.get_combined_counts(sample):
        count_file = dd.get_combined_counts(sample)
        if sample["analysis"].lower() == "scrna-seq":
            out.append({"path": count_file,
                        "type": "mtx"})
            out.append({"path": count_file + ".rownames",
                        "type": "rownames"})
            out.append({"path": count_file + ".colnames",
                        "type": "colnames"})
            out.append({"path": count_file + ".metadata",
                        "type": "metadata"})
            umi_file = os.path.splitext(count_file)[0] + "-dupes.mtx"
            if utils.file_exists(umi_file):
                out.append({"path": umi_file,
                            "type": "mtx"})
                out.append({"path": umi_file + ".rownames",
                            "type": "rownames"})
                out.append({"path": umi_file + ".colnames",
                            "type": "colnames"})
            if dd.get_combined_histogram(sample):
                out.append({"path": dd.get_combined_histogram(sample),
                            "type": "txt"})
            rda = os.path.join(os.path.dirname(count_file), "se.rda")
            if utils.file_exists(rda):
                out.append({"path": rda,
                            "type": "rda"})
        else:
            out.append({"path": dd.get_combined_counts(sample)})
    if dd.get_annotated_combined_counts(sample):
        out.append({"path": dd.get_annotated_combined_counts(sample)})
    if dd.get_combined_fpkm(sample):
        out.append({"path": dd.get_combined_fpkm(sample)})
    if dd.get_combined_fpkm_isoform(sample):
        out.append({"path": dd.get_combined_fpkm_isoform(sample)})
    if dd.get_transcript_assembler(sample):
        out.append({"path": dd.get_merged_gtf(sample)})
    if dd.get_dexseq_counts(sample):
        out.append({"path": dd.get_dexseq_counts(sample)})
        out.append({"path": "%s.ann" % dd.get_dexseq_counts(sample)})
    if dd.get_express_counts(sample):
        out.append({"path": dd.get_express_counts(sample)})
    if dd.get_express_fpkm(sample):
        out.append({"path": dd.get_express_fpkm(sample)})
    if dd.get_express_tpm(sample):
        out.append({"path": dd.get_express_tpm(sample)})
    if dd.get_isoform_to_gene(sample):
        out.append({"path": dd.get_isoform_to_gene(sample)})
    if dd.get_square_vcf(sample):
        out.append({"path": dd.get_square_vcf(sample)})
    if dd.get_sailfish_transcript_tpm(sample):
        out.append({"path": dd.get_sailfish_transcript_tpm(sample)})
    if dd.get_sailfish_gene_tpm(sample):
        out.append({"path": dd.get_sailfish_gene_tpm(sample)})
    if dd.get_tx2gene(sample):
        out.append({"path": dd.get_tx2gene(sample)})
    if dd.get_spikein_counts(sample):
        out.append({"path": dd.get_spikein_counts(sample)})
    transcriptome_dir = os.path.join(dd.get_work_dir(sample), "inputs",
                                     "transcriptome")
    if os.path.exists(transcriptome_dir):
        out.append({"path": transcriptome_dir, "type": "directory",
                    "ext": "transcriptome"})
    return _add_meta(out, config=upload_config)
169143
def generate(env):
    """"""
    try:
        bld = env['BUILDERS']['Ipkg']
    except KeyError:
        bld = SCons.Builder.Builder(action='$IPKGCOM',
                                    suffix='$IPKGSUFFIX',
                                    source_scanner=None,
                                    target_scanner=None)
        env['BUILDERS']['Ipkg'] = bld


    env['IPKG'] = 'ipkg-build'
    env['IPKGCOM'] = '$IPKG $IPKGFLAGS ${SOURCE}'

    if env.WhereIs('id'):
        env['IPKGUSER'] = os.popen('id -un').read().strip()
        env['IPKGGROUP'] = os.popen('id -gn').read().strip()
    env['IPKGFLAGS'] = SCons.Util.CLVar('-o $IPKGUSER -g $IPKGGROUP')
    env['IPKGSUFFIX'] = '.ipk'
495708
def generate_schema_file(config_file):
    

    config = utils.load_config_from_ini_file(config_file)
    schema = {}

    for section_name in config:
        for option_name in config[section_name]:
            schema.setdefault(section_name, {}).setdefault(option_name, {})
            schema[section_name][option_name]['description'] = 'No description provided.'

    return utils.dump_schema_file(schema)
354528
def generate(env):
    """"""
    path, cxx, shcxx, version = get_cppc(env)
    if path:
        cxx = os.path.join(path, cxx)
        shcxx = os.path.join(path, shcxx)

    cplusplus.generate(env)

    env['CXX'] = cxx
    env['SHCXX'] = shcxx
    env['CXXVERSION'] = version
    env['SHCXXFLAGS']   = SCons.Util.CLVar('$CXXFLAGS -KPIC')
    env['SHOBJPREFIX']  = 'so_'
    env['SHOBJSUFFIX']  = '.o'
791776
def generate_relay_config(project):
    
    ld_api = LaunchDarklyApi(
        os.environ.get('LD_API_KEY'),
        project_key=project
    )
    config = ConfigGenerator()

    envs = ld_api.get_environments(project)
    config.generate_relay_config(envs)
303622
def add_shared_configs(p, base_dir=''):
    
    p.add('--host', default='localhost',
          help="Service host")
    p.add('--port', '-p', type=int, default=8000,
          help="Service port")
    p.add('--app-host', default=None,
          help="Local application host for reverse proxy deployment, "
               "as opposed to service --host (must also specify --app-port)")
    p.add('--app-port', type=int, default=None,
          help="Local application port for reverse proxy deployment, "
               "as opposed to service --port (must also specify --app-host)")
    p.add('--image-dir', '-d', default=os.path.join(base_dir, 'testimages'),
          help="Image file directory")
    p.add('--generator-dir', default=os.path.join(base_dir, 'iiif/generators'),
          help="Generator directory for manipulator='gen'")
    p.add('--tile-height', type=int, default=512,
          help="Tile height")
    p.add('--tile-width', type=int, default=512,
          help="Tile width")
    p.add('--gauth-client-secret', default=os.path.join(base_dir, 'client_secret.json'),
          help="Name of file with Google auth client secret")
    p.add('--include-osd', action='store_true',
          help="Include a page with OpenSeadragon for each source")
    p.add('--access-cookie-lifetime', type=int, default=3600,
          help="Set access cookie lifetime for authenticated access in seconds")
    p.add('--access-token-lifetime', type=int, default=10,
          help="Set access token lifetime for authenticated access in seconds")
    p.add('--config', is_config_file=True, default=None,
          help='Read config from given file path')
    p.add('--debug', action='store_true',
          help="Set debug mode for web application. INSECURE!")
    p.add('--verbose', '-v', action='store_true',
          help="Be verbose")
    p.add('--quiet', '-q', action='store_true',
          help="Minimal output only")
455394
def gen_cmake_command(config):
    
    from autocmake.extract import extract_list

    s = []
    s.append("\n\ndef gen_cmake_command(options, arguments):")
    s.append('    """')
    s.append("    Generate CMake command based on options and arguments.")
    s.append('    """')
    s.append("    command = []")

    for env in config['export']:
        s.append('    command.append({0})'.format(env))

    s.append("    command.append(arguments['--cmake-executable'])")

    for definition in config['define']:
        s.append('    command.append({0})'.format(definition))

    s.append("    command.append('-DCMAKE_BUILD_TYPE={0}'.format(arguments['--type']))")
    s.append("    command.append('-G\"{0}\"'.format(arguments['--generator']))")
    s.append("    if arguments['--cmake-options'] != \"''\":")
    s.append("        command.append(arguments['--cmake-options'])")
    s.append("    if arguments['--prefix']:")
    s.append("        command.append('-DCMAKE_INSTALL_PREFIX=\"{0}\"'.format(arguments['--prefix']))")

    s.append("\n    return ' '.join(command)")

    return '\n'.join(s)
1264655
def generateInitd(conf_file):
    
    allowed_opts = [
        'virtualenv', 'project_path', 'settings', 'processes',
        'http_port', 'cache', 'cache_port', 'https_port', 'key', 'cert'
    ]
    base_opts = ['--daemonize', ]  # always daemonize
    options = base_opts
    with open(conf_file, 'r') as cfg:
        conf = yaml.load(cfg)
    conf_specs = set(conf.keys())

    if len(conf_specs - set(allowed_opts)):
        raise RuntimeError('Improperly configured.')

    try:
        virtualenv = conf.pop('virtualenv')
        project_path = conf.pop('project_path')
    except:
        raise RuntimeError('Improperly configured.')

    cache = False
    if 'cache' in conf:
        cache = conf.pop('cache')
    if not cache:
        options.append('--nocache')

    workers = 0
    if 'processes' in conf:
        processes = conf.pop('processes')
        workers = int(processes) - 1
    if workers > 0:
        options += ['--workers', str(workers)]

    for key, value in conf.iteritems():
        options += ['--%s' % key, str(value)]

    with open(os.path.join(SHARE_PATH, 'init.d.j2'), 'r') as f:
        TEMPLATE_FILE = f.read()
    template = jinja2.Template(TEMPLATE_FILE)

    initd_content = template.render(
        {
            'venv_path': virtualenv,
            'project_path': project_path,
            'hendrix_opts': ' '.join(options)
        }
    )

    return initd_content