Update the requirements.txt file and reformat the Pipfile.
773596
def main(requirements_file, skip_requirements_file, pipfile, skip_pipfile):
    # type: (str, bool, str, bool) -> None
    """"""
    pipfile_path = path.Path(pipfile)
    pf = load_pipfile(pipfile_path)

    if not skip_requirements_file:
        requirements_file_path = path.Path(requirements_file)
        update_requirements(requirements_file_path, pf)

    if not skip_pipfile:
        dump_pipfile(pipfile_path, pf)
640760
def _generate_requirements(self):
        """"""
        if not self._pip_packages:
            return

        reqs = ''
        for req in self._pip_packages:
                reqs += "{}\n".format(req)
        reqs_include = {
            'contents': reqs,
            'target':'opt/python/streams',
            'name': 'requirements.txt'}

        if 'opt' not in self._files:
             self._files['opt'] = [reqs_include]
        else:
             self._files['opt'].append(reqs_include)
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))
791227
def ensure_pipfile(validate=True, skip_requirements=False, system=False):
    """"""
    from .environments import PIPENV_VIRTUALENV

    # Assert Pipfile exists.
    python = which("python") if not (USING_DEFAULT_PYTHON or system) else None
    if project.pipfile_is_empty:
        # Show an error message and exit if system is passed and no pipfile exists
        if system and not PIPENV_VIRTUALENV:
            raise exceptions.PipenvOptionsError(
                "--system",
                "--system is intended to be used for pre-existing Pipfile "
                "installation, not installation of specific packages. Aborting."
            )
        # If there's a requirements file, but no Pipfile…
        if project.requirements_exists and not skip_requirements:
            click.echo(
                crayons.normal(
                    fix_utf8("requirements.txt found, instead of Pipfile! Converting…"),
                    bold=True,
                )
            )
            # Create a Pipfile…
            project.create_pipfile(python=python)
            with create_spinner("Importing requirements...") as sp:
                # Import requirements.txt.
                try:
                    import_requirements()
                except Exception:
                    sp.fail(environments.PIPENV_SPINNER_FAIL_TEXT.format("Failed..."))
                else:
                    sp.ok(environments.PIPENV_SPINNER_OK_TEXT.format("Success!"))
            # Warn the user of side-effects.
            click.echo(
                u"{0}: Your {1} now contains pinned versions, if your {2} did. \n"
                "We recommend updating your {1} to specify the {3} version, instead."
                "".format(
                    crayons.red("Warning", bold=True),
                    crayons.normal("Pipfile", bold=True),
                    crayons.normal("requirements.txt", bold=True),
                    crayons.normal('"*"', bold=True),
                )
            )
        else:
            click.echo(
                crayons.normal(fix_utf8("Creating a Pipfile for this project…"), bold=True),
                err=True,
            )
            # Create the pipfile if it doesn't exist.
            project.create_pipfile(python=python)
    # Validate the Pipfile's contents.
    if validate and project.virtualenv_exists and not PIPENV_SKIP_VALIDATION:
        # Ensure that Pipfile is using proper casing.
        p = project.parsed_pipfile
        changed = project.ensure_proper_casing()
        # Write changes out to disk.
        if changed:
            click.echo(
                crayons.normal(u"Fixing package names in Pipfile…", bold=True), err=True
            )
            project.write_toml(p)
1354617
def replace_in_files(dirname, replace):
    """"""
    filepath = os.path.abspath(dirname / "requirements.in")
    if os.path.isfile(filepath) and header_footer_exists(filepath):
        replaced = re.sub(Utils.exp, replace, get_file_string(filepath))
        with open(filepath, "w") as f:
            f.write(replaced)
        print(color(
            "Written to file: {}".format(filepath),
            fg='magenta', style='bold'))
696817
def pip_install(self, reqs):
        """"""
        if not reqs:
            return
        log.info('Calling pip to install %s', reqs)
        check_call([
            sys.executable, '-m', 'pip', 'install', '--ignore-installed',
            '--prefix', self.path] + list(reqs))
482412
def read_requirements():
    ''''''
    reqs_path = os.path.join('.', 'requirements.txt')
    install_reqs = parse_requirements(reqs_path, session=PipSession())
    reqs = [str(ir.req) for ir in install_reqs]
    return reqs
1346385
def update(**kwargs):
    '''
    
    '''
    stdout = {}

    for mode in ('fetch', 'install'):
        err_ = {}
        ret = _wrapper(mode, err_=err_, **kwargs)
        if 'retcode' in err_ and err_['retcode'] != 0:
            return ret
        if 'stdout' in err_:
            stdout[mode] = err_['stdout']
    return '\n'.join(['{0}: {1}'.format(k, v) for (k, v) in six.iteritems(stdout)])
1050942
def update(self):
        """"""
        for linenum in reversed(sorted(self.updates)):
            self.replace_baseline_repr(linenum, self.updates[linenum])

        if not self.TEST_MODE:
            path = '{}.update{}'.format(*os.path.splitext(self.path))
            with io.open(path, 'w', encoding='utf-8') as fh:
                fh.write('\n'.join(self.lines))
            print('UPDATE: {}'.format(self.showpath(path)))
1218191
def pip(filename):
    ''''''
    path = join('requirements', filename)
    return [line for line in open(path).readlines() if not line.startswith('-e')]
941408
def load(klass, filename, inject_env=True):
        """"""
        p = PipfileParser(filename=filename)
        pipfile = klass(filename=filename)
        pipfile.data = p.parse(inject_env=inject_env)
        return pipfile
