Create a new django project using the longclaw template
166865
def create_project(args):
    

    # Make sure given name is not already in use by another python package/module.
    try:
        __import__(args.project_name)
    except ImportError:
        pass
    else:
        sys.exit("'{}' conflicts with the name of an existing "
                 "Python module and cannot be used as a project "
                 "name. Please try another name.".format(args.project_name))

    # Get the longclaw template path
    template_path = path.join(path.dirname(longclaw.__file__), 'project_template')

    utility = ManagementUtility((
        'django-admin.py',
        'startproject',
        '--template={}'.format(template_path),
        '--extension=html,css,js,py,txt',
        args.project_name
    ))
    utility.execute()
    print("{} has been created.".format(args.project_name))
474245
def build_template(self, mapfile, names, renderer):
        
        AVAILABLE_DUMPS = json.load(open(mapfile, "r"))

        manager = self.get_deps_manager(AVAILABLE_DUMPS)

        fp = StringIO.StringIO()

        for i, item in enumerate(manager.get_dump_order(names), start=1):
            fp = renderer(fp, i, item, manager[item])

        if self.dump_other_apps:
            exclude_models = ['-e {0}'.format(app) for app in
                    self.exclude_apps]
            for i, item in enumerate(manager.get_dump_order(names), start=1):
                for model in manager[item]['models']:
                    if '-e ' not in model:
                        model = "-e {0}".format(model)
                    if model not in exclude_models:
                        exclude_models.append(model)
            fp = renderer(fp, i+1, 'other_apps', {'models': exclude_models,
                                                  'use_natural_key': True})

        content = fp.getvalue()
        fp.close()

        context = self.get_global_context().copy()
        context.update({'items': content})

        return self.base_template.format(**context)
952821
def start_distribution(project_name, template_dir, dist, noadmin):
    

    directory = os.getcwd()

    # Check that the project_name cannot be imported.
    try:
        import_module(project_name)
    except ImportError:
        pass
    else:
        raise CommandError("%r conflicts with the name of an existing Python module and cannot be used as a project name. Please try another name." % project_name)
    #woven override
    copy_helper('project', project_name, directory, dist, template_dir, noadmin)
    
    #Create a random SECRET_KEY hash, and put it in the main settings.
    main_settings_file = os.path.join(directory, dist, project_name, 'settings.py')
    settings_contents = open(main_settings_file, 'r').read()
    fp = open(main_settings_file, 'w')
    secret_key = ''.join([choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)])
    settings_contents = re.sub(r"(?<=SECRET_KEY = ')'", secret_key + "'", settings_contents)
    fp.write(settings_contents)
    fp.close()
    
    #import settings and create start directories
    sys.path.append(os.path.join(directory, dist))

    s = import_module('.'.join([project_name,'settings']))
    sys.path.pop()
    if s.DATABASES['default']['ENGINE']=='django.db.backends.sqlite3':
        if s.DATABASES['default']['NAME'] and not os.path.exists(s.DATABASES['default']['NAME']):
            os.mkdir(os.path.dirname(s.DATABASES['default']['NAME']))
    if s.STATIC_ROOT and os.path.isabs(s.STATIC_ROOT) and not os.path.exists(s.STATIC_ROOT):
        os.mkdir(s.STATIC_ROOT)
    if s.MEDIA_ROOT and os.path.isabs(s.MEDIA_ROOT) and not os.path.exists(s.MEDIA_ROOT):
        os.mkdir(s.MEDIA_ROOT)
    if s.TEMPLATE_DIRS:
        for t in s.TEMPLATE_DIRS:
            if not os.path.exists(t) and os.path.sep in t:
                os.mkdir(t)
