def test_local_repo_typo(template, user_config_data, cloned_cookiecutter_path):
    """An unknown local repo should raise a `RepositoryNotFound` exception."""
    with pytest.raises(exceptions.RepositoryNotFound) as err:
        repository.determine_repo_dir(
            template,
            abbreviations={},
            clone_to_dir=user_config_data['cookiecutters_dir'],
            checkout=None,
            no_input=True,
            directory='wrong-dir',
        )

    wrong_full_cookiecutter_path = os.path.join(
        os.path.dirname(cloned_cookiecutter_path),
        'wrong-dir'
    )
    assert str(err.value) == (
        'A valid repository for "{}" could not be found in the following '
        'locations:\n{}'.format(
            template,
            '\n'.join([
                os.path.join(template, 'wrong-dir'),
                wrong_full_cookiecutter_path
            ]),
        )
    )
Example #2
0
def project():
    """Manage projects"""
    repository.determine_repo_dir(
        template='https://github.com/audreyr/cookiecutter-pypackage',
        abbreviations={},
        clone_to_dir='test',
        checkout="master",
        no_input=True)
Example #3
0
File: cli.py Project: 4383/rogue
def main(args=None):
    """Console script for installer"""
    click.echo("Replace this message by putting your code into "
               "installer.cli.main")
    click.echo("See click documentation at http://click.pocoo.org/")
    repository.determine_repo_dir(
        template='https://github.com/audreyr/cookiecutter-pypackage',
        abbreviations={},
        clone_to_dir='test',
        checkout="master",
        no_input=True)
Example #4
0
def test_local_repo_with_no_context_raises():
    """A local repository without a cookiecutter.json should raise a
    `RepositoryNotFound` exception.
    """
    with pytest.raises(exceptions.RepositoryNotFound) as err:
        repository.determine_repo_dir('tests/fake-repo-bad',
                                      abbreviations={},
                                      clone_to_dir=None,
                                      checkout=None,
                                      no_input=True)

    assert str(err.value) == (
        'The repository tests/fake-repo-bad could not be located or does not '
        'contain a "cookiecutter.json" file.')
Example #5
0
def test_local_repo_typo():
    """An unknown local repository should raise a `RepositoryNotFound`
    exception.
    """
    with pytest.raises(exceptions.RepositoryNotFound) as err:
        repository.determine_repo_dir('tests/unknown-repo',
                                      abbreviations={},
                                      clone_to_dir=None,
                                      checkout=None,
                                      no_input=True)

    assert str(err.value) == (
        'The repository tests/unknown-repo could not be located or does not '
        'contain a "cookiecutter.json" file.')
Example #6
0
def _get_cookiecutter_dir(template_path: str, checkout: str, directory: str,
                          tmpdir: str) -> Path:
    """Gives a path to the cookiecutter directory. If template_path is a repo then
    clones it to ``tmpdir``; if template_path is a file path then directly uses that
    path without copying anything.
    """
    # pylint: disable=import-outside-toplevel
    from cookiecutter.exceptions import RepositoryCloneFailed, RepositoryNotFound
    from cookiecutter.repository import determine_repo_dir  # for performance reasons

    try:
        cookiecutter_dir, _ = determine_repo_dir(
            template=template_path,
            abbreviations=dict(),
            clone_to_dir=Path(tmpdir).resolve(),
            checkout=checkout,
            no_input=True,
            directory=directory,
        )
    except (RepositoryNotFound, RepositoryCloneFailed) as exc:
        error_message = f"Kedro project template not found at {template_path}."

        if checkout:
            error_message += (
                f" Specified tag {checkout}. The following tags are available: "
                + ", ".join(_get_available_tags(template_path)))
        raise KedroCliError(error_message) from exc

    return Path(cookiecutter_dir)
def test_repository_url_should_clone(mocker, template_url, user_config_data):
    """`clone()` should be called with correct args when
    `determine_repo_dir()` is passed a repository template url.
    """

    mock_clone = mocker.patch('cookiecutter.repository.clone',
                              return_value='tests/fake-repo-tmpl',
                              autospec=True)

    project_dir, cleanup = repository.determine_repo_dir(
        template_url,
        abbreviations={},
        clone_to_dir=user_config_data['cookiecutters_dir'],
        checkout=None,
        no_input=True)

    mock_clone.assert_called_once_with(
        repo_url=template_url,
        checkout=None,
        clone_to_dir=user_config_data['cookiecutters_dir'],
        no_input=True)

    assert os.path.isdir(project_dir)
    assert not cleanup
    assert 'tests/fake-repo-tmpl' == project_dir