1348948
def pipupdate():
    

    packages = [d for d in pkg_resources.working_set]
    subprocess.call('pip install --upgrade ' + ' '.join(packages))
712810
def install(self):
        
        other_args = list(requirement_args(self._argv, want_other=True))
        archive_path = join(self._temp_path, self._downloaded_filename())
        # -U so it installs whether pip deems the requirement "satisfied" or
        # not. This is necessary for GitHub-sourced zips, which change without
        # their version numbers changing.
        run_pip(['install'] + other_args + ['--no-deps', '-U', archive_path])
893525
def replace_in_file(filename: str, text_from: str, text_to: str) -> None:
    
    log.info("Amending {}: {} -> {}",
             filename, repr(text_from), repr(text_to))
    with open(filename) as infile:
        contents = infile.read()
    contents = contents.replace(text_from, text_to)
    with open(filename, 'w') as outfile:
        outfile.write(contents)
980429
def rewrite_file_imports(item, vendored_libs, vendor_dir):
    """"""
    text = item.read_text(encoding='utf-8')
    renames = LIBRARY_RENAMES
    for k in LIBRARY_RENAMES.keys():
        if k not in vendored_libs:
            vendored_libs.append(k)
    for lib in vendored_libs:
        to_lib = lib
        if lib in renames:
            to_lib = renames[lib]
        text = re.sub(
            r'([\n\s]*)import %s([\n\s\.]+)' % lib,
            r'\1import %s\2' % to_lib,
            text,
        )
        text = re.sub(
            r'([\n\s]*)from %s([\s\.])+' % lib,
            r'\1from %s\2' % to_lib,
            text,
        )
        text = re.sub(
            r"(\n\s*)__import__\('%s([\s'\.])+" % lib,
            r"\1__import__('%s\2" % to_lib,
            text,
        )
    item.write_text(text, encoding='utf-8')
303252
def pip_compile(*packages: str):
    """"""
    result = None
    packages = "\n".join(packages)

    with tempfile.TemporaryDirectory() as tmp_dirname, cwd(tmp_dirname):
        with open("requirements.in", "w") as requirements_file:
            requirements_file.write(packages)

        runner = CliRunner()

        try:
            result = runner.invoke(cli, ["requirements.in"], catch_exceptions=False)
        except Exception as exc:
            raise ThothPipCompileError(str(exc)) from exc

        if result.exit_code != 0:
            error_msg = (
                f"pip-compile returned non-zero ({result.exit_code:d}) " f"output: {result.output_bytes.decode():s}"
            )
            raise ThothPipCompileError(error_msg)

    return result.output_bytes.decode()
369798
def piprot():
    
    cli_parser = argparse.ArgumentParser(
        epilog="Here's hoping your requirements are nice and fresh!"
    )
    cli_parser.add_argument(
        '-v', '--verbose', action='store_true',
        help='verbosity, can be supplied more than once '
             '(enabled by default, use --quiet to disable)'
    )
    cli_parser.add_argument('-l', '--latest', action='store_true',
                            help='print the lastest available version for out '
                                 'of date requirements')
    cli_parser.add_argument('-x', '--verbatim', action='store_true',
                            help='output the full requirements file, with '
                                 'added comments with potential updates')
    cli_parser.add_argument('-q', '--quiet', action='store_true',
                            help='be a little less verbose with the output '
                                 '(<0.3 behaviour)')
    cli_parser.add_argument('-o', '--outdated', action='store_true',
                            help='only list outdated requirements')

    cli_parser.add_argument('-g', '--github',
                            help='Test the requirements from a GitHub repo. '
                                 'Requires that a `requirements.txt` file '
                                 'exists in the root of the repository.')

    cli_parser.add_argument(
        '-b', '--branch',
        help='The branch to test requirements from, used with '
             'the Github URL support.')

    cli_parser.add_argument(
        '-t', '--token',
        help='Github personal access token to be used with '
             'the Github URL support.')

    cli_parser.add_argument(
        '-p', '--path',
        help='Path to requirements file in remote repository.')

    cli_parser.add_argument(
        '-d', '--delay',
        help='Delay before an outdated package triggers an error.'
             '(in days, default to 1).')

    cli_parser.add_argument('-u', '--url',
                            help='URL to requirements file.')

    # if there is a requirements.txt file, use it by default. Otherwise print
    # usage if there are no arguments.
    nargs = '+'

    if (
        '--github' in sys.argv
        or '-g' in sys.argv
        or '-u' in sys.argv
        or '--url' in sys.argv
    ):
        nargs = "*"

    default = None
    if os.path.isfile('requirements.txt'):
        nargs = "*"
        default = [open('requirements.txt')]

    cli_parser.add_argument('file', nargs=nargs, type=argparse.FileType(),
                            default=default, help='requirements file(s), use '
                                                  '`-` for stdin')

    cli_args = cli_parser.parse_args()

    if len(cli_args.file) > 1 and cli_args.verbatim:
        sys.exit('--verbatim only allowed for single requirements files')

    verbose = True
    if cli_args.quiet:
        verbose = False
    elif cli_args.verbatim:
        verbose = False

    # call the main function to kick off the real work
    main(req_files=cli_args.file, verbose=verbose, outdated=cli_args.outdated,
         latest=cli_args.latest, verbatim=cli_args.verbatim,
         repo=cli_args.github, branch=cli_args.branch, path=cli_args.path,
         token=cli_args.token, url=cli_args.url, delay=cli_args.delay)