751663
def create_blueprint(app_path, blueprint, views_code, forms_code, templates_path):
    
    blueprint_path = os.path.join(app_path, blueprint)
    _mkdir_p(blueprint_path)
    # create  blueprint files
    os.chdir(blueprint_path)
    init_code('__init__.py', _init_blueprint_code % (blueprint, blueprint))
    init_code('views.py', views_code)
    init_code('forms.py', forms_code)
    # main blueprint templates
    os.chdir(templates_path)
    blueprint_templates_path = os.path.join(templates_path, blueprint)
    _mkdir_p(blueprint_templates_path)

    return blueprint_templates_path
384174
def new(self, fname=None, editorstack=None, text=None):
        
        # If no text is provided, create default content
        empty = False
        try:
            if text is None:
                default_content = True
                text, enc = encoding.read(self.TEMPLATE_PATH)
                enc_match = re.search(r'-*- coding: ?([a-z0-9A-Z\-]*) -*-',
                                      text)
                if enc_match:
                    enc = enc_match.group(1)
                # Initialize template variables
                # Windows
                username = encoding.to_unicode_from_fs(
                                os.environ.get('USERNAME', ''))
                # Linux, Mac OS X
                if not username:
                    username = encoding.to_unicode_from_fs(
                                   os.environ.get('USER', '-'))
                VARS = {
                    'date': time.ctime(),
                    'username': username,
                }
                try:
                    text = text % VARS
                except Exception:
                    pass
            else:
                default_content = False
                enc = encoding.read(self.TEMPLATE_PATH)[1]
        except (IOError, OSError):
            text = ''
            enc = 'utf-8'
            default_content = True
            empty = True

        create_fname = lambda n: to_text_string(_("untitled")) + ("%d.py" % n)
        # Creating editor widget
        if editorstack is None:
            current_es = self.get_current_editorstack()
        else:
            current_es = editorstack
        created_from_here = fname is None
        if created_from_here:
            while True:
                fname = create_fname(self.untitled_num)
                self.untitled_num += 1
                if not osp.isfile(fname):
                    break
            basedir = getcwd_or_home()

            if self.main.projects.get_active_project() is not None:
                basedir = self.main.projects.get_active_project_path()
            else:
                c_fname = self.get_current_filename()
                if c_fname is not None and c_fname != self.TEMPFILE_PATH:
                    basedir = osp.dirname(c_fname)
            fname = osp.abspath(osp.join(basedir, fname))
        else:
            # QString when triggered by a Qt signal
            fname = osp.abspath(to_text_string(fname))
            index = current_es.has_filename(fname)
            if index is not None and not current_es.close_file(index):
                return

        # Creating the editor widget in the first editorstack (the one that
        # can't be destroyed), then cloning this editor widget in all other
        # editorstacks:
        finfo = self.editorstacks[0].new(fname, enc, text, default_content,
                                         empty)
        finfo.path = self.main.get_spyder_pythonpath()
        self._clone_file_everywhere(finfo)
        current_editor = current_es.set_current_filename(finfo.filename)
        self.register_widget_shortcuts(current_editor)
        if not created_from_here:
            self.save(force=True)