def test_zipfile_unzip(mocker, template, is_url, user_config_data):
    """`unzip()` should be called with correct args when
    `determine_repo_dir()` is passed a zipfile, or a URL
    to a zipfile.
    """

    mock_clone = mocker.patch(
        'cookiecutter.repository.unzip',
        return_value='tests/fake-repo-tmpl',
        autospec=True
    )

    project_dir, cleanup = repository.determine_repo_dir(
        template,
        abbreviations={},
        clone_to_dir=user_config_data['cookiecutters_dir'],
        checkout=None,
        no_input=True,
        password=None,
    )

    mock_clone.assert_called_once_with(
        zip_uri=template,
        is_url=is_url,
        clone_to_dir=user_config_data['cookiecutters_dir'],
        no_input=True,
        password=None,
    )

    assert os.path.isdir(project_dir)
    assert cleanup
    assert 'tests/fake-repo-tmpl' == project_dir
def test_zipfile_unzip(mocker, template, is_url, user_config_data):
    """`unzip()` should be called with correct args when
    `determine_repo_dir()` is passed a zipfile, or a URL
    to a zipfile.
    """

    mock_clone = mocker.patch('cookiecutter.repository.unzip',
                              return_value='tests/fake-repo-tmpl',
                              autospec=True)

    project_dir, cleanup = repository.determine_repo_dir(
        template,
        abbreviations={},
        clone_to_dir=user_config_data['cookiecutters_dir'],
        checkout=None,
        no_input=True,
        password=None,
    )

    mock_clone.assert_called_once_with(
        zip_uri=template,
        is_url=is_url,
        clone_to_dir=user_config_data['cookiecutters_dir'],
        no_input=True,
        password=None,
    )

    assert os.path.isdir(project_dir)
    assert cleanup
    assert 'tests/fake-repo-tmpl' == project_dir
Example #10
0
def get_cookiecutter_config(template, default_config=None, version=None):
    """Obtains the configuration used for cookiecutter templating

    Args:
        template: Path to the template
        default_config (dict, optional): The default configuration
        version (str, optional): The git SHA or branch to use when
            checking out template. Defaults to latest version

    Returns:
        tuple: The cookiecutter repo directory and the config dict
    """
    default_config = default_config or {}
    config_dict = cc_config.get_user_config()
    repo_dir, _ = cc_repository.determine_repo_dir(
        template=template,
        abbreviations=config_dict['abbreviations'],
        clone_to_dir=config_dict['cookiecutters_dir'],
        checkout=version,
        no_input=True)
    context_file = os.path.join(repo_dir, 'cookiecutter.json')
    context = cc_generate.generate_context(
        context_file=context_file,
        default_context={
            **config_dict['default_context'],
            **default_config
        })
    return repo_dir, cc_prompt.prompt_for_config(context)
def test_repository_url_should_clone(
        mocker, template_url, user_config_data):
    """`clone()` should be called with correct args when
    `determine_repo_dir()` is passed a repository template url.
    """

    mock_clone = mocker.patch(
        'cookiecutter.repository.clone',
        return_value='tests/fake-repo-tmpl',
        autospec=True
    )

    project_dir, cleanup = repository.determine_repo_dir(
        template_url,
        abbreviations={},
        clone_to_dir=user_config_data['cookiecutters_dir'],
        checkout=None,
        no_input=True
    )

    mock_clone.assert_called_once_with(
        repo_url=template_url,
        checkout=None,
        clone_to_dir=user_config_data['cookiecutters_dir'],
        no_input=True
    )

    assert os.path.isdir(project_dir)
    assert not cleanup
    assert 'tests/fake-repo-tmpl' == project_dir
def test_determine_repository_should_use_local_repo():
    project_dir = determine_repo_dir('tests/fake-repo',
                                     abbreviations={},
                                     clone_to_dir=None,
                                     checkout=None,
                                     no_input=True)

    assert 'tests/fake-repo' == project_dir
