Creates the following structure:
    /plugins
        __init__.py
        hello.py
    /templates
        blank.html
    .gitignore
    run_will.py
    requirements.txt
    Procfile
    README.md
12147
def main():
    

    print_head()
    puts("Welcome to the will project generator.")
    puts("")

    if args.config_dist_only:
        print("Generating config.py.dist...")

    else:
        print("\nGenerating will scaffold...")

    current_dir = os.getcwd()
    plugins_dir = os.path.join(current_dir, "plugins")
    templates_dir = os.path.join(current_dir, "templates")

    if not args.config_dist_only:
        print("  /plugins")
        # Set up the directories
        if not os.path.exists(plugins_dir):
            os.makedirs(plugins_dir)

        print("     __init__.py")
        # Create the plugins __init__.py
        with open(os.path.join(plugins_dir, "__init__.py"), 'w+') as f:
            pass

        print("     morning.py")
        # Create the morning plugin
        morning_file_path = os.path.join(plugins_dir, "morning.py")
        if not os.path.exists(morning_file_path):
            with open(morning_file_path, 'w+') as f:
                f.write("""from will.plugin import WillPlugin
from will.decorators import respond_to, periodic, hear, randomly, route, rendered_template, require_settings


class MorningPlugin(WillPlugin):

    @respond_to("^good morning")
    def good_morning(self, message):
        self.reply("oh, g'morning!")
""")

        print("  /templates")
        if not os.path.exists(templates_dir):
            os.makedirs(templates_dir)

        print("     blank.html")
        # Create the plugins __init__.py
        with open(os.path.join(templates_dir, "blank.html"), 'w+') as f:
            pass

        print("  .gitignore")
        # Create .gitignore, or at least add shelf.db
        gitignore_path = os.path.join(current_dir, ".gitignore")
        if not os.path.exists(gitignore_path):
            with open(gitignore_path, 'w+') as f:
                f.write("""*.py[cod]
pip-log.txt
shelf.db
        """)
        else:
            append_ignore = False
            with open(gitignore_path, "r+") as f:
                if "shelf.db" not in f.read():
                    append_ignore = True
            if append_ignore:
                with open(gitignore_path, "a") as f:
                    f.write("\nshelf.db\n")

        # Create run_will.py
        print("  run_will.py")
        run_will_path = os.path.join(current_dir, "run_will.py")
        if not os.path.exists(run_will_path):
            with open(run_will_path, 'w+') as f:
                f.write("""#!/usr/bin/env python
from will.main import WillBot

if __name__ == '__main__':
    bot = WillBot()
    bot.bootstrap()
""")
        # And make it executable
        st = os.stat('run_will.py')
        os.chmod("run_will.py", st.st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)

    # Create config.py
        print("  config.py.dist")

    config_path = os.path.join(current_dir, "config.py.dist")
    if not os.path.exists(config_path) or ask_user("! config.py.dist exists.  Overwrite it?"):
        with open(os.path.join(PROJECT_ROOT, "config.py.dist"), "r") as source_f:
            source = source_f.read()
            if args.backends:
                for backend in SERVICE_BACKENDS:
                    if backend in args.backends:
                        _enable_service(backend, source)
                    else:
                        __disable_service(backend, source)
            else:
                # Ask user thru cmd line what backends to enable
                print("\nWill supports a few different service backends.  Let's set up the ones you want:\n")
                source = enable_disable_service("Slack", source)
                source = enable_disable_service("HipChat", source)
                source = enable_disable_service("Rocket.Chat", source)
                source = enable_disable_service("Shell", source)

            with open(config_path, "w+") as f:
                config = source
                f.write(config)

    if not args.config_dist_only:
        print("  requirements.txt")
        # Create requirements.txt
        requirements_path = os.path.join(current_dir, "requirements.txt")
        if not os.path.exists(requirements_path) or ask_user("! requirements.txt exists.  Overwrite it?"):
            with open(requirements_path, 'w+') as f:
                f.write(requirements_txt)

        print("  Procfile")
        # Create Procfile
        requirements_path = os.path.join(current_dir, "Procfile")
        if not os.path.exists(requirements_path):
            with open(requirements_path, 'w+') as f:
                f.write("web: python run_will.py")

        print("  README.md")
        # Create the readme
        readme_path = os.path.join(current_dir, "README.md")
        if not os.path.exists(readme_path):
            with open(readme_path, 'w+') as f:
                f.write("""
This is our bot, a [will](https://github.com/skoczen/will) bot.
    """)

        print("\nDone.")

        print("\n Your will is now ready to go. Run ./run_will.py to get started!")
    else:
        print("\nCreated a config.py.dist.  Open it up to see what's new!\n")