568791
def _export_single_project(self):
        
        expanded_dic = self.workspace.copy()

        # TODO 0xc0170: fix misc , its a list with a dictionary
        if 'misc' in expanded_dic and bool(expanded_dic['misc']):
            print ("Using deprecated misc options for coide. Please use template project files.")

        groups = self._get_groups(self.workspace)
        expanded_dic['groups'] = {}
        for group in groups:
            expanded_dic['groups'][group] = []
        self._iterate(self.workspace, expanded_dic)

        # generic tool template specified or project
        if expanded_dic['template']:
            for template in expanded_dic['template']:
                template = join(getcwd(), template)
                if splitext(template)[1] == '.coproj' or re.match('.*\.coproj.tmpl$', template):
                    try:
                        coproj_dic = xmltodict.parse(open(template))
                    except IOError:
                        logger.info("Template file %s not found. Using default template" % template)
                        coproj_dic = self.definitions.coproj_file
                else:
                    logger.info("Template file %s contains unknown template extension (.coproj/.coproj.tmpl are valid). Using default one" % template)
                    coproj_dic = self.definitions.coproj_file
        elif 'coide' in self.env_settings.templates.keys():
            # template overrides what is set in the yaml files
            for template in self.env_settings.templates['coide']:
                template = join(getcwd(), template)
                if splitext(template)[1] == '.coproj' or re.match('.*\.coproj.tmpl$', template):
                    try:
                        coproj_dic = xmltodict.parse(open(template))
                    except IOError:
                        logger.info("Template file %s not found. Using default template" % template)
                        coproj_dic = self.definitions.coproj_file
                else:
                    logger.info("Template file %s contains unknown template extension (.coproj/.coproj.tmpl are valid). Using default one" % template)
                    coproj_dic = self.definitions.coproj_file
        else:
            # setting values from the yaml files
            coproj_dic = self.definitions.coproj_file

        # set name and target
        try:
            coproj_dic['Project']['@name'] = expanded_dic['name']
        except KeyError:
            raise RuntimeError("The coide template is not valid .coproj file")

        coproj_dic['Project']['Target']['@name'] = expanded_dic['name']
        # library/exe
        coproj_dic['Project']['Target']['BuildOption']['Output']['Option'][0]['@value'] = 0 if expanded_dic['output_type'] == 'exe' else 1

        # Fill in progen data to the coproj_dic
        self._coproj_set_files(coproj_dic, expanded_dic)
        self._coproj_set_macros(coproj_dic, expanded_dic)
        self._coproj_set_includepaths(coproj_dic, expanded_dic)
        self._coproj_set_linker(coproj_dic, expanded_dic)

        # set target only if defined, otherwise use from template/default one
        if expanded_dic['target']:
            pro_def = ProGenDef('coide')
            if not pro_def.is_supported(expanded_dic['target'].lower()):
                raise RuntimeError("Target %s is not supported." % expanded_dic['target'].lower())
            mcu_def_dic = pro_def.get_tool_definition(expanded_dic['target'].lower())
            if not mcu_def_dic:
                 raise RuntimeError(
                    "Mcu definitions were not found for %s. Please add them to https://github.com/0xc0170/project_generator_definitions"
                    % expanded_dic['target'].lower())
            self._normalize_mcu_def(mcu_def_dic)
            logger.debug("Mcu definitions: %s" % mcu_def_dic)
            # correct attributes from definition, as yaml does not allowed multiple keys (=dict), we need to
            # do this magic.
            for k, v in mcu_def_dic['Device'].items():
                del mcu_def_dic['Device'][k]
                mcu_def_dic['Device']['@' + k] = str(v)
            memory_areas = []
            for k, v in mcu_def_dic['MemoryAreas'].items():
                # ??? duplicate use of k
                for k, att in v.items():
                    del v[k]
                    v['@' + k] = str(att)
                memory_areas.append(v)

            coproj_dic['Project']['Target']['Device'].update(mcu_def_dic['Device'])
            # TODO 0xc0170: fix debug options
            # coproj_dic['Project']['Target']['DebugOption'].update(mcu_def_dic['DebugOption'])
            coproj_dic['Project']['Target']['BuildOption']['Link']['MemoryAreas']['Memory'] = memory_areas

            # TODO 0xc0170: create a method and look at finding that option if we can reuse already defined method
            try:
                # find debugger definitions in the list of options
                index = 0
                for option in coproj_dic['Project']['Target']['DebugOption']['Option']:
                    # ??? k, v not used ???
                    for k, v in option.items():
                        if option['@name'] == 'org.coocox.codebugger.gdbjtag.core.adapter':
                            found = index
                index += 1
                debugger_name =pro_def.get_debugger(expanded_dic['target'])['name']
                coproj_dic['Project']['Target']['DebugOption']['Option'][found]['@value'] = self.definitions.debuggers[debugger_name]['Target']['DebugOption']['org.coocox.codebugger.gdbjtag.core.adapter']
            except (TypeError, KeyError) as err:
                pass


        # get debugger definitions
        if expanded_dic['debugger']:
            try:
                # find debugger definitions in the list of options
                index = 0
                for option in coproj_dic['Project']['Target']['DebugOption']['Option']:
                    # ??? k, v not used ???
                    for k, v in option.items():
                        if option['@name'] == 'org.coocox.codebugger.gdbjtag.core.adapter':
                            found = index
                index += 1
                coproj_dic['Project']['Target']['DebugOption']['Option'][found]['@value'] = self.definitions.debuggers[expanded_dic['debugger']]['Target']['DebugOption']['org.coocox.codebugger.gdbjtag.core.adapter']
            except KeyError:
                raise RuntimeError("Debugger %s is not supported" % expanded_dic['debugger'])

        # Project file
        # somehow this xml is not compatible with coide, coide v2.0 changing few things, lets use jinja
        # for now, more testing to get xml output right. Jinja template follows the xml dictionary,which is
        # what we want anyway.
        # coproj_xml = xmltodict.unparse(coproj_dic, pretty=True)
        project_path, projfile = self.gen_file_jinja(
            'coide.coproj.tmpl', coproj_dic, '%s.coproj' % expanded_dic['name'], expanded_dic['output_dir']['path'])
        return project_path, projfile