def test_local_repo_typo():
    """An unknown local repository should raise a `RepositoryNotFound`
    exception.
    """
    with pytest.raises(exceptions.RepositoryNotFound) as err:
        repository.determine_repo_dir(
            'tests/unknown-repo',
            abbreviations={},
            clone_to_dir=None,
            checkout=None,
            no_input=True
        )

    assert str(err.value) == (
        'The repository tests/unknown-repo could not be located or does not '
        'contain a "cookiecutter.json" file.'
    )
def test_local_repo_with_no_context_raises():
    """A local repository without a cookiecutter.json should raise a
    `RepositoryNotFound` exception.
    """
    with pytest.raises(exceptions.RepositoryNotFound) as err:
        repository.determine_repo_dir(
            'tests/fake-repo-bad',
            abbreviations={},
            clone_to_dir=None,
            checkout=None,
            no_input=True
        )

    assert str(err.value) == (
        'The repository tests/fake-repo-bad could not be located or does not '
        'contain a "cookiecutter.json" file.'
    )
Example #15
0
def _custom_cookiecutter(template, output_dir, project_slug, package_slug):

    config_dict = get_user_config(
        config_file=None,
        default_config=False,
    )

    template_name = os.path.splitext(os.path.basename(template))[0]

    repo_dir = os.path.join(config_dict['cookiecutters_dir'], template_name)
    if os.path.isdir(repo_dir):
        purge_dir(repo_dir)

    repo_dir, _ = determine_repo_dir(
        template=template,
        abbreviations=config_dict['abbreviations'],
        clone_to_dir=config_dict['cookiecutters_dir'],
        checkout=None,
        no_input=False,
        password=None,
        directory=None,
    )

    context_file = os.path.join(repo_dir, 'cookiecutter.json')
    context = generate_context(
        context_file=context_file,
        default_context=config_dict['default_context'],
        extra_context=None,
    )

    answers = dialogus(
        ADD_REPORT_QUESTIONS,
        'Add report to existing project',
        intro=REPORT_ADD_WIZARD_INTRO,
        summary=REPORT_SUMMARY,
        finish_text='Add',
        previous_text='Back',
    )

    if not answers:
        raise ClickException('Aborted by user input')

    context['cookiecutter']['_template'] = template
    context['cookiecutter']['project_slug'] = project_slug
    context['cookiecutter']['package_slug'] = package_slug
    context['cookiecutter']['initial_report_name'] = answers[
        'initial_report_name']
    context['cookiecutter']['initial_report_slug'] = answers[
        'initial_report_slug']
    context['cookiecutter']['initial_report_description'] = answers[
        'initial_report_description']
    context['cookiecutter']['initial_report_renderer'] = answers[
        'initial_report_renderer']

    result = _generate_files(context, output_dir, repo_dir)

    return result, context['cookiecutter']['initial_report_slug']
def test_finds_local_repo(tmpdir):
    """A valid local repository should be returned."""
    project_dir = repository.determine_repo_dir('tests/fake-repo',
                                                abbreviations={},
                                                clone_to_dir=str(tmpdir),
                                                checkout=None,
                                                no_input=True)

    assert 'tests/fake-repo' == project_dir
Example #17
0
def _fetch_config_from_prompts(template_path: str, checkout: str,
                               directory: str) -> Dict[str, str]:
    """Obtains configuration for a new kedro project interactively from user prompts.

    Args:
       template_path: The path to the cookiecutter template to create the project.
           It could either be a local directory or a remote VCS repository
           supported by cookiecutter. For more details, please see:
           https://cookiecutter.readthedocs.io/en/latest/usage.html#generate-your-project
       checkout: The tag, branch or commit in the starter repository to checkout.
           Maps directly to cookiecutter's ``checkout`` argument. Relevant only when
           using a starter.
       directory: The directory of a specific starter inside a repository containing
           multiple starters. Maps directly to cookiecutter's ``directory`` argument.
           Relevant only when using a starter.
           https://cookiecutter.readthedocs.io/en/1.7.2/advanced/directories.html

    Returns:
        Configuration for starting a new project. This is passed as ``extra_context``
        to cookiecutter and will overwrite the cookiecutter.json defaults.

    Raises:
        KedroCliError: if Kedro project template could not be found.
    """
    # pylint: disable=import-outside-toplevel, too-many-locals
    from cookiecutter.exceptions import RepositoryCloneFailed, RepositoryNotFound
    from cookiecutter.repository import determine_repo_dir  # for performance reasons

    with tempfile.TemporaryDirectory() as tmpdir:
        temp_dir_path = Path(tmpdir).resolve()
        try:
            cookiecutter_repo, _ = determine_repo_dir(
                template=template_path,
                abbreviations=dict(),
                clone_to_dir=temp_dir_path,
                checkout=checkout,
                no_input=True,
                directory=directory,
            )
        except (RepositoryNotFound, RepositoryCloneFailed) as exc:
            error_message = (
                f"Kedro project template not found at {template_path}"
                f" with tag {checkout}.")
            tags = _get_available_tags(template_path)
            if tags:
                error_message += f" The following tags are available: {', '.join(tags)}"
            raise KedroCliError(error_message) from exc

        cookiecutter_dir = temp_dir_path / cookiecutter_repo
        prompts_yml = cookiecutter_dir / "prompts.yml"

        # If there is no prompts.yml, no need to ask user for input.
        if not prompts_yml.is_file():
            return dict()

        prompts = _parse_prompts_from_file(prompts_yml)
        return _run_prompts_for_user_input(prompts, cookiecutter_dir)