1592
def create(cls, path, encoding='utf-8'):
        """"""
        cmd = [GIT, 'init', '--quiet', '--bare', path]
        subprocess.check_call(cmd)
        return cls(path, encoding)
94017
def _create_configs(cls, site):
        
        provider = cls.name

        cls._render_config('wsgi.py', 'wsgi.py', site)

        # create yaml file
        yaml_template_name = os.path.join(provider, cls.provider_yml_name)
        cls._render_config(cls.provider_yml_name, yaml_template_name, site)

        # create requirements file
        # don't do anything if the requirements file is called requirements.txt and in the root of the project
        requirements_filename = "requirements.txt"
        if site['requirements'] != requirements_filename:   # providers expect the file to be called requirements.txt
            requirements_template_name = os.path.join(provider, requirements_filename)
            cls._render_config(requirements_filename, requirements_template_name, site)

        # create settings file
        settings_template_name = os.path.join(provider, 'settings_%s.py' % provider)
        settings_path = site['django_settings'].replace('.', '/') + '_%s.py' % provider
        cls._render_config(settings_path, settings_template_name, site)
148021
def gitignore_template(self, language):
        
        url = self._build_url('gitignore', 'templates', language)
        json = self._json(self._get(url), 200)
        if not json:
            return ''
        return json.get('source', '')
1146838
def init(self):
        
        self.logger.info('Start initialize dir [%s]', self.basePath)
        # Clean the directory
        for name in os.listdir(self.basePath):
            path = os.path.join(self.basePath, name)
            if os.path.isdir(path):
                shutil.rmtree(path)
            else:
                os.unlink(path)
        # Prepare dirs and files
        self.logger.info('Prepare dirs and files')
        for name in self.DIRS:
            os.mkdir(os.path.join(self.basePath, name))
        with open(os.path.join(self.basePath, self.FILE_INDEX), 'wb') as fd:
            pass
        with open(os.path.join(self.basePath, self.FILE_SERIAL), 'wb') as fd:
            print >>fd, 1000
        # Format the config file
        env = jinja2.Environment(
                loader = jinja2.FileSystemLoader(os.path.dirname(os.path.abspath(__file__))),
                trim_blocks = True,
                lstrip_blocks = True
                )
        template = env.get_template('openssl.config.template')
        content = template.render(basePath = self.basePath)
        with open(os.path.join(self.basePath, self.FILE_CONFIG), 'wb') as fd:
            print >>fd, content
1025719
def create_template(properties)
      template_dir_path = Pathname.new(File.dirname(__FILE__)).join(NEW_TEMPLATE_FOLDER)
      rambaspec_template_file_path = template_dir_path.join(RAMBASPEC_TEMPLATE_NAME)
      code_file_path = template_dir_path.join(CODE_FOLDER)
      tests_file_path = template_dir_path.join(TESTS_FOLDER)

      file_source = IO.read(rambaspec_template_file_path)

      template = Liquid::Template.parse(file_source)
      output = template.render(properties)

      result_name = properties[TEMPLATE_NAME_KEY] + RAMBASPEC_EXTENSION
      result_dir_path = Pathname.new(properties[TEMPLATE_NAME_KEY])

      FileUtils.mkdir_p result_dir_path
      FileUtils.cp_r(code_file_path, result_dir_path)
      FileUtils.cp_r(tests_file_path, result_dir_path)

      File.open(result_dir_path.join(result_name), 'w+') {|f|
        f.write(output)
      }
    end