1111333
def create_project( name, description = nil)
      post_params = {
        :body => {name: name, description: description}.to_json,
        :headers => Logan::Client.headers.merge({'Content-Type' => 'application/json'})
      }

      response = Logan::Client.post "/project_templates/#{@id}/projects.json", post_params
      Logan::Project.new response
    end
891960
def create(self, project, title, href, **attrs):
        
        attrs.update({'project': project, 'title': title, 'href': href})
        return self._new_resource(payload=attrs)
831904
def create(project: 'projects.Project') -> COMPONENT:
    

    source_path = get_source_path()
    if not source_path:
        return COMPONENT([], [])

    output_slug = 'components/plotly/plotly.min.js'
    output_path = os.path.join(project.output_directory, output_slug)

    return COMPONENT(
        includes=[WEB_INCLUDE(
            name='plotly',
            src='/{}'.format(output_slug)
        )],
        files=[file_io.FILE_COPY_ENTRY(
            source=source_path,
            destination=output_path
        )]
    )
1349107
def _newproject(command, path, name, settings):
    
    key = None
    title = _get_project_title()
    template = _get_template(settings)

    # Init repo
    git = sh.git.bake(_cwd=path)
    puts(git.init())

    if template.get("url"):
        # Create submodule
        puts(git.submodule.add(template['url'], '_blueprint'))
        puts(git.submodule.update(*['--init']))

        # Create spreadsheet
        key = _create_spreadsheet(name, title, path, settings)

        # Copy html files
        puts(colored.green("\nCopying html files..."))
        files = glob.iglob(os.path.join(path, "_blueprint", "*.html"))
        for file in files:
            if os.path.isfile(file):
                dir, filename = os.path.split(file)
                if not filename.startswith("_") and not filename.startswith("."):
                    puts("Copying {0} to {1}".format(filename, path))
                    shutil.copy2(file, path)
        ignore = os.path.join(path, "_blueprint", ".gitignore")
        if os.path.isfile(ignore):
            shutil.copy2(ignore, path)
    else:
        empty_index_path = os.path.join(path, "index.html")
        open(empty_index_path, "w")

    # Create config file
    _copy_config_template(name, title, template, path, key, settings)

    # Commit
    puts(colored.green("\nInitial commit"))
    puts(git.add('.'))
    puts(git.commit(m='Created {0} from {1}'.format(name, template['name'])))

    _install_requirements(path)

    # Get site, run hook
    with ensure_project(command, args, path) as site:
        site.call_hook("newproject", site, git)

    # Messages
    puts("\nAll done! To preview your new project, type:\n")
    puts("{0} {1}".format(colored.green("tarbell switch"), colored.green(name)))
    puts("\nor\n")
    puts("{0}".format(colored.green("cd %s" % path)))
    puts("{0}".format(colored.green("tarbell serve\n")))

    puts("\nYou got this!\n")