def test_local_repo_typo(tmpdir):
    """An unknown local repository should raise a `RepositoryNotFound`
    exception.
    """
    template_path = os.path.join('tests', 'unknown-repo')
    with pytest.raises(exceptions.RepositoryNotFound) as err:
        repository.determine_repo_dir(template_path,
                                      abbreviations={},
                                      clone_to_dir=str(tmpdir),
                                      checkout=None,
                                      no_input=True)

    assert str(err.value) == (
        'A valid repository for "{}" could not be found in the following '
        'locations:\n{}'.format(
            template_path,
            '\n'.join([template_path,
                       str(tmpdir / 'tests/unknown-repo')]),
        ))
def test_local_repo_with_no_context_raises(tmpdir):
    """A local repository without a cookiecutter.json should raise a
    `RepositoryNotFound` exception.
    """
    template_path = os.path.join('tests', 'fake-repo-bad')
    with pytest.raises(exceptions.RepositoryNotFound) as err:
        repository.determine_repo_dir(template_path,
                                      abbreviations={},
                                      clone_to_dir=str(tmpdir),
                                      checkout=None,
                                      no_input=True)

    assert str(err.value) == (
        'A valid repository for "{}" could not be found in the following '
        'locations:\n{}'.format(
            template_path,
            '\n'.join([template_path,
                       str(tmpdir / 'tests/fake-repo-bad')]),
        ))
def test_determine_repository_should_use_local_repo():
    project_dir = determine_repo_dir(
        'tests/fake-repo',
        abbreviations={},
        clone_to_dir=None,
        checkout=None,
        no_input=True
    )

    assert 'tests/fake-repo' == project_dir
Example #21
0
def test_repository_url_with_no_context_file(mocker, template_url,
                                             user_config_data):
    mocker.patch('cookiecutter.repository.clone',
                 return_value='tests/fake-repo-bad',
                 autospec=True)

    with pytest.raises(exceptions.RepositoryNotFound) as err:
        repository.determine_repo_dir(template_url,
                                      abbreviations={},
                                      clone_to_dir=None,
                                      checkout=None,
                                      no_input=True)

    assert str(err.value) == (
        'A valid repository for "{}" could not be found in the following '
        'locations:\n{}'.format(
            template_url,
            'tests/fake-repo-bad',
        ))
Example #22
0
def main(template: str):
    config_dict = get_user_config()
    repo_dir, cleanup = determine_repo_dir(
        template=template,
        abbreviations=config_dict['abbreviations'],
        clone_to_dir=config_dict['cookiecutters_dir'],
        checkout=None,
        no_input=False,
    )
    print("repo_dir: ", repo_dir)
    print("cleanup: ", cleanup)
def test_finds_local_repo():
    """A valid local repository should be returned."""
    project_dir = repository.determine_repo_dir(
        'tests/fake-repo',
        abbreviations={},
        clone_to_dir=None,
        checkout=None,
        no_input=True
    )

    assert 'tests/fake-repo' == project_dir
def test_should_find_existing_cookiecutter(
        template, user_config_data, cloned_cookiecutter_path):
    project_dir = repository.determine_repo_dir(
        template,
        abbreviations={},
        clone_to_dir=user_config_data['cookiecutters_dir'],
        checkout=None,
        no_input=True,
    )

    assert cloned_cookiecutter_path == project_dir