667838
function buildProcessTemplate(opts, callback) {
  var viewOpt = {
    app: opts.app,
    processName: opts.processName,
    directory: opts.directory,
    port: opts.port,
    command: opts.command,
    logRoot: opts.logRoot,
    num: opts.num,
    envVar: opts.envVar
  };

  renderTemplate(templateFilePath('process.conf', opts.templateOpt), viewOpt, function(err, renderedOutput) {
    if (err) {
      return callback(err.message);
    } else {
      return fs.writeFile(opts.writePath, renderedOutput, function(err) {
	if (err) {
	  return callback(err.message);
	} else {
	  return callback(null);
	}
      });
    }
  });
}
1109895
def main(argv=None, directory=None):
    
    logging.basicConfig(format='%(message)s')

    argv = argv or sys.argv
    arg_dict = parse_quality_args(argv[1:])
    GitPathTool.set_cwd(directory)
    fail_under = arg_dict.get('fail_under')
    tool = arg_dict['violations']
    user_options = arg_dict.get('options')
    if user_options:
        # strip quotes if present
        first_char = user_options[0]
        last_char = user_options[-1]
        if first_char == last_char and first_char in ('"', "'"):
            user_options = user_options[1:-1]
    driver = QUALITY_DRIVERS.get(tool)

    if driver is not None:
        # If we've been given pre-generated reports,
        # try to open the files
        input_reports = []

        for path in arg_dict['input_reports']:
            try:
                input_reports.append(open(path, 'rb'))
            except IOError:
                LOGGER.warning("Could not load '{}'".format(path))
        try:
            reporter = QualityReporter(driver, input_reports, user_options)
            percent_passing = generate_quality_report(
                reporter,
                arg_dict['compare_branch'],
                html_report=arg_dict['html_report'],
                css_file=arg_dict['external_css_file'],
                ignore_staged=arg_dict['ignore_staged'],
                ignore_unstaged=arg_dict['ignore_unstaged'],
                exclude=arg_dict['exclude'],
            )
            if percent_passing >= fail_under:
                return 0
            else:
                LOGGER.error("Failure. Quality is below {}%.".format(fail_under))
                return 1

        except (ImportError, EnvironmentError):
            LOGGER.error(
                "Quality tool not installed: '{}'".format(tool)
            )
            return 1
        # Close any reports we opened
        finally:
            for file_handle in input_reports:
                file_handle.close()

    else:
        LOGGER.error("Quality tool not recognized: '{}'".format(tool))
        return 1
1144029
def reset_templates_dir_to_default_set
        input = gets.chomp.strip.downcase
        if input == "yes" || input == "y"
          FileUtils.delete_dir_contents(FileUtils.join_paths(ROOT_PATH, '/jumpstart_templates'))
          FileUtils.touch(FileUtils.join_paths(ROOT_PATH, '.gitignore'))
          @current_files_and_dirs[:dirs].each {|x| FileUtils.mkdir_p(FileUtils.join_paths(ROOT_PATH, '/jumpstart_templates', x))}
          @current_files_and_dirs[:files].each {|x| FileUtils.cp(FileUtils.join_paths(JumpStart.templates_path, x), FileUtils.join_paths(ROOT_PATH, '/jumpstart_templates', x)) }
          JumpStart.templates_path = FileUtils.join_paths(ROOT_PATH, '/jumpstart_templates')
          JumpStart.dump_jumpstart_setup_yaml
          puts "\n  SUCCESS! the jumpstart templates directory has been set to the default: #{ROOT_PATH}/jumpstart_templates".green
          templates_dir_menu
        elsif input == "no" || input == "n"
          puts "\n You have chosen not to move the jumpstart templates directory, nothing has been changed."
          templates_dir_menu
        else
          puts "\n The command you entered could not be understood, please enter yes '" + "y".yellow + "' or no '" + "n".yellow + "'"
          reset_templates_dir_to_default_set
        end
      end