488513
def process_templates(input_dir, target_dir, context):
    
    if not target_dir.endswith('/'):
        target_dir = "{}/".format(target_dir)
    if not os.path.exists(target_dir):
        LOGGER.info('Creating: {}'.format(target_dir))
        os.makedirs(target_dir)
    replicate_directory_tree(input_dir, target_dir)
    templates = find_templates(input_dir)
    for templ in templates:
        output_file = templ.replace(input_dir, target_dir)
        output_file = output_file[:-len('.mustache')]
        render_template(templ,  output_file, context)
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
153699
def mustache_template_build(dir, template_file, logic_file)
      # Get the class name from an underscore-named file
      logic_class_name = underscore_to_camelcase(logic_file)
      # Output file should match the syntax of the mustaches config
      output_file = logic_file
      # Now we can name the logic_file to underscored version
      logic_file = camelcase_to_underscore(logic_file)
      # Require logic file, used to generate content from template
      require File.join(project_root, camelcase_to_underscore(dir), logic_file)
      # Create relevant directory path
      FileUtils.mkdir_p File.join(build_path, dir.to_s)
      # Instantiate class from required file
      mustache = Kernel.const_get(logic_class_name).new
      # Set the template file
      mustache.template_file = File.join(project_root, camelcase_to_underscore(dir), template_file) + ".html.mustache"
      # Get the name of the file we will write to after it's template is processed
      build_file = File.join(build_path, dir, "#{output_file}.html")
      File.open(build_file, 'w') do |f|
        f.write(mustache.render)
      end
    end
7679
def generic_insert_with_folder(folder_name, file_name, template_name, args):
    
    # First we make sure views are a package instead a file
    if not os.path.isdir(
        os.path.join(
            args['django_application_folder'],
            folder_name
        )
    ):
        os.mkdir(os.path.join(args['django_application_folder'], folder_name))
        codecs.open(
            os.path.join(
                args['django_application_folder'],
                folder_name,
                '__init__.py'
            ),
            'w+'
        )

    view_file = create_or_open(
        os.path.join(
            folder_name,
            '{}.py'.format(file_name)
        ), 
        '', 
        args
    )
    # Load content from template
    render_template_with_args_in_file(
        view_file, 
        os.path.join(
            BASE_TEMPLATES_DIR, 
            template_name
        ),
        model_name=args['model_name'],
        model_prefix=args['model_prefix'],
        model_name_lower=args['model_name'].lower(),
        application_name=args['django_application_folder'].split("/")[-1]
    )
    view_file.close()