Example #25
0
def test_repository_url_with_no_context_file(mocker, template_url):
    mocker.patch(
        'cookiecutter.repository.clone',
        return_value='tests/fake-repo-bad',
        autospec=True
    )

    with pytest.raises(exceptions.RepositoryNotFound) as err:
        repository.determine_repo_dir(
            template_url,
            abbreviations={},
            clone_to_dir=None,
            checkout=None,
            no_input=True
        )

    assert str(err.value) == (
        'The repository tests/fake-repo-bad could not be located or does not '
        'contain a "cookiecutter.json" file.'
    )
Example #26
0
def test_finds_local_repo(tmpdir):
    """A valid local repository should be returned."""
    project_dir, cleanup = repository.determine_repo_dir(
        "tests/fake-repo",
        abbreviations={},
        clone_to_dir=str(tmpdir),
        checkout=None,
        no_input=True,
    )

    assert "tests/fake-repo" == project_dir
    assert not cleanup
Example #27
0
def _prompt_user_for_config(  # pylint: disable=too-many-locals
        template_path: Path,
        checkout: str = None,
        directory: str = None) -> Dict[str, str]:
    """Prompt user in the CLI to provide configuration values for cookiecutter variables
    in a starter, such as project_name, package_name, etc.
    """
    # pylint: disable=import-outside-toplevel
    from cookiecutter.prompt import read_user_variable, render_variable
    from cookiecutter.repository import determine_repo_dir  # for performance reasons

    with tempfile.TemporaryDirectory() as tmpdir:
        temp_dir_path = Path(tmpdir).resolve()
        cookiecutter_repo, _ = determine_repo_dir(
            template=str(template_path),
            abbreviations=dict(),
            clone_to_dir=temp_dir_path,
            checkout=checkout,
            no_input=True,
            directory=directory,
        )
        cookiecutter_dir = temp_dir_path / cookiecutter_repo
        prompts_yml = cookiecutter_dir / "prompts.yml"

        # If there is no prompts.yml, no need to ask user for input.
        if not prompts_yml.is_file():
            return {}

        with open(prompts_yml) as config_file:
            prompts_dict = yaml.safe_load(config_file)

        cookiecutter_env = _prepare_cookiecutter_env(cookiecutter_dir)

        config: Dict[str, str] = dict()
        config["output_dir"] = str(Path.cwd().resolve())

        for variable_name, prompt_dict in prompts_dict.items():
            prompt = _Prompt(**prompt_dict)

            # render the variable on the command line
            cookiecutter_variable = render_variable(
                env=cookiecutter_env.env,
                raw=cookiecutter_env.context[variable_name],
                cookiecutter_dict=config,
            )

            # read the user's input for the variable
            user_input = read_user_variable(str(prompt), cookiecutter_variable)
            if user_input:
                prompt.validate(user_input)
                config[variable_name] = user_input
        return config
def test_should_find_existing_cookiecutter(template, user_config_data,
                                           cloned_cookiecutter_path):
    """Find `cookiecutter.json` in sub folder created by `cloned_cookiecutter_path`."""
    project_dir, cleanup = repository.determine_repo_dir(
        template=template,
        abbreviations={},
        clone_to_dir=user_config_data['cookiecutters_dir'],
        checkout=None,
        no_input=True,
        directory='my-dir',
    )

    assert cloned_cookiecutter_path == project_dir
    assert not cleanup
def test_local_repo_typo(tmpdir):
    """An unknown local repository should raise a `RepositoryNotFound`
    exception.
    """
    template_path = os.path.join('tests', 'unknown-repo')
    with pytest.raises(exceptions.RepositoryNotFound) as err:
        repository.determine_repo_dir(
            template_path,
            abbreviations={},
            clone_to_dir=str(tmpdir),
            checkout=None,
            no_input=True
        )

    assert str(err.value) == (
        'A valid repository for "{}" could not be found in the following '
        'locations:\n{}'.format(
            template_path,
            '\n'.join([
                template_path,
                str(tmpdir / 'tests/unknown-repo')
            ]),
        )
    )