563185
def template(path, extend_path, out):
    
    files = []

    # add the "extender" template when it exists
    if len(extend_path) > 0:
        # determine the base readme path
        base_path = os.path.dirname(extend_path)
        new_base_path = os.path.join(base_path, "README.{0}.j2".format(out))

        if os.path.exists(new_base_path):
            path = new_base_path

        if os.path.exists(extend_path):
            files = [path, extend_path]
        else:
            ui.error(c.MESSAGES["template_extender_missing"])
            ui.error(extend_path)
            sys.exit(1)
    else:
        files = [path]

    try:
        # Use the subclassed relative environment class
        env = RelEnvironment(trim_blocks=True)

        # Add a unique dict filter, by key.
        # DEPRECATION WARNING: This is only used for backwards compatibility,
        #                      please use the unique filter instead.
        def unique_dict(items, key):
            return {v[key]: v for v in items}.values()

        env.filters["unique_dict"] = unique_dict

        def unique(a):

            # Don’t use the following commented out optimization which is used
            # in ansible/lib/ansible/plugins/filter/mathstuff.py in Ansigenome
            # as it resorts the role dependencies:
            # if isinstance(a,collections.Hashable):
            #     c = set(a)

            c = []
            for x in a:
                if x not in c:
                    c.append(x)
            return c

        env.filters["unique"] = unique

        # create a dictionary of templates
        templates = dict(
            (name, codecs.open(name, "rb", 'UTF-8').read())
            for name in files)
        env.loader = DictLoader(templates)

        # return the final result (the last template in the list)
        return env.get_template(files[len(files) - 1])
    except Exception as err:
        ui.error(c.MESSAGES["template_error"], err)
        sys.exit(1)
773685
def build(templates=None, schemes=None, base_output_dir=None):
    """"""
    template_dirs = templates or get_template_dirs()
    scheme_files = get_scheme_files(schemes)
    base_output_dir = base_output_dir or rel_to_cwd('output')

    # raise LookupError if there is not at least one template or scheme
    # to work with
    if not template_dirs or not scheme_files:
        raise LookupError

    # raise PermissionError if user has no write acces for $base_output_dir
    try:
        os.makedirs(base_output_dir)
    except FileExistsError:
        pass

    if not os.access(base_output_dir, os.W_OK):
        raise PermissionError

    templates = [TemplateGroup(path) for path in template_dirs]

    build_from_job_list(scheme_files, templates, base_output_dir)
    print('Finished building process.')