751365
def create_template(self):
        """"""
        template = self.template
        variables = self.get_variables()
        template.add_version('2010-09-09')
        template.add_description('Static Website - Bucket and Distribution')

        # Conditions
        template.add_condition(
            'AcmCertSpecified',
            And(Not(Equals(variables['AcmCertificateArn'].ref, '')),
                Not(Equals(variables['AcmCertificateArn'].ref, 'undefined')))
        )
        template.add_condition(
            'AliasesSpecified',
            And(Not(Equals(Select(0, variables['Aliases'].ref), '')),
                Not(Equals(Select(0, variables['Aliases'].ref), 'undefined')))
        )
        template.add_condition(
            'CFLoggingEnabled',
            And(Not(Equals(variables['LogBucketName'].ref, '')),
                Not(Equals(variables['LogBucketName'].ref, 'undefined')))
        )
        template.add_condition(
            'DirectoryIndexSpecified',
            And(Not(Equals(variables['RewriteDirectoryIndex'].ref, '')),
                Not(Equals(variables['RewriteDirectoryIndex'].ref, 'undefined')))  # noqa
        )
        template.add_condition(
            'WAFNameSpecified',
            And(Not(Equals(variables['WAFWebACL'].ref, '')),
                Not(Equals(variables['WAFWebACL'].ref, 'undefined')))
        )

        # Resources
        oai = template.add_resource(
            cloudfront.CloudFrontOriginAccessIdentity(
                'OAI',
                CloudFrontOriginAccessIdentityConfig=cloudfront.CloudFrontOriginAccessIdentityConfig(  # noqa pylint: disable=line-too-long
                    Comment='CF access to website'
                )
            )
        )

        bucket = template.add_resource(
            s3.Bucket(
                'Bucket',
                AccessControl=s3.Private,
                LifecycleConfiguration=s3.LifecycleConfiguration(
                    Rules=[
                        s3.LifecycleRule(
                            NoncurrentVersionExpirationInDays=90,
                            Status='Enabled'
                        )
                    ]
                ),
                VersioningConfiguration=s3.VersioningConfiguration(
                    Status='Enabled'
                ),
                WebsiteConfiguration=s3.WebsiteConfiguration(
                    IndexDocument='index.html',
                    ErrorDocument='error.html'
                )
            )
        )
        template.add_output(Output(
            'BucketName',
            Description='Name of website bucket',
            Value=bucket.ref()
        ))

        allowcfaccess = template.add_resource(
            s3.BucketPolicy(
                'AllowCFAccess',
                Bucket=bucket.ref(),
                PolicyDocument=PolicyDocument(
                    Version='2012-10-17',
                    Statement=[
                        Statement(
                            Action=[awacs.s3.GetObject],
                            Effect=Allow,
                            Principal=Principal(
                                'CanonicalUser',
                                oai.get_att('S3CanonicalUserId')
                            ),
                            Resource=[
                                Join('', [bucket.get_att('Arn'),
                                          '/*'])
                            ]
                        )
                    ]
                )
            )
        )

        cfdirectoryindexrewriterole = template.add_resource(
            iam.Role(
                'CFDirectoryIndexRewriteRole',
                Condition='DirectoryIndexSpecified',
                AssumeRolePolicyDocument=PolicyDocument(
                    Version='2012-10-17',
                    Statement=[
                        Statement(
                            Effect=Allow,
                            Action=[awacs.sts.AssumeRole],
                            Principal=Principal('Service',
                                                ['lambda.amazonaws.com',
                                                 'edgelambda.amazonaws.com'])
                        )
                    ]
                ),
                ManagedPolicyArns=[
                    IAM_ARN_PREFIX + 'AWSLambdaBasicExecutionRole'
                ]
            )
        )

        cfdirectoryindexrewrite = template.add_resource(
            awslambda.Function(
                'CFDirectoryIndexRewrite',
                Condition='DirectoryIndexSpecified',
                Code=awslambda.Code(
                    ZipFile=Join(
                        '',
                        ["'use strict';\n",
                         "exports.handler = (event, context, callback) => {\n",
                         "\n",
                         "    // Extract the request from the CloudFront event that is sent to Lambda@Edge\n",  # noqa pylint: disable=line-too-long
                         "    var request = event.Records[0].cf.request;\n",
                         "    // Extract the URI from the request\n",
                         "    var olduri = request.uri;\n",
                         "    // Match any '/' that occurs at the end of a URI. Replace it with a default index\n",  # noqa pylint: disable=line-too-long
                         "    var newuri = olduri.replace(/\\/$/, '\\/",
                         variables['RewriteDirectoryIndex'].ref,
                         "');\n",  # noqa
                         "    // Log the URI as received by CloudFront and the new URI to be used to fetch from origin\n",  # noqa pylint: disable=line-too-long
                         "    console.log(\"Old URI: \" + olduri);\n",
                         "    console.log(\"New URI: \" + newuri);\n",
                         "    // Replace the received URI with the URI that includes the index page\n",  # noqa pylint: disable=line-too-long
                         "    request.uri = newuri;\n",
                         "    // Return to CloudFront\n",
                         "    return callback(null, request);\n",
                         "\n",
                         "};\n"]
                    )
                ),
                Description='Rewrites CF directory HTTP requests to default page',  # noqa
                Handler='index.handler',
                Role=cfdirectoryindexrewriterole.get_att('Arn'),
                Runtime='nodejs8.10'
            )
        )

        # Generating a unique resource name here for the Lambda version, so it
        # updates automatically if the lambda code changes
        code_hash = hashlib.md5(
            str(cfdirectoryindexrewrite.properties['Code'].properties['ZipFile'].to_dict()).encode()  # noqa pylint: disable=line-too-long
        ).hexdigest()

        cfdirectoryindexrewritever = template.add_resource(
            awslambda.Version(
                'CFDirectoryIndexRewriteVer' + code_hash,
                Condition='DirectoryIndexSpecified',
                FunctionName=cfdirectoryindexrewrite.ref()
            )
        )

        # If custom associations defined, use them
        if variables['lambda_function_associations']:
            lambda_function_associations = [
                cloudfront.LambdaFunctionAssociation(
                    EventType=x['type'],
                    LambdaFunctionARN=x['arn']
                ) for x in variables['lambda_function_associations']
            ]
        else:  # otherwise fallback to pure CFN condition
            lambda_function_associations = If(
                'DirectoryIndexSpecified',
                [cloudfront.LambdaFunctionAssociation(
                    EventType='origin-request',
                    LambdaFunctionARN=cfdirectoryindexrewritever.ref()
                )],
                NoValue
            )

        cfdistribution = template.add_resource(
            get_cf_distribution_class()(
                'CFDistribution',
                DependsOn=allowcfaccess.title,
                DistributionConfig=get_cf_distro_conf_class()(
                    Aliases=If(
                        'AliasesSpecified',
                        variables['Aliases'].ref,
                        NoValue
                    ),
                    Origins=[
                        get_cf_origin_class()(
                            DomainName=Join(
                                '.',
                                [bucket.ref(),
                                 's3.amazonaws.com']),
                            S3OriginConfig=get_s3_origin_conf_class()(
                                OriginAccessIdentity=Join(
                                    '',
                                    ['origin-access-identity/cloudfront/',
                                     oai.ref()])
                            ),
                            Id='S3Origin'
                        )
                    ],
                    DefaultCacheBehavior=cloudfront.DefaultCacheBehavior(
                        AllowedMethods=['GET', 'HEAD'],
                        Compress=False,
                        DefaultTTL='86400',
                        ForwardedValues=cloudfront.ForwardedValues(
                            Cookies=cloudfront.Cookies(Forward='none'),
                            QueryString=False,
                        ),
                        LambdaFunctionAssociations=lambda_function_associations,  # noqa
                        TargetOriginId='S3Origin',
                        ViewerProtocolPolicy='redirect-to-https'
                    ),
                    DefaultRootObject='index.html',
                    Logging=If(
                        'CFLoggingEnabled',
                        cloudfront.Logging(
                            Bucket=Join('.',
                                        [variables['LogBucketName'].ref,
                                         's3.amazonaws.com'])
                        ),
                        NoValue
                    ),
                    PriceClass=variables['PriceClass'].ref,
                    Enabled=True,
                    WebACLId=If(
                        'WAFNameSpecified',
                        variables['WAFWebACL'].ref,
                        NoValue
                    ),
                    ViewerCertificate=If(
                        'AcmCertSpecified',
                        cloudfront.ViewerCertificate(
                            AcmCertificateArn=variables['AcmCertificateArn'].ref,  # noqa
                            SslSupportMethod='sni-only'
                        ),
                        NoValue
                    )
                )
            )
        )
        template.add_output(Output(
            'CFDistributionId',
            Description='CloudFront distribution ID',
            Value=cfdistribution.ref()
        ))
        template.add_output(
            Output(
                'CFDistributionDomainName',
                Description='CloudFront distribution domain name',
                Value=cfdistribution.get_att('DomainName')
            )
        )