def test_local_repo_with_no_context_raises(tmpdir):
    """A local repository without a cookiecutter.json should raise a
    `RepositoryNotFound` exception.
    """
    template_path = os.path.join('tests', 'fake-repo-bad')
    with pytest.raises(exceptions.RepositoryNotFound) as err:
        repository.determine_repo_dir(
            template_path,
            abbreviations={},
            clone_to_dir=str(tmpdir),
            checkout=None,
            no_input=True
        )

    assert str(err.value) == (
        'A valid repository for "{}" could not be found in the following '
        'locations:\n{}'.format(
            template_path,
            '\n'.join([
                template_path,
                str(tmpdir / 'tests/fake-repo-bad')
            ]),
        )
    )
def test_repository_url_with_no_context_file(
        mocker, template_url, user_config_data):
    mocker.patch(
        'cookiecutter.repository.clone',
        return_value='tests/fake-repo-bad',
        autospec=True
    )

    with pytest.raises(exceptions.RepositoryNotFound) as err:
        repository.determine_repo_dir(
            template_url,
            abbreviations={},
            clone_to_dir=None,
            checkout=None,
            no_input=True
        )

    assert str(err.value) == (
        'A valid repository for "{}" could not be found in the following '
        'locations:\n{}'.format(
            template_url,
            'tests/fake-repo-bad',
        )
    )
Example #32
0
File: core.py Project: rom-py/rompy
    def __init__(self,
                 run_id='run_0001',
                 model=None,
                 template=None,
                 checkout=None,
                 settings=None,
                 output_dir=None):
        self.model = model
        self.run_id = run_id
        self.template = template
        self.checkout = checkout
        self.output_dir = output_dir
        self.staging_dir = self.output_dir + '/' + self.run_id

        # The following code is mostly lifted from https://github.com/cookiecutter/cookiecutter/blob/master/cookiecutter/main.py
        # Load cookie-cutter config - see https://cookiecutter.readthedocs.io/en/1.7.0/advanced/user_config.html
        config_dict = cc_config.get_user_config(
            config_file=None,
            default_config=False,
        )

        self._repo_dir, cleanup = cc_repository.determine_repo_dir(
            template=template,
            abbreviations=config_dict['abbreviations'],
            clone_to_dir=config_dict['cookiecutters_dir'],
            checkout=checkout,
            no_input=True)

        context_file = os.path.join(self._repo_dir, 'cookiecutter.json')
        logger.debug('context_file is {}'.format(context_file))

        context = cc_generate.generate_context(
            context_file=context_file,
            default_context=config_dict['default_context'],
            extra_context=settings)

        print('Default context: (from cookiecutter.json)')
        pprint.pprint(context['cookiecutter'])
        self.default_context = context['cookiecutter']

        if settings is None:
            self.settings = {}
        self.settings['_template'] = template
        self.settings['_checkout'] = checkout
        self.settings['model'] = model

        if not os.path.isdir(self.staging_dir):
            os.makedirs(self.staging_dir + '/downloads')
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 test_should_find_existing_cookiecutter(template, user_config_data,
                                           cloned_cookiecutter_path):
    """
    Should find folder created by `cloned_cookiecutter_path` and return it.

    This folder is considered like previously cloned project directory.
    """
    project_dir, cleanup = repository.determine_repo_dir(
        template=template,
        abbreviations={},
        clone_to_dir=user_config_data['cookiecutters_dir'],
        checkout=None,
        no_input=True,
    )

    assert cloned_cookiecutter_path == project_dir
    assert not cleanup
Example #35
0
def test_finds_local_repo(monkeypatch, tmpdir):
    """A valid local repository should be returned."""
    test_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..',
                            '..')
    monkeypatch.chdir(test_dir)

    project_dir, context_file, cleanup = repository.determine_repo_dir(
        'tests/fixtures/fake-repo',
        abbreviations={},
        clone_to_dir=str(tmpdir),
        checkout=None,
        no_input=True,
    )

    assert 'tests/fixtures/fake-repo' == project_dir
    assert context_file == 'cookiecutter.json'
    assert not cleanup