453232
def init(self, project_name='', template='base', quiet=False, debug=False):
        ''''''

        self.logger.setLevel(DEBUG if debug else WARNING)

        self.logger.info('Project creation started.')

        self.logger.debug(f'Template: {template}')

        template_path = Path(template)

        if not template_path.exists():
            self.logger.debug(
                f'Template not found in {template_path}, looking in installed templates.'
            )

            installed_templates_path = Path(Path(__file__).parent / 'templates')

            installed_templates = [
                item.name for item in installed_templates_path.iterdir() if item.is_dir()
            ]

            self.logger.debug(f'Available templates: {installed_templates}')

            if template in installed_templates:
                self.logger.debug('Template found.')

            else:
                self.logger.debug('Template not found, asking for user input.')

                try:
                    template = prompt(
                        f'Please pick a template from {installed_templates}: ',
                        completer=WordCompleter(installed_templates),
                        validator=BuiltinTemplateValidator(installed_templates)
                    )

                except KeyboardInterrupt:
                    self.logger.warning('Project creation interrupted.')
                    return

            template_path = installed_templates_path / template

            self.logger.debug(f'Template path: {template_path}')

        if not project_name:
            self.logger.debug('Project name not specified, asking for user input.')

            try:
                project_name = prompt('Enter the project name: ')

            except KeyboardInterrupt:
                self.logger.warning('Project creation interrupted.')
                return

        project_slug = slugify(project_name)
        project_path = Path(project_slug)

        properties = {
            'title': project_name,
            'slug': project_slug
        }

        self.logger.debug(f'Project properties: {properties}')

        result = None

        with spinner('Generating project', self.logger, quiet, debug):
            copytree(template_path, project_path)

            text_types = '*.md', '*.yml', '*.txt', '*.py'

            text_file_paths = reduce(
                lambda acc, matches: acc + [*matches],
                (project_path.rglob(text_type) for text_type in text_types),
                []
            )

            for text_file_path in text_file_paths:
                self.logger.debug(f'Processing content of {text_file_path}')
                replace_placeholders(text_file_path, properties)

            for item in project_path.rglob('*'):
                self.logger.debug(f'Processing name of {item}')
                item.rename(Template(item.as_posix()).safe_substitute(properties))

            result = project_path

        if result:
            self.logger.info(f'Result: {result}')

            if not quiet:
                print('─' * 20)
                print(f'Project "{project_name}" created in {result}')
            else:
                print(result)

        else:
            self.logger.critical('Project creation failed.')
            exit(1)
727368
def main():
    """"""
    data = Common.open_file(F_INFO)
    config = Common.open_file(F_CONFIG)
    file_full_path = ""

    env = load_jinja2_env(config['p_template'])

    for index, page in data.iteritems():
        logging.info('Creating ' + index + ' page:')

        template = env.get_template(page['f_template'] + \
            config['f_template_ext'])

        for lang, content in page['content'].items():
            if lang == "NaL":
                if page['f_directory'] != '':
                    Common.make_dir(config['p_build'] + page['f_directory'])

                file_full_path = config['p_build'] + page['f_directory'] + \
                    page['f_name'] +page['f_endtype']
            else:
                if page['f_directory'] != '':
                    Common.make_dir(config['p_build'] + lang + '/' + \
                        page['f_directory'])

                file_full_path = config['p_build'] + lang + '/' + \
                    page['f_directory'] + page['f_name'] +page['f_endtype']

            with open(file_full_path, 'w') as target_file:
                target_file.write(template.render(content))

        logging.info('Page ' + index + ' created.')
1330877
function init(pluginInterface) {
    const pi = pluginInterface;

    // Static contents call
    pi.http.endpoint('get', '*', (req, res, next) => {
        let path = req.path;
        if (path.charAt(path.length-1)=='/') path += 'index.html';

        const pt = pathm.join(pathm.dirname(__filename), 'htdocs', path);
        fs.readFile(pt, (err, data)=>{
            if (err) {
                res.status(404).send('No such resource');
                return;
            }
            if (path==='/js/customize.js') {
                data = data.toString();
                data = data.split('__%%RSA_PUB_KEY%%__')
                    .join('"'+pi.crypt.getPubKey()+'"');
            }
            res.set('Content-Type', mime.getType(path)); // 'text/html; charset=UTF-8'
            res.status(200);

            res.send(data);
        });
    });
}
1054695
def build_requirements(docs_path, package_name="yacms"):
    
    mezz_string = "yacms=="
    project_path = os.path.join(docs_path, "..")
    requirements_file = os.path.join(project_path, package_name,
                                     "project_template", "requirements.txt")
    with open(requirements_file, "r") as f:
        requirements = f.readlines()
    with open(requirements_file, "w") as f:
        f.write("yacms==%s\n" % __version__)
        for requirement in requirements:
            if requirement.strip() and not requirement.startswith(mezz_string):
                f.write(requirement)