452309
def __main(draft, directory, project_name, project_version, project_date, answer_yes):
    
    directory = os.path.abspath(directory)
    config = load_config(directory)
    to_err = draft

    click.echo("Loading template...", err=to_err)
    if config["template"] is None:
        template = pkg_resources.resource_string(
            __name__, "templates/template.rst"
        ).decode("utf8")
    else:
        with open(config["template"], "rb") as tmpl:
            template = tmpl.read().decode("utf8")

    click.echo("Finding news fragments...", err=to_err)

    definitions = config["types"]

    if config.get("directory"):
        base_directory = os.path.abspath(config["directory"])
        fragment_directory = None
    else:
        base_directory = os.path.abspath(
            os.path.join(directory, config["package_dir"], config["package"])
        )
        fragment_directory = "newsfragments"

    fragments, fragment_filenames = find_fragments(
        base_directory, config["sections"], fragment_directory, definitions
    )

    click.echo("Rendering news fragments...", err=to_err)
    fragments = split_fragments(fragments, definitions)
    rendered = render_fragments(
        # The 0th underline is used for the top line
        template,
        config["issue_format"],
        fragments,
        definitions,
        config["underlines"][1:],
        config["wrap"],
    )

    if project_version is None:
        project_version = get_version(
            os.path.join(directory, config["package_dir"]), config["package"]
        )

    if project_name is None:
        package = config.get("package")
        if package:
            project_name = get_project_name(
                os.path.abspath(os.path.join(directory, config["package_dir"])), package
            )
        else:
            # Can't determine a project_name, but maybe it is not needed.
            project_name = ""

    if project_date is None:
        project_date = _get_date()

    top_line = config["title_format"].format(
        name=project_name, version=project_version, project_date=project_date
    )
    top_line += u"\n" + (config["underlines"][0] * len(top_line)) + u"\n"

    if draft:
        click.echo(
            "Draft only -- nothing has been written.\n"
            "What is seen below is what would be written.\n",
            err=to_err,
        )
        click.echo("%s\n%s" % (top_line, rendered))
    else:
        click.echo("Writing to newsfile...", err=to_err)
        start_line = config["start_line"]
        append_to_newsfile(
            directory, config["filename"], start_line, top_line, rendered
        )

        click.echo("Staging newsfile...", err=to_err)
        stage_newsfile(directory, config["filename"])

        click.echo("Removing news fragments...", err=to_err)
        remove_files(fragment_filenames, answer_yes)

        click.echo("Done!", err=to_err)
