def generate_project(self, extra_context=None): ctx = { "project_name": "My Project", "project_description": "add a short project description here", "main_module": "djcoookie", "github_username": "******", "github_repository": "djcoookie", "timezone": "UTC", "django_admin_email": "*****@*****.**", "version": "0.1.0", "celery (y/n)": "n" } if extra_context: assert isinstance(extra_context, dict) ctx.update(extra_context) self.ctx = ctx self.destpath = join(self.root_dir, self.ctx['github_repository']) cookiecutter(template='./', checkout=None, no_input=True, extra_context=ctx) # Build a list containing absolute paths to the generated files paths = [os.path.join(dirpath, file_path) for dirpath, subdirs, files in os.walk(self.destpath) for file_path in files] return paths
def main(template, target, no_input, checkout, verbose): if verbose: logging.basicConfig( format='%(levelname)s %(filename)s: %(message)s', level=logging.DEBUG ) else: logging.basicConfig( format='%(levelname)s: %(message)s', level=logging.INFO ) try: src = os.path.join(target, '.cookiecutterrc') if os.path.exists(src): logger.info("Loading config from %r", src) extra_context = get_config(src) logger.debug("Loaded %r", extra_context) extra_context = extra_context.get('cookiecutter') or extra_context.get('default_context') logger.debug("Loaded %r", extra_context) else: logger.info("No .cookiecutterrc in %r", target) extra_context = None with weave('cookiecutter.main.generate_files', save_context): cookiecutter( template, checkout, no_input, overwrite_if_exists=True, output_dir=os.path.dirname(target), extra_context=extra_context, ) except (OutputDirExistsException, InvalidModeException) as e: click.echo(e) sys.exit(1)
def create(self): parser = argparse.ArgumentParser( description="Create a new xcode project") parser.add_argument("name", help="Name of your project") parser.add_argument("directory", help="Directory where your project live") args = parser.parse_args(sys.argv[2:]) from cookiecutter.main import cookiecutter ctx = Context() template_dir = join(curdir, "tools", "templates") context = { "title": args.name, "project_name": args.name.lower(), "domain_name": "org.kivy.{}".format(args.name.lower()), "project_dir": realpath(args.directory), "version": "1.0.0", "dist_dir": ctx.dist_dir, } cookiecutter(template_dir, no_input=True, extra_context=context) filename = join( getcwd(), "{}-ios".format(args.name.lower()), "{}.xcodeproj".format(args.name.lower()), "project.pbxproj") update_pbxproj(filename) print("--") print("Project directory : {}-ios".format( args.name.lower())) print("XCode project : {0}-ios/{0}.xcodeproj".format( args.name.lower()))
def main(template, no_input, checkout, verbose, replay, overwrite_if_exists, output_dir): """Create a project from a Cookiecutter project template (TEMPLATE).""" if verbose: logging.basicConfig( format=u'%(levelname)s %(filename)s: %(message)s', level=logging.DEBUG ) else: # Log info and above to console logging.basicConfig( format=u'%(levelname)s: %(message)s', level=logging.INFO ) try: cookiecutter( template, checkout, no_input, replay=replay, overwrite_if_exists=overwrite_if_exists, output_dir=output_dir ) except (OutputDirExistsException, InvalidModeException) as e: click.echo(e) sys.exit(1)
def test_cookiecutter_git(): main.cookiecutter("https://github.com/audreyr/cookiecutter-pypackage.git", no_input=True) clone_dir = os.path.join(os.path.expanduser("~/.cookiecutters"), "cookiecutter-pypackage") assert os.path.exists(clone_dir) assert os.path.isdir("python_boilerplate") assert os.path.isfile("python_boilerplate/README.rst") assert os.path.exists("python_boilerplate/setup.py")
def add_pyextension(module, tgtdir, no_input=False, extra=None): r"""Add new extension *module* to *tgtdir*. If *no_input* is ``True``, user will be prompted to answer questions. *extra* is a dictionary of optional key/values passed to cookiecutter as default overrides. If the key 'project_type' exists in extra, then any ``*.rst`` files will be installed in ``tgtdir/../docs`` and any ``test*.py`` will be installed in ``tgtdir/../tests``.""" extra = extra or {} module = os.path.splitext(module)[0] extra['module'] = module extra['year'] = datetime.date.today().year cwd = os.getcwdu() tmpd = tempfile.mkdtemp() try: os.chdir(tmpd) cookiecutter('gh:jamercee/cookiecutter-pyext', extra_context=extra, no_input=no_input) # Look for C++ first, then fallback to .C src = os.path.join(module, module + '_module.cpp') tgt = os.path.join(tgtdir, module + '_module.cpp') if not os.path.exists(src): src = os.path.join(module, module + '.c') tgt = os.path.join(tgtdir, module + '.c') if os.path.exists(tgt): LOG.info(">>> Skipped overwritting target %s", tgt) return LOG.debug("copy %s -> %s", src, tgt) shutil.copyfile(src, tgt) # Is this a project? if 'project_type' in extra: # Copy doc *.rst docdir = os.path.abspath(os.path.join(tgtdir, '../docs')) if os.path.isdir(docdir): src = os.path.join(module, module + '.rst') tgt = os.path.join(docdir, module + '.rst') if os.path.isfile(src) and not os.path.exists(tgt): LOG.debug("copy %s -> %s", src, tgt) shutil.copyfile(src, tgt) # Copy unittest tstdir = os.path.abspath(os.path.join(tgtdir, '../tests')) if os.path.isdir(tstdir): src = os.path.join(module, 'test' + module + '.py') tgt = os.path.join(tstdir, 'test' + module + '.py') if os.path.isfile(src) and not os.path.exists(tgt): LOG.debug("copy %s -> %s", src, tgt) shutil.copyfile(src, tgt) finally: os.chdir(cwd) shutil.rmtree(tmpd, ignore_errors=True)
def generate_project(self, extra_context=None): ctx = { 'project_title': 'Some New Project', 'project_name': 'thenewtestproject', 'author_name': 'Your name', 'author_email': '*****@*****.**', 'domain_name': 'wildfish.com', 'secret_key': 'Change me to a random string!', 'time_zone': 'Europe/London', 'email_user': '', 'email_password': '', 'sentry_dsn': '', 'app_name': 'testthings', 'model_name': 'TestThing' } if extra_context: assert isinstance(extra_context, dict) ctx.update(extra_context) self.ctx = ctx self.destpath = join(self.root_dir, self.ctx['project_name']) cookiecutter(template='./', checkout=None, no_input=True, extra_context=ctx) # Build a list containing absolute paths to the generated files paths = [os.path.join(dirpath, file_path) for dirpath, subdirs, files in os.walk(self.destpath) for file_path in files] return paths
def generate_project(self, extra_context=None): ctx = { "project_name": "My Test Project", "repo_name": "my_test_project", "author_name": "Test Author", "email": "*****@*****.**", "description": "A short description of the project.", "domain_name": "example.com", "version": "0.1.0", "timezone": "UTC", "now": "2015/01/13", "year": "2015" } if extra_context: assert isinstance(extra_context, dict) ctx.update(extra_context) self.ctx = ctx self.destpath = join(self.root_dir, self.ctx['repo_name']) cookiecutter(template='./', checkout=None, no_input=True, extra_context=ctx) # Build a list containing absolute paths to the generated files paths = [os.path.join(dirpath, file_path) for dirpath, subdirs, files in os.walk(self.destpath) for file_path in files] return paths
def test_replay_dump_template_name( monkeypatch, mocker, user_config_data, user_config_file): """Check that replay_dump is called with a valid template_name that is not a relative path. Otherwise files such as ``..json`` are created, which are not just cryptic but also later mistaken for replay files of other templates if invoked with '.' and '--replay'. Change the current working directory temporarily to 'tests/fake-repo-tmpl' for this test and call cookiecutter with '.' for the target template. """ monkeypatch.chdir('tests/fake-repo-tmpl') mock_replay_dump = mocker.patch('cookiecutter.main.dump') mocker.patch('cookiecutter.main.generate_files') cookiecutter( '.', no_input=True, replay=False, config_file=user_config_file, ) mock_replay_dump.assert_called_once_with( user_config_data['replay_dir'], 'fake-repo-tmpl', mocker.ANY, )
def main(): print EXPLANATION # Find the prototype. proto_dir = os.path.abspath(os.path.join(__file__, "../../prototype")) cookiecutter(proto_dir)
def test_cookiecutter_git(self): main.cookiecutter('https://github.com/audreyr/cookiecutter-pypackage.git') logging.debug('Current dir is {0}'.format(os.getcwd())) self.assertFalse(os.path.exists('cookiecutter-pypackage')) self.assertTrue(os.path.isdir('alotofeffort')) self.assertTrue(os.path.isfile('alotofeffort/README.rst')) self.assertTrue(os.path.exists('alotofeffort/setup.py'))
def new(appname, size, database, blueprint, dataview, template, view): base_directory = os.path.dirname(os.path.abspath(__file__)) if size == 'small': cookiecutter_path = '{0}/cookiecutters/small/'.format(base_directory) cookiecutter(cookiecutter_path, no_input=True, extra_context={'repo_name': '{0}'.format(appname)}) if database: add_database_files(appname, base_directory) if blueprint: for blueprintname in blueprint: add_blueprint(appname, blueprintname, base_directory, size) if dataview: for dataviewname in dataview: add_dataview(appname, dataviewname, base_directory, 'snippets/dataview') if template: for templatename in template: add_template(appname, templatename, base_directory) if view: for viewname in view: add_view(appname, viewname, base_directory)
def generate_project(self, extra_context=None): ctx = { "project_name": "Infoscience Units Module", "repo_name": "infoscience_unit_module", "django_project_name": "unit_module", "app_name": "units", "model_name": "Unit", "manager_email": "*****@*****.**", "description": "A short description of the project.", "timezone": "UTC", "now": "2015/11/06", "year": "{{ cookiecutter.now[:4] }}", "use_coveralls" : "y", "use_codacy" : "y", "use_codeclimate" : "y" } if extra_context: assert isinstance(extra_context, dict) ctx.update(extra_context) self.ctx = ctx self.destpath = join(self.root_dir, self.ctx['repo_name']) cookiecutter(template='./', checkout=None, no_input=True, extra_context=ctx) # Build a list containing absolute paths to the generated files paths = [os.path.join(dirpath, file_path) for dirpath, subdirs, files in os.walk(self.destpath) for file_path in files] return paths
def update_template(template_url, root, branch): """Update template branch from a template url""" tmpdir = os.path.join(root, ".git", "cookiecutter") project_slug = os.path.basename(root) config_file = os.path.join(root, ".cookiecutter.json") tmp_workdir = os.path.join(tmpdir, project_slug) # read context from file. context = None if os.path.exists(config_file): with open(config_file, 'r') as fd: context = json.loads(fd.read()) context['project_slug'] = project_slug # create a template branch if necessary if subprocess.run(["git", "rev-parse", "-q", "--verify", branch], cwd=root).returncode != 0: firstref = subprocess.run(["git", "rev-list", "--max-parents=0", "HEAD"], cwd=root, stdout=subprocess.PIPE, universal_newlines=True).stdout.strip() subprocess.run(["git", "branch", branch, firstref]) with TemporaryWorkdir(tmp_workdir, repo=root, branch=branch): # update the template cookiecutter(template_url, no_input=(context != None), extra_context=context, overwrite_if_exists=True, output_dir=tmpdir) # commit to template branch subprocess.run(["git", "add", "-A", "."], cwd=tmp_workdir) subprocess.run(["git", "commit", "-m", "Update template"], cwd=tmp_workdir)
def main(): print EXPLANATION # Get the values. try: while True: short_name = raw_input("Short name: ") if re.match(r"^[a-z][a-z0-9_]+$", short_name): break print "The short name must be a valid Python identifier, all lower-case." while True: class_name = raw_input("Class name: ") if re.match(r"[A-Z][a-zA-Z0-9]+XBlock$", class_name): break print "The class name must be a valid Python class name, ending with XBlock." except KeyboardInterrupt: print "\n** Cancelled **" return # Find the prototype. proto_dir = os.path.abspath(os.path.join(__file__, "../../prototype")) cookiecutter( proto_dir, no_input=True, extra_context={ 'short_name': short_name, 'class_name': class_name, }, )
def test_cookiecutter_template_cleanup(mocker): """ `Call cookiecutter()` with `no_input=True` and templates in the cookiecutter.json file """ mocker.patch( 'tempfile.mkdtemp', return_value='fake-tmp', autospec=True ) mocker.patch( 'cookiecutter.utils.prompt_and_delete', return_value=True, autospec=True ) main.cookiecutter( 'tests/files/fake-repo-tmpl.zip', no_input=True ) assert os.path.isdir('fake-project-templated') # The tmp directory will still exist, but the # extracted template directory *in* the temp directory will not. assert os.path.exists('fake-tmp') assert not os.path.exists('fake-tmp/fake-repo-tmpl')
def init(framework, user): '''initialize a new cookiecutter template''' # Check that cookiecutter template exists for requested framework git_url = 'https://github.com/' framework = framework.lower().replace(' ', '-') mo_url = git_url+user+'/mo-'+framework try: response = requests.head(mo_url) status = response.status_code except requests.exceptions.ConnectionError as e: sys.exit("Encountered an error with the connection.") except Exception as e: sys.exit(e) if status != 200: sys.exit("No '{0}' cookiecutter found at {1}." .format(framework, git_url+user)) # Run cookiecutter template if click.confirm('Ready to start cookiecutter {0}.git ' 'in the current directory.\n' 'Do you want to continue?'.format(mo_url)): try: cookiecutter(mo_url+'.git') except: sys.exit("Problem encounted while cloning '{0}'.git" .format(mo_url))
def main(template, no_input, checkout, verbose, replay, overwrite_if_exists, output_dir): """Create a project from a Cookiecutter project template (TEMPLATE).""" if verbose: logging.basicConfig( format=u'%(levelname)s %(filename)s: %(message)s', level=logging.DEBUG ) else: # Log info and above to console logging.basicConfig( format=u'%(levelname)s: %(message)s', level=logging.INFO ) try: # If you _need_ to support a local template in a directory # called 'help', use a qualified path to the directory. if template == u'help': click.echo(click.get_current_context().get_help()) sys.exit(0) cookiecutter( template, checkout, no_input, replay=replay, overwrite_if_exists=overwrite_if_exists, output_dir=output_dir ) except (OutputDirExistsException, InvalidModeException, FailedHookException) as e: click.echo(e) sys.exit(1)
def main(): """ Execute the test. """ @contextmanager def tmpdir(): """ Enter a self-deleting temporary directory. """ cwd = getcwd() tmp = mkdtemp() try: chdir(tmp) yield tmp finally: rmtree(tmp) chdir(cwd) return template = dirname(dirname(abspath(__file__))) defaults = load(open(join(template, "cookiecutter.json"))) with tmpdir(): cookiecutter(template, no_input=True) chdir(defaults["project_slug"]) check_call(split("cmake -DCMAKE_BUILD_TYPE=Debug")) check_call(split("cmake --build .")) main_app = join(".", defaults["project_slug"]) check_call(split("{:s} -h".format(main_app))) test_app = join("test", "test_{:s}".format(defaults["project_slug"])) check_call(split(test_app)) return 0
def test_cookiecutter_with_custom_config(self): patch_clone = patch('cookiecutter.main.clone', return_value='./') patch_generate_files = patch('cookiecutter.main.generate_files') clone = patch_clone.start() generate_files = patch_generate_files.start() cookiecutters_dir = os.path.join(os.getcwd(), 'tests', 'test-config') config_dict = { 'default_context': {'foo': 1, 'bar': 2}, 'cookiecutters_dir': cookiecutters_dir} # build some fake goodness location = self.util_create_base( full_name='Audrey Roy', email='*****@*****.**') main.cookiecutter(location, config_dict=config_dict, no_input=True) # cleanup the fake goodness self.util_finalize(location) call_kwargs = generate_files.call_args[1] self.assertTrue(call_kwargs['repo_dir'] == location) self.assertTrue('cookiecutter' in call_kwargs['context']) self.assertTrue(call_kwargs['context']['cookiecutter']['foo'] == 1) self.assertTrue(call_kwargs['context']['cookiecutter']['bar'] == 2)
def package(self): print("Creating Python package") cookiecutter("cookiecutter-pymorphy2-dicts", no_input=True, extra_context={ 'lang': 'uk', 'lang_full': 'Ukrainian', 'version': get_version(corpus=False, timestamp=True), })
def test_cookiecutter_templated_context(): """ `Call cookiecutter()` with `no_input=True` and templates in the cookiecutter.json file """ main.cookiecutter("tests/fake-repo-tmpl", no_input=True) assert os.path.isdir("fake-project-templated")
def generate_project(self, extra_context=None): ctx = { "project_name": "Wagtail Project", "project_slug": "wagtail_project", "version_control_system": "hg", "author_name": "Your Name", "email": "Your email", "description": "A short description of the project.", "timezone": "UTC", "now": "2015/04/16", "year": "2015", "production_host_name": "example.org", "use_ssl_in_production": "true", "staging_host_name": "staging.example.org", "use_vagrant_staging": "true" } if extra_context: assert isinstance(extra_context, dict) ctx.update(extra_context) self.ctx = ctx self.destpath = join(self.root_dir, self.ctx['project_slug']) cookiecutter( template='./', checkout=None, no_input=True, extra_context=ctx ) # Build a list containing absolute paths to the generated files paths = [os.path.join(dirpath, file_path) for dirpath, subdirs, files in os.walk(self.destpath) for file_path in files] return paths
def main(): """ Execute the test. """ @contextmanager def tmpdir(): """ Enter a self-deleting temporary directory. """ cwd = getcwd() tmp = mkdtemp() try: chdir(tmp) yield tmp finally: rmtree(tmp) chdir(cwd) return template = dirname(dirname(abspath(__file__))) defaults = load(open(join(template, "cookiecutter.json"))) with tmpdir(): cookiecutter(template, no_input=True) chdir(defaults["project_name"]) virtualenv = "virtualenv venv" check_call(split(virtualenv)) install = "venv/bin/pip install ." for name in "requirements.txt", "test/requirements.txt": install = " ".join((install, "--requirement={:s}".format(name))) check_call(split(install)) pytest = "venv/bin/pytest --verbose test" check_call(split(pytest)) return 0
def execute_nose(*args): with TemporaryDirectory() as temp_dir: try: boilerplate = None project_dir = os.path.join(temp_dir, project_name) requirements = os.path.join(project_dir, 'requirements.txt') cookiecutter( cookiecutter_dir, no_input=True, extra_context=extra_context, output_dir=temp_dir ) if project_dir not in sys.path: sys.path.append(project_dir) try: import boilerplate from boilerplate.testsuite import main except ImportError: pip.main(['install', '-r', requirements]) import boilerplate from boilerplate.testsuite import main return main() except SystemExit as x: if hasattr(x, 'message'): print("Found error {0}: {1}".format(x.code, x.message)) return not x.code else: return 1
def main(template, no_input, checkout, api, web): context=dict(today=datetime.now().strftime('%Y-%m-%d')) if api: context['has_api'] = True if web: context['has_web'] = True cookiecutter(template, checkout, no_input, extra_context=context)
def test_run_cookiecutter_and_plugin_tests(testdir): cookiecutter(TEMPLATE, no_input=True) project_root = 'pytest-foobar' assert os.path.isdir(project_root) install_plugin_and_run_tests(project_root, testdir.runpytest)
def test_template(self): main.cookiecutter(self.tmpldir, checkout=False, no_input=True) os.chdir(os.path.join(self.wd, 'project_name')) for filename in self.scripts: self.assertTrue(os.path.isfile(filename), filename + ' not generated') for filename in self.filenames: self.assertTrue(os.path.isfile(filename), filename + ' not generated') ret = subprocess.call( 'bin/django-manage syncdb --noinput --migrate', shell=True) self.assertEqual(ret, 0) tox = os.path.join(self.cwd, 'bin', 'tox') if not os.path.isfile(tox): tox = 'tox' ret = subprocess.call(tox, shell=True) self.assertEqual(ret, 0) ret = subprocess.call('bin/gulp test', shell=True) self.assertEqual(ret, 0) ret = subprocess.call('flake8', shell=True) self.assertEqual(ret, 0)
def run(self, path_arg=None): if not cookiecutter_available: raise Exception('Cookiecutter is not available on your computer, more information can be found here: https://cookiecutter.readthedocs.io/en/latest/installation.html#install-cookiecutter') app_template = None if path_arg: for template in APP_TEMPLATES: if template['name'] == path_arg: app_template = template if not app_template: print_info('Available app templates:') for (index, template) in enumerate(APP_TEMPLATES): print('[{}] {} - {}'.format(index + 1, template['name'], template['display'])) choice = input('Choose an app template [1]: ').strip() if not choice: choice = '1' try: choice = int(choice) except ValueError: raise Exception('Invalid choice') if choice > len(APP_TEMPLATES) or choice < 1: raise Exception('Invalid choice') app_template = APP_TEMPLATES[choice - 1] print_info('Generating new app from template: {}'.format(app_template['display'])) cookiecutter(app_template['url']) print_info('Your new app has been generated, go to the app\'s directory and run clickable to get started')
def test_cookiecutter_local_with_input(self): main.cookiecutter('tests/fake-repo-pre/', no_input=False) self.assertTrue(os.path.isdir('tests/fake-repo-pre/{{cookiecutter.repo_name}}')) self.assertFalse(os.path.isdir('tests/fake-repo-pre/fake-project')) self.assertTrue(os.path.isdir('fake-project')) self.assertTrue(os.path.isfile('fake-project/README.rst')) self.assertFalse(os.path.exists('fake-project/json/'))
def recurse_submodule(template): commit = False # get the cloned repo config_dict = get_user_config() print(config_dict) repo_dir, cleanup = determine_repo_dir( template=template, checkout=None, no_input=True, abbreviations=config_dict['abbreviations'], clone_to_dir=config_dict['cookiecutters_dir'] ) # run a git submodule update print("repo_dir: ", repo_dir) # check any submodule not initialzed result = subprocess.run(["git", "submodule", "status"], cwd=repo_dir , stdout=subprocess.PIPE) output = result.stdout.decode() print(output) if (output[0] != ' ') : subprocess.run(["git", "submodule", "sync", "--recursive"], cwd=repo_dir) subprocess.run(["git", "submodule", "update", "--init", "--recursive"], cwd=repo_dir) # remove this folder if it is empty ( because it was created with uninitialized submodule ) submodule_dir = PROJECT_DIRECTORY+'/meerkat_adminlte' try: os.rmdir(submodule_dir) except OSError as ex: if ex.errno == errno.ENOTEMPTY: print("directory not empty") exit(1) # replay cookiecutter(template,replay=True, overwrite_if_exists=True, output_dir="../") commit = False else : commit = True return commit
def new(self) -> None: """Create a new executor using cookiecutter template """ with ImportExtensions(required=True): from cookiecutter.main import cookiecutter import click # part of cookiecutter cookiecutter_template = self.args.template if self.args.type == 'app': cookiecutter_template = 'https://github.com/jina-ai/cookiecutter-jina.git' elif self.args.type == 'pod': cookiecutter_template = 'https://github.com/jina-ai/cookiecutter-jina-hub.git' try: cookiecutter(cookiecutter_template, overwrite_if_exists=self.args.overwrite, output_dir=self.args.output_dir) except click.exceptions.Abort: self.logger.info('nothing is created, bye!')
def do_cli(location, runtime, output_dir, name, namespace, no_input, type): click.secho(''' _____ ______ ______ ______ __ ____ / ___/ / ____// ____// ____// / / _/ \__ \ / / / /_ / / / / / / ___/ // /___ / __/ / /___ / /___ _/ / /____/ \____//_/ \____//_____//___/ ''') click.secho("[+] Initializing project...", fg="green") params = { "template": location if location else Init._runtime_path(runtime), "output_dir": output_dir, "no_input": no_input, } Operation("Template: %s" % params["template"]).process() Operation("Output-Dir: %s" % params["output_dir"]).process() if name is not None: params["no_input"] = True params['extra_context'] = { 'project_name': name, 'runtime': runtime, 'namespace': namespace, 'type': type } Operation("Project-Name: %s" % params['extra_context']["project_name"]).process() Operation("Type: %s" % params['extra_context']["type"]).process() Operation("Runtime: %s" % params['extra_context']["runtime"]).process() try: cookiecutter(**params) except exceptions.CookiecutterException as e: # click.secho(str(e), fg="red") # raise click.Abort() raise InitException(e) if runtime in infor.SERVICE_RUNTIME: click.secho("[*] Project initing,please wait.....", fg="green") zipfile_path = os.path.join(os.path.abspath(output_dir), name, 'node_modules.zip') zipobj = zipfile.ZipFile(zipfile_path, mode="r") zipobj.extractall(os.path.join(os.path.abspath(output_dir), name)) zipobj.close() os.remove(zipfile_path) click.secho("[*] Project initialization is complete", fg="green") Operation("You could 'cd %s', and start this project." % (params['extra_context']["project_name"])).information()
def test_use_continuous_deployment(project_default, use_continuous_deployment, expected, tmp_path): project = project_default project["use_continuous_deployment"] = use_continuous_deployment cookiecutter(str(COOKIECUTTER_ROOT), no_input=True, extra_context=project, output_dir=tmp_path) file_path = tmp_path.joinpath(project["project_slug"]).joinpath( ".github/workflows/pypi_publish.yaml") if expected: assert file_path.exists() else: assert not file_path.exists()
def test_main_does_not_invoke_load_but_dump(monkeypatch, mocker): """Test `cookiecutter` calling correct functions on non-replay launch.""" monkeypatch.chdir(os.path.abspath(os.path.dirname(__file__))) mock_prompt = mocker.patch('cookiecutter.main.prompt_for_config') mock_gen_context = mocker.patch('cookiecutter.main.generate_context') mock_gen_files = mocker.patch('cookiecutter.main.generate_files') mock_replay_dump = mocker.patch('cookiecutter.main.dump') mock_replay_load = mocker.patch('cookiecutter.main.load') main.cookiecutter('../fixtures/fake-repo-tmpl/', replay=False) assert mock_prompt.called assert mock_gen_context.called assert mock_replay_dump.called assert not mock_replay_load.called assert mock_gen_files.called
def test_python_min_version(tmp_path): with pytest.raises(FailedHookException): project = { "project_name": "Test Project", "creator": "Some Person", "creator_email": "*****@*****.**", "license": "No License", "min_python_version": 3.9, "github_action_python_test_versions": "3.8, 3.9", } cookiecutter(str(COOKIECUTTER_ROOT), no_input=True, extra_context=project, output_dir=tmp_path) assert sys.exit == 4
def init_evaluation(challenge_name, kind, dev): template_dir = Path(__file__).parent / "templates" / "evaluation" try: cookiecutter( template=str(template_dir.absolute()), no_input=True, extra_context={ "challenge_name": challenge_name, "evalutils_name": __name__.split(".")[0], "evalutils_version": __version__, "challenge_kind": kind, "dev_build": 1 if dev else 0, }, ) click.echo(f"Created project {challenge_name}") except FailedHookException: exit(1)
def create_research(self, new_app=False): ''' :param new_app (bool): Flag for auto generating an app that goes with the research target. :return: Adds new directories in the current project labeled with the proper names. ''' e_c = { "research_type": self.research_type, "research_name": self.research } cookiecutter(self.research_cookie, no_input=True, extra_context=e_c, output_dir=self.research_path) if new_app is True: self.create_app()
def test_use_dependabot(project_default, use_dependabot, expected, tmp_path): project = project_default project["use_dependabot"] = use_dependabot cookiecutter(str(COOKIECUTTER_ROOT), no_input=True, extra_context=project, output_dir=tmp_path) file_path = tmp_path.joinpath( project["project_slug"]).joinpath(".github") / "dependabot.yaml" if expected: assert file_path.exists() assert no_curlies(file_path) else: assert not file_path.exists()
def init(target: str, page_size: str, landscape: bool, template: str) -> None: """Initialize a new sketch. TARGET is the name or path of the new sketch directory.""" dir_path = pathlib.Path(target) with vsketch.working_directory(dir_path.parent): cookiecutter( template, no_input=True, extra_context={ "sketch_name": dir_path.name, "page_size": page_size, "landscape": str(landscape), }, )
def test_cookiecutter_no_input_return_project_dir(path): """Verify `cookiecutter` create project dir on input with or without slash.""" project_dir = main.cookiecutter(path, no_input=True) assert os.path.isdir('tests/fake-repo-pre/{{cookiecutter.repo_name}}') assert not os.path.isdir('tests/fake-repo-pre/fake-project') assert os.path.isdir(project_dir) assert os.path.isfile('fake-project/README.rst') assert not os.path.exists('fake-project/json/')
def config_files(tmp_path): """ Create config files in a temp directory. """ # Lookup the path to our embedded cookiecutter template. basedir = pathlib.Path(__file__).resolve().parent.parent template = str(basedir / 'tests' / 'cookiecutter' / 'config') cookiecutter( template, extra_context={'config_parent': str(tmp_path)}, output_dir=str(tmp_path), no_input=True, overwrite_if_exists=True, ) # Inject the path to the temp config. virt_up.instance.virtup_config_home = str(tmp_path / 'virt-up') return tmp_path
def test_custom_replay_file(monkeypatch, mocker, user_config_file): """Check that reply.load is called with the custom replay_file.""" monkeypatch.chdir('tests/fake-repo-tmpl') mock_replay_load = mocker.patch('cookiecutter.main.load') mocker.patch('cookiecutter.main.generate_files') cookiecutter( '.', replay='./custom-replay-file', config_file=user_config_file, ) mock_replay_load.assert_called_once_with( '.', 'custom-replay-file', )
def kedro_project(tmp_path): # TODO : this is also an integration test since this depends from the kedro version config = { "output_dir": tmp_path, "kedro_version": kedro_version, "project_name": "This is a fake project", "repo_name": "fake-project", "python_package": "fake_project", "include_example": True, } cookiecutter( str(TEMPLATE_PATH), output_dir=config["output_dir"], no_input=True, extra_context=config, )
def main(template, extra_context, no_input, checkout, verbose, replay, overwrite_if_exists, output_dir, config_file, default_config, debug_file): """Create a project from a Cookiecutter project template (TEMPLATE). Cookiecutter is free and open source software, developed and managed by volunteers. If you would like to help out or fund the project, please get in touch at https://github.com/audreyr/cookiecutter. """ # If you _need_ to support a local template in a directory # called 'help', use a qualified path to the directory. if template == u'help': click.echo(click.get_current_context().get_help()) sys.exit(0) configure_logger( stream_level='DEBUG' if verbose else 'INFO', debug_file=debug_file, ) try: cookiecutter( template, checkout, no_input, extra_context=extra_context, replay=replay, overwrite_if_exists=overwrite_if_exists, output_dir=output_dir, config_file=config_file, default_config=default_config, ) except (OutputDirExistsException, InvalidModeException, FailedHookException, UnknownExtension, RepositoryNotFound, RepositoryCloneFailed) as e: click.echo(e) sys.exit(1) except UndefinedVariableInTemplate as undefined_err: click.echo('{}'.format(undefined_err.message)) click.echo('Error message: {}'.format(undefined_err.error.message)) context_str = json.dumps(undefined_err.context, indent=4, sort_keys=True) click.echo('Context: {}'.format(context_str)) sys.exit(1)
def run(self, operator_name, template=DEFAULT_TEMPLATE_REPO, checkout=None, no_input=True, output_dir=None, extra_context=None, replay=False, overwrite_if_exists=False, config_file=None, default_config=False, password=None): output_dir = output_dir \ or os.path.join( find_experiment_root_dir(), OPERATOR_DIR_PREFIX) extra_context = {'operator_name': operator_name} # powering cookiecutter to generate experiment from templates try: cookiecutter(template, checkout, no_input=no_input, extra_context=extra_context, replay=replay, overwrite_if_exists=overwrite_if_exists, output_dir=output_dir, config_file=config_file, default_config=default_config, password=os.environ.get('COOKIECUTTER_REPO_PASSWORD')) except (OutputDirExistsException, InvalidModeException, FailedHookException, UnknownExtension, InvalidZipRepository, RepositoryNotFound, RepositoryCloneFailed) as e: click.echo(e) sys.exit(1) except UndefinedVariableInTemplate as undefined_err: click.echo('{}'.format(undefined_err.message)) click.echo('Error message: {}'.format(undefined_err.error.message)) context_str = json.dumps(undefined_err.context, indent=4, sort_keys=True) click.echo('Context: {}'.format(context_str)) sys.exit(1)
def render_single_layer(resource, regions, append_id=False): # logger.info("...") try: region = list(regions.keys())[0] except Exception: region = "eu-west-1" path_parts = [] text = resource.get("text") if text is not None and len(text): path_parts.append(text) if append_id: path_parts.append(resource["ref_id"]) else: path_parts.append(resource["type"]) if append_id: path_parts.append(resource["ref_id"]) dir_name = "_".join(path_parts) dir_name = re.sub(' ', '_', dir_name.strip()) dir_name = re.sub('[^a-zA-Z0-9-_]', '', dir_name) dir_name = re.sub('_+', '_', dir_name) full_dir_name = "single_layer/%s/%s" % (region, dir_name) single_layer = { "dir_name": full_dir_name.lower(), "layer_name": dir_name.lower(), "region": region, "module_source": MODULES[resource["type"]]["source"], "module_variables": MODULES[resource["type"]]["variables"], } extra_context = resource.update(single_layer) or resource cookiecutter(os.path.join(COOKIECUTTER_TEMPLATES_DIR, COOKIECUTTER_TEMPLATES_PREFIX + "-single-layer"), config_file=os.path.join(COOKIECUTTER_TEMPLATES_DIR, "config_aws_lambda.yaml"), no_input=True, extra_context=extra_context)
def test_operator_split(monkeypatch, tmpdir): """Verify the operator call works successfully.""" monkeypatch.chdir(os.path.abspath(os.path.dirname(__file__))) output = cookiecutter('.', no_input=True, output_dir=str(tmpdir)) assert output['a_list'] == [['stuff', 'thing'], ['things', 'stuffs']] assert output['a_str'] == ['things', 'stuffs'] assert output['join_a_str'] == 'things.stuffs'
def init(framework, user): '''initialize a new cookiecutter template''' # Check that cookiecutter template exists for requested framework git_url = 'https://github.com/' framework = framework.lower().replace(' ', '-') mo_url = "{0}{1}/mo-{2}".format(git_url, user, framework) cookie_find(mo_url) # Run cookiecutter template if click.confirm('Ready to start cookiecutter {0}.git ' 'in the current directory.\n' 'Do you want to continue?'.format(mo_url)): try: cookiecutter('{0}.git'.format(mo_url)) except: sys.exit("Problem encounted while cloning '{0}.git'" .format(mo_url))
def main(template, no_input, checkout, verbose, rc_file): """Create a project from a Cookiecutter project template (TEMPLATE).""" if verbose: logging.basicConfig(format='%(levelname)s %(filename)s: %(message)s', level=logging.DEBUG) else: # Log info and above to console logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.INFO) cookiecutter(template, checkout, no_input, rc_file=rc_file, extra_globals=dict( checkout=checkout, verbose=verbose, ))
def main(): args = parse_arguments() template_path = str(parent / 'template') if not args.get('name'): cookiecutter(template_path) else: ctx = { 'project_name': args.get('name'), 'use_postgres': 'n' if args.get('without_postgres') else 'y', 'use_redis': 'y' if args.get('without_postgres') else 'n', } cookiecutter(template_path, no_input=True, extra_context=ctx) print('\n\nSuccessfully generated!\n') print(f'cd {args["name"] or "app"}/') print('make run\n\n')
def test_operator_lists(monkeypatch, tmpdir): """Verify the operator call works successfully.""" monkeypatch.chdir(os.path.abspath(os.path.dirname(__file__))) output = cookiecutter('.', no_input=True, output_dir=str(tmpdir)) assert 'donkey' in output['appended_list'] assert 'donkey' in output['appended_lists'] assert 'chickens' in output['appended_lists']
def verbose_cookiecutter(**kwargs): from cookiecutter.log import configure_logger configure_logger(stream_level='DEBUG') print("Run cookiecutter with:") pprint(kwargs) print() result = cookiecutter(**kwargs) return result
def test_cookiecutter_template_cleanup(mocker): """ `Call cookiecutter()` with `no_input=True` and templates in the cookiecutter.json file """ mocker.patch('tempfile.mkdtemp', return_value='fake-tmp', autospec=True) mocker.patch('cookiecutter.utils.prompt_and_delete', return_value=True, autospec=True) main.cookiecutter('tests/files/fake-repo-tmpl.zip', no_input=True) assert os.path.isdir('fake-project-templated') # The tmp directory will still exist, but the # extracted template directory *in* the temp directory will not. assert os.path.exists('fake-tmp') assert not os.path.exists('fake-tmp/fake-repo-tmpl')
def test_cookiecutter_no_input_return_project_dir(monkeypatch): """Verify `cookiecutter` create project dir on input with or without slash.""" monkeypatch.chdir(os.path.abspath(os.path.dirname(__file__))) context = main.cookiecutter('fake-repo-pre', no_input=True) assert type(context) == dict assert os.path.isdir('fake-repo-pre/{{cookiecutter.repo_name}}') assert not os.path.isdir('fake-repo-pre/fake-project')
def generate_cookiecutter(cookiecutter_url, metadata_file=None): notebook_metadata = {} if metadata_file and os.path.isfile(metadata_file): with io.open(metadata_file) as fd: notebook_metadata = yaml.load(fd) notebook_fname = metadata_file.replace('.yaml', '') project_slug = notebook_metadata['project_slug'] print('metadata loaded from notebook: ' + notebook_fname) print('generating to output dir: ' + project_slug) print('metadata to be passed to cookiecutter as extra_context:') pprint(notebook_metadata) # # Use notebook metadata to preload the cookiecutter config options: # http://cookiecutter.readthedocs.io/en/latest/advanced/suppressing_prompts.html # cookiecutter(cookiecutter_url, extra_context=notebook_metadata) return project_slug
def prepare(): """ Prepare all the stuff for start a new Python project. This function use cookiecutter(https://github.com/audreyr/cookiecutter) The template dir is ./project_template """ return cookiecutter(TEMPLATE_PATH)
def test_operator_aws_azs(monkeypatch, tmpdir): """Verify the operator call works successfully.""" monkeypatch.chdir(os.path.abspath(os.path.dirname(__file__))) context = cookiecutter('.', context_file='region.yaml', no_input=True, output_dir=str(tmpdir)) assert len(context) > 1 context = cookiecutter('.', context_file='regions.yaml', no_input=True, output_dir=str(tmpdir)) assert len(context) > 1 assert len(context['azs']['us-east-1']) > 1
def cut(self): logging.debug("DataSource.cut()") cookiecutter( self.template, no_input=True, extra_context = { 'package_name' : self.package_name_capitalized, 'datasource_name' : self.datasource_name, 'author' : self.author, 'date' : self.timestamp, 'timestamp' : self.timestamp, 'copyright' : self.copyright, 'license' : self.copyright, 'implementation_details' : self.implementation_details, 'interface_details' : self.interface_details, 'datasource_include_guard' : self.datasource_include_guard } )
def start(self): dir_path = os.path.dirname(os.path.realpath(__file__)) dir_path = os.path.abspath(os.path.join(dir_path, 'templates')) filename = '{}'.format(os.path.join(dir_path, self.template)) # content from cli or prompt (if enabled) extra_context = { 'username': self.username, 'fullname': self.fullname, 'project_name': self.name, 'project_short_description': self.desc } # Create project from the cookiecutter-pypackage/ template cookiecutter(filename, no_input=self.prompt, extra_context=extra_context)