29161
def create_napp(cls, meta_package=False):
        
        templates_path = SKEL_PATH / 'napp-structure/username/napp'

        ui_templates_path = os.path.join(templates_path, 'ui')

        username = None
        napp_name = None

        print('--------------------------------------------------------------')
        print('Welcome to the bootstrap process of your NApp.')
        print('--------------------------------------------------------------')
        print('In order to answer both the username and the napp name,')
        print('You must follow this naming rules:')
        print(' - name starts with a letter')
        print(' - name contains only letters, numbers or underscores')
        print(' - at least three characters')
        print('--------------------------------------------------------------')
        print('')
        while not cls.valid_name(username):
            username = input('Please, insert your NApps Server username: ')

        while not cls.valid_name(napp_name):
            napp_name = input('Please, insert your NApp name: ')

        description = input('Please, insert a brief description for your'
                            'NApp [optional]: ')
        if not description:
            # pylint: disable=fixme
            description = '# TODO: <<<< Insert your NApp description here >>>>'
            # pylint: enable=fixme

        context = {'username': username, 'napp': napp_name,
                   'description': description}

        #: Creating the directory structure (username/napp_name)
        os.makedirs(username, exist_ok=True)

        #: Creating ``__init__.py`` files
        with open(os.path.join(username, '__init__.py'), 'w') as init_file:
            init_file.write(f'"""Napps for the user {username}.""""')

        os.makedirs(os.path.join(username, napp_name))

        #: Creating the other files based on the templates
        templates = os.listdir(templates_path)
        templates.remove('ui')
        templates.remove('openapi.yml.template')

        if meta_package:
            templates.remove('main.py.template')
            templates.remove('settings.py.template')

        for tmp in templates:
            fname = os.path.join(username, napp_name,
                                 tmp.rsplit('.template')[0])
            with open(fname, 'w') as file:
                content = cls.render_template(templates_path, tmp, context)
                file.write(content)

        if not meta_package:
            NAppsManager.create_ui_structure(username, napp_name,
                                             ui_templates_path, context)

        print()
        print(f'Congratulations! Your NApp has been bootstrapped!\nNow you '
              'can go to the directory {username}/{napp_name} and begin to '
              'code your NApp.')
        print('Have fun!')
11026
def create_new_project():
    ''''''
    readline.parse_and_bind('tab: complete')

    print \
'''
    xbmcswift2 - A micro-framework for creating XBMC plugins.
    xbmc@jonathanbeluch.com
    --
'''
    print 'I\'m going to ask you a few questions to get this project' \
        ' started.'

    opts = {}

    # Plugin Name
    opts['plugin_name'] = get_valid_value(
        'What is your plugin name?',
        validate_nonblank
    )

    # Plugin ID
    opts['plugin_id'] = get_valid_value(
        'Enter your plugin id.',
        validate_pluginid,
        'plugin.video.%s' % (opts['plugin_name'].lower().replace(' ', ''))
    )

    # Parent Directory
    opts['parent_dir'] = get_valid_value(
        'Enter parent folder (where to create project)',
        validate_isfolder,
        getcwd()
    )
    opts['plugin_dir'] = os.path.join(opts['parent_dir'], opts['plugin_id'])
    assert not os.path.isdir(opts['plugin_dir']), \
        'A folder named %s already exists in %s.' % (opts['plugin_id'],
                                                     opts['parent_dir'])

    # Provider
    opts['provider_name'] = get_valid_value(
        'Enter provider name',
        validate_nonblank,
    )

    # Create the project folder by copying over skel
    copytree(SKEL, opts['plugin_dir'], ignore=ignore_patterns('*.pyc'))

    # Walk through all the new files and fill in with out options
    for root, dirs, files in os.walk(opts['plugin_dir']):
        for filename in files:
            update_file(os.path.join(root, filename), opts)

    print 'Projects successfully created in %s.' % opts['plugin_dir']
    print 'Done.'