Create a temporary requirements.txt.

        This allows testing again a git branch instead of pulling from pypi.
333281
def _create_temp_requirements(self):
        
        self.use_temp_requirements_file = True
        # Replace tcex version with develop branch of tcex
        with open(self.requirements_file, 'r') as fh:
            current_requirements = fh.read().strip().split('\n')

        self.requirements_file = 'temp-{}'.format(self.requirements_file)
        with open(self.requirements_file, 'w') as fh:
            new_requirements = ''
            for line in current_requirements:
                if not line:
                    continue
                if line.startswith('tcex'):
                    line = 'git+https://github.com/ThreatConnect-Inc/tcex.git@{}#egg=tcex'
                    line = line.format(self.args.branch)
                # print('line', line)
                new_requirements += '{}\n'.format(line)
            fh.write(new_requirements)
1295146
def get_or_create_environment(self, repo: str, branch: str, git_repo: Repo, repo_path: Path) -> str:
        
        return sys.executable
248530
def expand(conf, output_requirements_filename, input_requirements_filename):
    
    exit_if_file_not_exists(input_requirements_filename, conf)
    cireqs.expand_requirements(
        requirements_filename=input_requirements_filename,
        expanded_requirements_filename=output_requirements_filename,
        **conf._asdict()
    )
    click.echo(click.style('✓', fg='green') + " {} has been expanded into {}".format(
        input_requirements_filename, output_requirements_filename
    ))
1087815
def git_clone(target_dir, repo_location, branch_or_tag=None, verbose=True):
    
    target_dir = pipes.quote(target_dir)
    command = ['git', 'clone']
    if verbose:
        command.append('--verbose')
    if os.path.isdir(repo_location):
        command.append('--no-hardlinks')
    command.extend([pipes.quote(repo_location), target_dir])
    if branch_or_tag:
        command.extend(['--branch', branch_or_tag])
    return execute_git_command(command)
184152
function generateRequirementsFile(
  requirementsPath,
  targetFile,
  serverless,
  servicePath,
  options
) {
  if (
    options.usePoetry &&
    fse.existsSync(path.join(servicePath, 'pyproject.toml'))
  ) {
    filterRequirementsFile(
      path.join(servicePath, '.serverless/requirements.txt'),
      targetFile,
      options
    );
    serverless.cli.log(
      `Parsed requirements.txt from pyproject.toml in ${targetFile}...`
    );
  } else if (
    options.usePipenv &&
    fse.existsSync(path.join(servicePath, 'Pipfile'))
  ) {
    filterRequirementsFile(
      path.join(servicePath, '.serverless/requirements.txt'),
      targetFile,
      options
    );
    serverless.cli.log(
      `Parsed requirements.txt from Pipfile in ${targetFile}...`
    );
  } else {
    filterRequirementsFile(requirementsPath, targetFile, options);
    serverless.cli.log(
      `Generated requirements from ${requirementsPath} in ${targetFile}...`
    );
  }
}
817831
def create_branch(self, new_branch, delete_empty=False):
        
        logger.info("Preparing to create branch {} from {}".format(new_branch, self.config.branch))
        try:
            # create new branch
            self.provider.create_branch(
                base_branch=self.config.branch,
                new_branch=new_branch,
                repo=self.user_repo
            )
            logger.info("Created branch {} from {}".format(new_branch, self.config.branch))
            return True
        except BranchExistsError:
            logger.info("Branch {} exists.".format(new_branch))
            # if the branch exists, is empty and delete_empty is set, delete it and call
            # this function again
            if delete_empty:
                if self.provider.is_empty_branch(self.user_repo, self.config.branch, new_branch,
                                                 self.config.branch_prefix):
                    self.provider.delete_branch(self.user_repo, new_branch,
                                                self.config.branch_prefix)
                    logger.info("Branch {} was empty and has been deleted".format(new_branch))
                    return self.create_branch(new_branch, delete_empty=False)
                logger.info("Branch {} is not empty".format(new_branch))
        return False