Example #36
0
def test_zipfile_unzip(monkeypatch, mocker, template, is_url,
                       user_config_data):
    """Verify zip files correctly handled for different source locations.

    `unzip()` should be called with correct args when `determine_repo_dir()`
    is passed a zipfile, or a URL to a zipfile.
    """
    test_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..',
                            '..')
    monkeypatch.chdir(test_dir)

    mock_clone = mocker.patch(
        'cookiecutter.repository.unzip',
        return_value='tests/fake-repo-tmpl',
        autospec=True,
    )

    project_dir, context_file, cleanup = repository.determine_repo_dir(
        template,
        abbreviations={},
        clone_to_dir=user_config_data['cookiecutters_dir'],
        checkout=None,
        no_input=True,
        password=None,
    )

    mock_clone.assert_called_once_with(
        zip_uri=template,
        is_url=is_url,
        clone_to_dir=user_config_data['cookiecutters_dir'],
        no_input=True,
        password=None,
    )

    assert os.path.isdir(project_dir)
    assert cleanup
    assert 'tests/fake-repo-tmpl' == project_dir
Example #37
0
def recurse_submodule(template):

    # 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)
        commit = False

    else:
        commit = True

    return commit
Example #38
0
def test_repository_url_should_clone(monkeypatch, mocker, template_url,
                                     user_config_data):
    """Verify repository url triggers clone function.

    `clone()` should be called with correct args when `determine_repo_dir()` is
    passed a repository template url.
    """
    test_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..',
                            '..')
    monkeypatch.chdir(test_dir)

    mock_clone = mocker.patch(
        'cookiecutter.repository.clone',
        return_value='tests/fake-repo-tmpl',
        autospec=True,
    )

    project_dir, context_file, cleanup = repository.determine_repo_dir(
        template_url,
        abbreviations={},
        clone_to_dir=user_config_data['cookiecutters_dir'],
        checkout=None,
        no_input=True,
    )

    mock_clone.assert_called_once_with(
        repo_url=template_url,
        checkout=None,
        clone_to_dir=user_config_data['cookiecutters_dir'],
        no_input=True,
    )

    assert os.path.isdir(project_dir)
    assert not cleanup
    assert context_file == 'cookiecutter.json'
    assert 'tests/fake-repo-tmpl' == project_dir
Example #39
0
def cookiecutter(
    template,
    checkout=None,
    no_input=False,
    extra_context=None,
    replay=False,
    overwrite_if_exists=False,
    output_dir='.',
    config_file=None,
    default_config=False,
    password=None,
    directory=None,
    skip_if_file_exists=False,
):
    """
    Run Cookiecutter just as if using it from the command line.

    :param template: A directory containing a project template directory,
        or a URL to a git repository.
    :param checkout: The branch, tag or commit ID to checkout after clone.
    :param no_input: Prompt the user at command line for manual configuration?
    :param extra_context: A dictionary of context that overrides default
        and user configuration.
    :param overwrite_if_exists: Overwrite the contents of output directory
        if it exists
    :param output_dir: Where to output the generated project dir into.
    :param config_file: User configuration file path.
    :param default_config: Use default values rather than a config file.
    :param password: The password to use when extracting the repository.
    :param directory: Relative path to a cookiecutter template in a repository.
    """
    if replay and ((no_input is not False) or (extra_context is not None)):
        err_msg = ("You can not use both replay and no_input or extra_context "
                   "at the same time.")
        raise InvalidModeException(err_msg)

    config_dict = get_user_config(
        config_file=config_file,
        default_config=default_config,
    )

    repo_dir, cleanup = determine_repo_dir(
        template=template,
        abbreviations=config_dict['abbreviations'],
        clone_to_dir=config_dict['cookiecutters_dir'],
        checkout=checkout,
        no_input=no_input,
        password=password,
        directory=directory,
    )

    template_name = os.path.basename(os.path.abspath(repo_dir))

    if replay:
        context = load(config_dict['replay_dir'], template_name)
    else:
        context_file = os.path.join(repo_dir, 'cookiecutter.json')
        logger.debug('context_file is %s', context_file)

        context = generate_context(
            context_file=context_file,
            default_context=config_dict['default_context'],
            extra_context=extra_context,
        )

        # prompt the user to manually configure at the command line.
        # except when 'no-input' flag is set
        context['cookiecutter'] = prompt_for_config(context, no_input)

        # include template dir or url in the context dict
        context['cookiecutter']['_template'] = template

        dump(config_dict['replay_dir'], template_name, context)

    # Create project from local context and project template.
    result = generate_files(
        repo_dir=repo_dir,
        context=context,
        overwrite_if_exists=overwrite_if_exists,
        skip_if_file_exists=skip_if_file_exists,
        output_dir=output_dir,
    )

    # Cleanup (if required)
    if cleanup:
        rmtree(repo_dir)

    return result