351358
def create_new(projectname):
    """"""
    git_url = "https://github.com/moluwole/Bast_skeleton"
    path = os.path.abspath('.') + "/" + projectname
    if not os.path.exists(path):
        os.makedirs(path)

    click.echo(Fore.GREEN + '    ___  ___   __________')
    click.echo(Fore.GREEN + '  / _ )/ _ | / __/_  __/')
    click.echo(Fore.GREEN + ' / _  / __ |_\ \  / /')
    click.echo(Fore.GREEN + '/____/_/ |_/___/ /_/')

    click.echo(Fore.GREEN + "Creating Project at %s.... " % path)
    click.echo(Fore.GREEN + "Pulling Project Skeleton from Repo")
    try:
        Repo.clone_from(git_url, path)

        click.echo(Fore.GREEN + "Setting up project")

        shutil.rmtree(path + "/.git")

        if not os.path.exists('/.env'):
            shutil.copy(path + '/.env.example', path + '/.env')

        env_file = path + "/.env"
        if not os.path.isfile(env_file):
            shutil.copy('.env.example', '.env')
        call(['panther', 'generate:key', path])

        click.echo(Fore.GREEN + "New Bast Project created at  %s " % path)
    except Exception as e:
        click.echo(Fore.RED + "An error occurred creating a new project. Try Again.\n Reason: {}".format(e))