542257
def git_try_describe(repo_path):
    
    try:
        p = subprocess.Popen(['git', 'describe', '--always', '--dirty'],
                             cwd=repo_path, stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
        output, _ = p.communicate()
    except:
        return None
    else:
        if p.returncode == 0:
            return output.strip()

    return None
370410
def repo_context(url, branch=None, quiet=True, dest_ctx=temp_dir):
	
	exe = 'git' if 'git' in url else 'hg'
	with dest_ctx() as repo_dir:
		cmd = [exe, 'clone', url, repo_dir]
		if branch:
			cmd.extend(['--branch', branch])
		devnull = open(os.path.devnull, 'w')
		stdout = devnull if quiet else None
		subprocess.check_call(cmd, stdout=stdout)
		yield repo_dir
48195
def update_changed_requirements():
    
    reqs_path = join(env.proj_path, env.reqs_path)
    get_reqs = lambda: run("cat %s" % reqs_path, show=False)
    old_reqs = get_reqs() if env.reqs_path else ""
    yield
    if old_reqs:
        new_reqs = get_reqs()
        if old_reqs == new_reqs:
            # Unpinned requirements should always be checked.
            for req in new_reqs.split("\n"):
                if req.startswith("-e"):
                    if "@" not in req:
                        # Editable requirement without pinned commit.
                        break
                elif req.strip() and not req.startswith("#"):
                    if not set(">=<") & set(req):
                        # PyPI requirement without version.
                        break
            else:
                # All requirements are pinned.
                return
        pip("-r %s/%s" % (env.proj_path, env.reqs_path))
169417
def pypi(
    click_ctx,
    requirements,
    index=None,
    python_version=3,
    exclude_packages=None,
    output=None,
    subgraph_check_api=None,
    no_transitive=True,
    no_pretty=False,
):
    """"""
    requirements = [requirement.strip() for requirement in requirements.split("\\n") if requirement]

    if not requirements:
        _LOG.error("No requirements specified, exiting")
        sys.exit(1)

    if not subgraph_check_api:
        _LOG.info(
            "No subgraph check API provided, no queries will be done for dependency subgraphs that should be avoided"
        )  # Ignore PycodestyleBear (E501)

    result = resolve_python(
        requirements,
        index_urls=index.split(",") if index else ("https://pypi.org/simple",),
        python_version=int(python_version),
        transitive=not no_transitive,
        exclude_packages=set(map(str.strip, (exclude_packages or "").split(","))),
        subgraph_check_api=subgraph_check_api,
    )

    print_command_result(
        click_ctx,
        result,
        analyzer=analyzer_name,
        analyzer_version=analyzer_version,
        output=output or "-",
        pretty=not no_pretty,
    )
1011558
def load(self):
        """"""
        if not git:
            raise EnvironmentError(MISSING_GIT_ERROR)

        if os.path.exists(self.path):
            if not config.CACHE_DISABLE:
                return
            shutil.rmtree(self.path, ignore_errors=True)

        with files.remove_on_exception(self.path):
            url = self.GIT_URL.format(**vars(self))
            repo = git.Repo.clone_from(
                url=url, to_path=self.path, b=self.branch)
            if self.commit:
                repo.head.reset(self.commit, index=True, working_tree=True)
775660
def create(gitpath, cache=None):
    
    if gitpath.startswith(config.LIBRARY_PREFIX):
        path = gitpath[len(config.LIBRARY_PREFIX):]
        return Library(*path.split('/'), cache=cache)
831465
def freeze(self):
        '''
        
        '''
        remote_path = os.path.join(self.venv, 'requirements.txt')
        run('{} freeze > {}'.format(self.pip(), remote_path))
        get(remote_path, self.requirements)
401128
def get_install_requires():
    
    requirements = []
    for line in open('requirements.txt').readlines():
        # skip to next iteration if comment or empty line
        if line.startswith('#') or line == '' or line.startswith('http') or line.startswith('git'):
            continue
        # add line to requirements
        requirements.append(line)
    return requirements
446911
def release():
    

    from secrets import pypi_auth

    # Check that all changes are committed before creating a new version
    git_check()

    # Test package
    test()

    # Increment version
    inc_version()

    # Commit new version, create tag for version and push everything to origin
    git_push()

    # Build and publish package
    build()
    pathname = 'dist/pynb-{}.tar.gz'.format(version.__version__)
    docker_exec('twine upload -u {user} -p {pass} {pathname}'.format(pathname=pathname, **pypi_auth))

    # Remove temporary files
    clean()
634742
def reqs(amend: bool = False, stage: bool = False):
    
    changed_files = CTX.repo.changed_files()
    if 'requirements.txt' in changed_files or 'requirements-dev.txt' in changed_files:
        LOGGER.error('Requirements have changed; cannot update them')
        sys.exit(-1)
    _write_reqs(amend, stage)
796342
def add():
    

    editor = find_editor()

    handle, tmp_path = tempfile.mkstemp(".rst")
    os.close(handle)
    atexit.register(lambda : os.unlink(tmp_path))

    def init_tmp_with_template():
        with open(tmp_path, "wt", encoding="utf-8") as file:
            # hack:
            # my editor likes to strip trailing whitespace from lines.
            # normally this is a good idea.  but in the case of the template
            # it's unhelpful.
            # so, manually ensure there's a space at the end of the bpo line.
            text = template

            bpo_line = ".. bpo:"
            without_space = "\n" + bpo_line + "\n"
            with_space = "\n" + bpo_line + " \n"
            if without_space not in text:
                sys.exit("Can't find BPO line to ensure there's a space on the end!")
            text = text.replace(without_space, with_space)
            file.write(text)

    init_tmp_with_template()

    # We need to be clever about EDITOR.
    # On the one hand, it might be a legitimate path to an
    #   executable containing spaces.
    # On the other hand, it might be a partial command-line
    #   with options.
    if shutil.which(editor):
        args = [editor]
    else:
        args = list(shlex.split(editor))
        if not shutil.which(args[0]):
            sys.exit(f("Invalid GIT_EDITOR / EDITOR value: {editor}"))
    args.append(tmp_path)

    while True:
        subprocess.run(args)

        failure = None
        blurb = Blurbs()
        try:
            blurb.load(tmp_path)
        except BlurbError as e:
            failure = str(e)

        if not failure:
            assert len(blurb) # if parse_blurb succeeds, we should always have a body
            if len(blurb) > 1:
                failure = "Too many entries!  Don't specify '..' on a line by itself."

        if failure:
            print()
            print(f("Error: {failure}"))
            print()
            try:
                prompt("Hit return to retry (or Ctrl-C to abort)")
            except KeyboardInterrupt:
                print()
                return
            print()
            continue
        break

    path = blurb.save_next()
    git_add_files.append(path)
    flush_git_add_files()
    print("Ready for commit.")