We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
pip-compile quiet
Feature request:

Add -q/--quiet flag to pip-sync command.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `piptools/logging.py`
Content:
```
1 # coding: utf-8
2 from __future__ import (absolute_import, division, print_function,
3                         unicode_literals)
4 
5 import sys
6 
7 from . import click
8 
9 
10 class LogContext(object):
11     def __init__(self, verbose=False):
12         self.verbose = verbose
13 
14     def log(self, *args, **kwargs):
15         click.secho(*args, **kwargs)
16 
17     def debug(self, *args, **kwargs):
18         if self.verbose:
19             self.log(*args, **kwargs)
20 
21     def info(self, *args, **kwargs):
22         self.log(*args, **kwargs)
23 
24     def warning(self, *args, **kwargs):
25         kwargs.setdefault('fg', 'yellow')
26         kwargs.setdefault('file', sys.stderr)
27         self.log(*args, **kwargs)
28 
29     def error(self, *args, **kwargs):
30         kwargs.setdefault('fg', 'red')
31         kwargs.setdefault('file', sys.stderr)
32         self.log(*args, **kwargs)
33 
34 
35 log = LogContext()
36
```

Path: `piptools/scripts/compile.py`
Content:
```
1 # coding: utf-8
2 from __future__ import (absolute_import, division, print_function,
3                         unicode_literals)
4 
5 import optparse
6 import os
7 import sys
8 import tempfile
9 
10 from .._compat import (
11     install_req_from_line,
12     parse_requirements,
13     cmdoptions,
14     Command,
15 )
16 
17 from .. import click
18 from ..exceptions import PipToolsError
19 from ..logging import log
20 from ..repositories import LocalRequirementsRepository, PyPIRepository
21 from ..resolver import Resolver
22 from ..utils import (dedup, is_pinned_requirement, key_from_req, UNSAFE_PACKAGES)
23 from ..writer import OutputWriter
24 
25 DEFAULT_REQUIREMENTS_FILE = 'requirements.in'
26 
27 
28 class PipCommand(Command):
29     name = 'PipCommand'
30 
31 
32 @click.command()
33 @click.version_option()
34 @click.option('-v', '--verbose', is_flag=True, help="Show more output")
35 @click.option('-n', '--dry-run', is_flag=True, help="Only show what would happen, don't change anything")
36 @click.option('-p', '--pre', is_flag=True, default=None, help="Allow resolving to prereleases (default is not)")
37 @click.option('-r', '--rebuild', is_flag=True, help="Clear any caches upfront, rebuild from scratch")
38 @click.option('-f', '--find-links', multiple=True, help="Look for archives in this directory or on this HTML page", envvar='PIP_FIND_LINKS')  # noqa
39 @click.option('-i', '--index-url', help="Change index URL (defaults to PyPI)", envvar='PIP_INDEX_URL')
40 @click.option('--extra-index-url', multiple=True, help="Add additional index URL to search", envvar='PIP_EXTRA_INDEX_URL')  # noqa
41 @click.option('--cert', help="Path to alternate CA bundle.")
42 @click.option('--client-cert', help="Path to SSL client certificate, a single file containing the private key and the certificate in PEM format.")  # noqa
43 @click.option('--trusted-host', multiple=True, envvar='PIP_TRUSTED_HOST',
44               help="Mark this host as trusted, even though it does not have "
45                    "valid or any HTTPS.")
46 @click.option('--header/--no-header', is_flag=True, default=True,
47               help="Add header to generated file")
48 @click.option('--index/--no-index', is_flag=True, default=True,
49               help="Add index URL to generated file")
50 @click.option('--emit-trusted-host/--no-emit-trusted-host', is_flag=True,
51               default=True, help="Add trusted host option to generated file")
52 @click.option('--annotate/--no-annotate', is_flag=True, default=True,
53               help="Annotate results, indicating where dependencies come from")
54 @click.option('-U', '--upgrade', is_flag=True, default=False,
55               help='Try to upgrade all dependencies to their latest versions')
56 @click.option('-P', '--upgrade-package', 'upgrade_packages', nargs=1, multiple=True,
57               help="Specify particular packages to upgrade.")
58 @click.option('-o', '--output-file', nargs=1, type=str, default=None,
59               help=('Output file name. Required if more than one input file is given. '
60                     'Will be derived from input file otherwise.'))
61 @click.option('--allow-unsafe', is_flag=True, default=False,
62               help="Pin packages considered unsafe: {}".format(', '.join(sorted(UNSAFE_PACKAGES))))
63 @click.option('--generate-hashes', is_flag=True, default=False,
64               help="Generate pip 8 style hashes in the resulting requirements file.")
65 @click.option('--max-rounds', default=10,
66               help="Maximum number of rounds before resolving the requirements aborts.")
67 @click.argument('src_files', nargs=-1, type=click.Path(exists=True, allow_dash=True))
68 def cli(verbose, dry_run, pre, rebuild, find_links, index_url, extra_index_url,
69         cert, client_cert, trusted_host, header, index, emit_trusted_host, annotate,
70         upgrade, upgrade_packages, output_file, allow_unsafe, generate_hashes,
71         src_files, max_rounds):
72     """Compiles requirements.txt from requirements.in specs."""
73     log.verbose = verbose
74 
75     if len(src_files) == 0:
76         if os.path.exists(DEFAULT_REQUIREMENTS_FILE):
77             src_files = (DEFAULT_REQUIREMENTS_FILE,)
78         elif os.path.exists('setup.py'):
79             src_files = ('setup.py',)
80             if not output_file:
81                 output_file = 'requirements.txt'
82         else:
83             raise click.BadParameter(("If you do not specify an input file, "
84                                       "the default is {} or setup.py").format(DEFAULT_REQUIREMENTS_FILE))
85 
86     if len(src_files) == 1 and src_files[0] == '-':
87         if not output_file:
88             raise click.BadParameter('--output-file is required if input is from stdin')
89 
90     if len(src_files) > 1 and not output_file:
91         raise click.BadParameter('--output-file is required if two or more input files are given.')
92 
93     if output_file:
94         dst_file = output_file
95     else:
96         base_name = src_files[0].rsplit('.', 1)[0]
97         dst_file = base_name + '.txt'
98 
99     if upgrade and upgrade_packages:
100         raise click.BadParameter('Only one of --upgrade or --upgrade-package can be provided as an argument.')
101 
102     ###
103     # Setup
104     ###
105 
106     pip_command = get_pip_command()
107 
108     pip_args = []
109     if find_links:
110         for link in find_links:
111             pip_args.extend(['-f', link])
112     if index_url:
113         pip_args.extend(['-i', index_url])
114     if extra_index_url:
115         for extra_index in extra_index_url:
116             pip_args.extend(['--extra-index-url', extra_index])
117     if cert:
118         pip_args.extend(['--cert', cert])
119     if client_cert:
120         pip_args.extend(['--client-cert', client_cert])
121     if pre:
122         pip_args.extend(['--pre'])
123     if trusted_host:
124         for host in trusted_host:
125             pip_args.extend(['--trusted-host', host])
126 
127     pip_options, _ = pip_command.parse_args(pip_args)
128 
129     session = pip_command._build_session(pip_options)
130     repository = PyPIRepository(pip_options, session)
131 
132     upgrade_install_reqs = {}
133     # Proxy with a LocalRequirementsRepository if --upgrade is not specified
134     # (= default invocation)
135     if not upgrade and os.path.exists(dst_file):
136         ireqs = parse_requirements(dst_file, finder=repository.finder, session=repository.session, options=pip_options)
137         # Exclude packages from --upgrade-package/-P from the existing pins: We want to upgrade.
138         upgrade_reqs_gen = (install_req_from_line(pkg) for pkg in upgrade_packages)
139         upgrade_install_reqs = {key_from_req(install_req.req): install_req for install_req in upgrade_reqs_gen}
140 
141         existing_pins = {key_from_req(ireq.req): ireq
142                          for ireq in ireqs
143                          if is_pinned_requirement(ireq) and key_from_req(ireq.req) not in upgrade_install_reqs}
144         repository = LocalRequirementsRepository(existing_pins, repository)
145 
146     log.debug('Using indexes:')
147     # remove duplicate index urls before processing
148     repository.finder.index_urls = list(dedup(repository.finder.index_urls))
149     for index_url in repository.finder.index_urls:
150         log.debug('  {}'.format(index_url))
151 
152     if repository.finder.find_links:
153         log.debug('')
154         log.debug('Configuration:')
155         for find_link in repository.finder.find_links:
156             log.debug('  -f {}'.format(find_link))
157 
158     ###
159     # Parsing/collecting initial requirements
160     ###
161 
162     constraints = []
163     for src_file in src_files:
164         is_setup_file = os.path.basename(src_file) == 'setup.py'
165         if is_setup_file or src_file == '-':
166             # pip requires filenames and not files. Since we want to support
167             # piping from stdin, we need to briefly save the input from stdin
168             # to a temporary file and have pip read that.  also used for
169             # reading requirements from install_requires in setup.py.
170             tmpfile = tempfile.NamedTemporaryFile(mode='wt', delete=False)
171             if is_setup_file:
172                 from distutils.core import run_setup
173                 dist = run_setup(src_file)
174                 tmpfile.write('\n'.join(dist.install_requires))
175             else:
176                 tmpfile.write(sys.stdin.read())
177             tmpfile.flush()
178             constraints.extend(parse_requirements(
179                 tmpfile.name, finder=repository.finder, session=repository.session, options=pip_options))
180         else:
181             constraints.extend(parse_requirements(
182                 src_file, finder=repository.finder, session=repository.session, options=pip_options))
183 
184     constraints.extend(upgrade_install_reqs.values())
185 
186     # Filter out pip environment markers which do not match (PEP496)
187     constraints = [req for req in constraints
188                    if req.markers is None or req.markers.evaluate()]
189 
190     # Check the given base set of constraints first
191     Resolver.check_constraints(constraints)
192 
193     try:
194         resolver = Resolver(constraints, repository, prereleases=pre,
195                             clear_caches=rebuild, allow_unsafe=allow_unsafe)
196         results = resolver.resolve(max_rounds=max_rounds)
197         if generate_hashes:
198             hashes = resolver.resolve_hashes(results)
199         else:
200             hashes = None
201     except PipToolsError as e:
202         log.error(str(e))
203         sys.exit(2)
204 
205     log.debug('')
206 
207     ##
208     # Output
209     ##
210 
211     # Compute reverse dependency annotations statically, from the
212     # dependency cache that the resolver has populated by now.
213     #
214     # TODO (1a): reverse deps for any editable package are lost
215     #            what SHOULD happen is that they are cached in memory, just
216     #            not persisted to disk!
217     #
218     # TODO (1b): perhaps it's easiest if the dependency cache has an API
219     #            that could take InstallRequirements directly, like:
220     #
221     #                cache.set(ireq, ...)
222     #
223     #            then, when ireq is editable, it would store in
224     #
225     #              editables[egg_name][link_without_fragment] = deps
226     #              editables['pip-tools']['git+...ols.git@future'] = {'click>=3.0', 'six'}
227     #
228     #            otherwise:
229     #
230     #              self[as_name_version_tuple(ireq)] = {'click>=3.0', 'six'}
231     #
232     reverse_dependencies = None
233     if annotate:
234         reverse_dependencies = resolver.reverse_dependencies(results)
235 
236     writer = OutputWriter(src_files, dst_file, dry_run=dry_run,
237                           emit_header=header, emit_index=index,
238                           emit_trusted_host=emit_trusted_host,
239                           annotate=annotate,
240                           generate_hashes=generate_hashes,
241                           default_index_url=repository.DEFAULT_INDEX_URL,
242                           index_urls=repository.finder.index_urls,
243                           trusted_hosts=pip_options.trusted_hosts,
244                           format_control=repository.finder.format_control,
245                           allow_unsafe=allow_unsafe)
246     writer.write(results=results,
247                  unsafe_requirements=resolver.unsafe_constraints,
248                  reverse_dependencies=reverse_dependencies,
249                  primary_packages={key_from_req(ireq.req) for ireq in constraints if not ireq.constraint},
250                  markers={key_from_req(ireq.req): ireq.markers
251                           for ireq in constraints if ireq.markers},
252                  hashes=hashes)
253 
254     if dry_run:
255         log.warning('Dry-run, so nothing updated.')
256 
257 
258 def get_pip_command():
259     # Use pip's parser for pip.conf management and defaults.
260     # General options (find_links, index_url, extra_index_url, trusted_host,
261     # and pre) are defered to pip.
262     pip_command = PipCommand()
263     pip_command.parser.add_option(cmdoptions.no_binary())
264     pip_command.parser.add_option(cmdoptions.only_binary())
265     index_opts = cmdoptions.make_option_group(
266         cmdoptions.index_group,
267         pip_command.parser,
268     )
269     pip_command.parser.insert_option_group(0, index_opts)
270     pip_command.parser.add_option(optparse.Option('--pre', action='store_true', default=False))
271 
272     return pip_command
273
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/piptools/logging.py b/piptools/logging.py
--- a/piptools/logging.py
+++ b/piptools/logging.py
@@ -8,18 +8,19 @@
 
 
 class LogContext(object):
-    def __init__(self, verbose=False):
-        self.verbose = verbose
+    def __init__(self, verbosity=0):
+        self.verbosity = verbosity
 
     def log(self, *args, **kwargs):
         click.secho(*args, **kwargs)
 
     def debug(self, *args, **kwargs):
-        if self.verbose:
+        if self.verbosity >= 1:
             self.log(*args, **kwargs)
 
     def info(self, *args, **kwargs):
-        self.log(*args, **kwargs)
+        if self.verbosity >= 0:
+            self.log(*args, **kwargs)
 
     def warning(self, *args, **kwargs):
         kwargs.setdefault('fg', 'yellow')
diff --git a/piptools/scripts/compile.py b/piptools/scripts/compile.py
--- a/piptools/scripts/compile.py
+++ b/piptools/scripts/compile.py
@@ -31,7 +31,8 @@
 
 @click.command()
 @click.version_option()
-@click.option('-v', '--verbose', is_flag=True, help="Show more output")
+@click.option('-v', '--verbose', count=True, help="Show more output")
+@click.option('-q', '--quiet', count=True, help="Give less output")
 @click.option('-n', '--dry-run', is_flag=True, help="Only show what would happen, don't change anything")
 @click.option('-p', '--pre', is_flag=True, default=None, help="Allow resolving to prereleases (default is not)")
 @click.option('-r', '--rebuild', is_flag=True, help="Clear any caches upfront, rebuild from scratch")
@@ -65,12 +66,12 @@
 @click.option('--max-rounds', default=10,
               help="Maximum number of rounds before resolving the requirements aborts.")
 @click.argument('src_files', nargs=-1, type=click.Path(exists=True, allow_dash=True))
-def cli(verbose, dry_run, pre, rebuild, find_links, index_url, extra_index_url,
+def cli(verbose, quiet, dry_run, pre, rebuild, find_links, index_url, extra_index_url,
         cert, client_cert, trusted_host, header, index, emit_trusted_host, annotate,
         upgrade, upgrade_packages, output_file, allow_unsafe, generate_hashes,
         src_files, max_rounds):
     """Compiles requirements.txt from requirements.in specs."""
-    log.verbose = verbose
+    log.verbosity = verbose - quiet
 
     if len(src_files) == 0:
         if os.path.exists(DEFAULT_REQUIREMENTS_FILE):

{"golden_diff": "diff --git a/piptools/logging.py b/piptools/logging.py\n--- a/piptools/logging.py\n+++ b/piptools/logging.py\n@@ -8,18 +8,19 @@\n \n \n class LogContext(object):\n-    def __init__(self, verbose=False):\n-        self.verbose = verbose\n+    def __init__(self, verbosity=0):\n+        self.verbosity = verbosity\n \n     def log(self, *args, **kwargs):\n         click.secho(*args, **kwargs)\n \n     def debug(self, *args, **kwargs):\n-        if self.verbose:\n+        if self.verbosity >= 1:\n             self.log(*args, **kwargs)\n \n     def info(self, *args, **kwargs):\n-        self.log(*args, **kwargs)\n+        if self.verbosity >= 0:\n+            self.log(*args, **kwargs)\n \n     def warning(self, *args, **kwargs):\n         kwargs.setdefault('fg', 'yellow')\ndiff --git a/piptools/scripts/compile.py b/piptools/scripts/compile.py\n--- a/piptools/scripts/compile.py\n+++ b/piptools/scripts/compile.py\n@@ -31,7 +31,8 @@\n \n @click.command()\n @click.version_option()\n-@click.option('-v', '--verbose', is_flag=True, help=\"Show more output\")\n+@click.option('-v', '--verbose', count=True, help=\"Show more output\")\n+@click.option('-q', '--quiet', count=True, help=\"Give less output\")\n @click.option('-n', '--dry-run', is_flag=True, help=\"Only show what would happen, don't change anything\")\n @click.option('-p', '--pre', is_flag=True, default=None, help=\"Allow resolving to prereleases (default is not)\")\n @click.option('-r', '--rebuild', is_flag=True, help=\"Clear any caches upfront, rebuild from scratch\")\n@@ -65,12 +66,12 @@\n @click.option('--max-rounds', default=10,\n               help=\"Maximum number of rounds before resolving the requirements aborts.\")\n @click.argument('src_files', nargs=-1, type=click.Path(exists=True, allow_dash=True))\n-def cli(verbose, dry_run, pre, rebuild, find_links, index_url, extra_index_url,\n+def cli(verbose, quiet, dry_run, pre, rebuild, find_links, index_url, extra_index_url,\n         cert, client_cert, trusted_host, header, index, emit_trusted_host, annotate,\n         upgrade, upgrade_packages, output_file, allow_unsafe, generate_hashes,\n         src_files, max_rounds):\n     \"\"\"Compiles requirements.txt from requirements.in specs.\"\"\"\n-    log.verbose = verbose\n+    log.verbosity = verbose - quiet\n \n     if len(src_files) == 0:\n         if os.path.exists(DEFAULT_REQUIREMENTS_FILE):\n", "issue": "pip-compile quiet\nFeature request:\r\n\r\nAdd -q/--quiet flag to pip-sync command.\r\n\n", "before_files": [{"content": "# coding: utf-8\nfrom __future__ import (absolute_import, division, print_function,\n                        unicode_literals)\n\nimport sys\n\nfrom . import click\n\n\nclass LogContext(object):\n    def __init__(self, verbose=False):\n        self.verbose = verbose\n\n    def log(self, *args, **kwargs):\n        click.secho(*args, **kwargs)\n\n    def debug(self, *args, **kwargs):\n        if self.verbose:\n            self.log(*args, **kwargs)\n\n    def info(self, *args, **kwargs):\n        self.log(*args, **kwargs)\n\n    def warning(self, *args, **kwargs):\n        kwargs.setdefault('fg', 'yellow')\n        kwargs.setdefault('file', sys.stderr)\n        self.log(*args, **kwargs)\n\n    def error(self, *args, **kwargs):\n        kwargs.setdefault('fg', 'red')\n        kwargs.setdefault('file', sys.stderr)\n        self.log(*args, **kwargs)\n\n\nlog = LogContext()\n", "path": "piptools/logging.py"}, {"content": "# coding: utf-8\nfrom __future__ import (absolute_import, division, print_function,\n                        unicode_literals)\n\nimport optparse\nimport os\nimport sys\nimport tempfile\n\nfrom .._compat import (\n    install_req_from_line,\n    parse_requirements,\n    cmdoptions,\n    Command,\n)\n\nfrom .. import click\nfrom ..exceptions import PipToolsError\nfrom ..logging import log\nfrom ..repositories import LocalRequirementsRepository, PyPIRepository\nfrom ..resolver import Resolver\nfrom ..utils import (dedup, is_pinned_requirement, key_from_req, UNSAFE_PACKAGES)\nfrom ..writer import OutputWriter\n\nDEFAULT_REQUIREMENTS_FILE = 'requirements.in'\n\n\nclass PipCommand(Command):\n    name = 'PipCommand'\n\n\n@click.command()\n@click.version_option()\n@click.option('-v', '--verbose', is_flag=True, help=\"Show more output\")\n@click.option('-n', '--dry-run', is_flag=True, help=\"Only show what would happen, don't change anything\")\n@click.option('-p', '--pre', is_flag=True, default=None, help=\"Allow resolving to prereleases (default is not)\")\n@click.option('-r', '--rebuild', is_flag=True, help=\"Clear any caches upfront, rebuild from scratch\")\n@click.option('-f', '--find-links', multiple=True, help=\"Look for archives in this directory or on this HTML page\", envvar='PIP_FIND_LINKS')  # noqa\n@click.option('-i', '--index-url', help=\"Change index URL (defaults to PyPI)\", envvar='PIP_INDEX_URL')\n@click.option('--extra-index-url', multiple=True, help=\"Add additional index URL to search\", envvar='PIP_EXTRA_INDEX_URL')  # noqa\n@click.option('--cert', help=\"Path to alternate CA bundle.\")\n@click.option('--client-cert', help=\"Path to SSL client certificate, a single file containing the private key and the certificate in PEM format.\")  # noqa\n@click.option('--trusted-host', multiple=True, envvar='PIP_TRUSTED_HOST',\n              help=\"Mark this host as trusted, even though it does not have \"\n                   \"valid or any HTTPS.\")\n@click.option('--header/--no-header', is_flag=True, default=True,\n              help=\"Add header to generated file\")\n@click.option('--index/--no-index', is_flag=True, default=True,\n              help=\"Add index URL to generated file\")\n@click.option('--emit-trusted-host/--no-emit-trusted-host', is_flag=True,\n              default=True, help=\"Add trusted host option to generated file\")\n@click.option('--annotate/--no-annotate', is_flag=True, default=True,\n              help=\"Annotate results, indicating where dependencies come from\")\n@click.option('-U', '--upgrade', is_flag=True, default=False,\n              help='Try to upgrade all dependencies to their latest versions')\n@click.option('-P', '--upgrade-package', 'upgrade_packages', nargs=1, multiple=True,\n              help=\"Specify particular packages to upgrade.\")\n@click.option('-o', '--output-file', nargs=1, type=str, default=None,\n              help=('Output file name. Required if more than one input file is given. '\n                    'Will be derived from input file otherwise.'))\n@click.option('--allow-unsafe', is_flag=True, default=False,\n              help=\"Pin packages considered unsafe: {}\".format(', '.join(sorted(UNSAFE_PACKAGES))))\n@click.option('--generate-hashes', is_flag=True, default=False,\n              help=\"Generate pip 8 style hashes in the resulting requirements file.\")\n@click.option('--max-rounds', default=10,\n              help=\"Maximum number of rounds before resolving the requirements aborts.\")\n@click.argument('src_files', nargs=-1, type=click.Path(exists=True, allow_dash=True))\ndef cli(verbose, dry_run, pre, rebuild, find_links, index_url, extra_index_url,\n        cert, client_cert, trusted_host, header, index, emit_trusted_host, annotate,\n        upgrade, upgrade_packages, output_file, allow_unsafe, generate_hashes,\n        src_files, max_rounds):\n    \"\"\"Compiles requirements.txt from requirements.in specs.\"\"\"\n    log.verbose = verbose\n\n    if len(src_files) == 0:\n        if os.path.exists(DEFAULT_REQUIREMENTS_FILE):\n            src_files = (DEFAULT_REQUIREMENTS_FILE,)\n        elif os.path.exists('setup.py'):\n            src_files = ('setup.py',)\n            if not output_file:\n                output_file = 'requirements.txt'\n        else:\n            raise click.BadParameter((\"If you do not specify an input file, \"\n                                      \"the default is {} or setup.py\").format(DEFAULT_REQUIREMENTS_FILE))\n\n    if len(src_files) == 1 and src_files[0] == '-':\n        if not output_file:\n            raise click.BadParameter('--output-file is required if input is from stdin')\n\n    if len(src_files) > 1 and not output_file:\n        raise click.BadParameter('--output-file is required if two or more input files are given.')\n\n    if output_file:\n        dst_file = output_file\n    else:\n        base_name = src_files[0].rsplit('.', 1)[0]\n        dst_file = base_name + '.txt'\n\n    if upgrade and upgrade_packages:\n        raise click.BadParameter('Only one of --upgrade or --upgrade-package can be provided as an argument.')\n\n    ###\n    # Setup\n    ###\n\n    pip_command = get_pip_command()\n\n    pip_args = []\n    if find_links:\n        for link in find_links:\n            pip_args.extend(['-f', link])\n    if index_url:\n        pip_args.extend(['-i', index_url])\n    if extra_index_url:\n        for extra_index in extra_index_url:\n            pip_args.extend(['--extra-index-url', extra_index])\n    if cert:\n        pip_args.extend(['--cert', cert])\n    if client_cert:\n        pip_args.extend(['--client-cert', client_cert])\n    if pre:\n        pip_args.extend(['--pre'])\n    if trusted_host:\n        for host in trusted_host:\n            pip_args.extend(['--trusted-host', host])\n\n    pip_options, _ = pip_command.parse_args(pip_args)\n\n    session = pip_command._build_session(pip_options)\n    repository = PyPIRepository(pip_options, session)\n\n    upgrade_install_reqs = {}\n    # Proxy with a LocalRequirementsRepository if --upgrade is not specified\n    # (= default invocation)\n    if not upgrade and os.path.exists(dst_file):\n        ireqs = parse_requirements(dst_file, finder=repository.finder, session=repository.session, options=pip_options)\n        # Exclude packages from --upgrade-package/-P from the existing pins: We want to upgrade.\n        upgrade_reqs_gen = (install_req_from_line(pkg) for pkg in upgrade_packages)\n        upgrade_install_reqs = {key_from_req(install_req.req): install_req for install_req in upgrade_reqs_gen}\n\n        existing_pins = {key_from_req(ireq.req): ireq\n                         for ireq in ireqs\n                         if is_pinned_requirement(ireq) and key_from_req(ireq.req) not in upgrade_install_reqs}\n        repository = LocalRequirementsRepository(existing_pins, repository)\n\n    log.debug('Using indexes:')\n    # remove duplicate index urls before processing\n    repository.finder.index_urls = list(dedup(repository.finder.index_urls))\n    for index_url in repository.finder.index_urls:\n        log.debug('  {}'.format(index_url))\n\n    if repository.finder.find_links:\n        log.debug('')\n        log.debug('Configuration:')\n        for find_link in repository.finder.find_links:\n            log.debug('  -f {}'.format(find_link))\n\n    ###\n    # Parsing/collecting initial requirements\n    ###\n\n    constraints = []\n    for src_file in src_files:\n        is_setup_file = os.path.basename(src_file) == 'setup.py'\n        if is_setup_file or src_file == '-':\n            # pip requires filenames and not files. Since we want to support\n            # piping from stdin, we need to briefly save the input from stdin\n            # to a temporary file and have pip read that.  also used for\n            # reading requirements from install_requires in setup.py.\n            tmpfile = tempfile.NamedTemporaryFile(mode='wt', delete=False)\n            if is_setup_file:\n                from distutils.core import run_setup\n                dist = run_setup(src_file)\n                tmpfile.write('\\n'.join(dist.install_requires))\n            else:\n                tmpfile.write(sys.stdin.read())\n            tmpfile.flush()\n            constraints.extend(parse_requirements(\n                tmpfile.name, finder=repository.finder, session=repository.session, options=pip_options))\n        else:\n            constraints.extend(parse_requirements(\n                src_file, finder=repository.finder, session=repository.session, options=pip_options))\n\n    constraints.extend(upgrade_install_reqs.values())\n\n    # Filter out pip environment markers which do not match (PEP496)\n    constraints = [req for req in constraints\n                   if req.markers is None or req.markers.evaluate()]\n\n    # Check the given base set of constraints first\n    Resolver.check_constraints(constraints)\n\n    try:\n        resolver = Resolver(constraints, repository, prereleases=pre,\n                            clear_caches=rebuild, allow_unsafe=allow_unsafe)\n        results = resolver.resolve(max_rounds=max_rounds)\n        if generate_hashes:\n            hashes = resolver.resolve_hashes(results)\n        else:\n            hashes = None\n    except PipToolsError as e:\n        log.error(str(e))\n        sys.exit(2)\n\n    log.debug('')\n\n    ##\n    # Output\n    ##\n\n    # Compute reverse dependency annotations statically, from the\n    # dependency cache that the resolver has populated by now.\n    #\n    # TODO (1a): reverse deps for any editable package are lost\n    #            what SHOULD happen is that they are cached in memory, just\n    #            not persisted to disk!\n    #\n    # TODO (1b): perhaps it's easiest if the dependency cache has an API\n    #            that could take InstallRequirements directly, like:\n    #\n    #                cache.set(ireq, ...)\n    #\n    #            then, when ireq is editable, it would store in\n    #\n    #              editables[egg_name][link_without_fragment] = deps\n    #              editables['pip-tools']['git+...ols.git@future'] = {'click>=3.0', 'six'}\n    #\n    #            otherwise:\n    #\n    #              self[as_name_version_tuple(ireq)] = {'click>=3.0', 'six'}\n    #\n    reverse_dependencies = None\n    if annotate:\n        reverse_dependencies = resolver.reverse_dependencies(results)\n\n    writer = OutputWriter(src_files, dst_file, dry_run=dry_run,\n                          emit_header=header, emit_index=index,\n                          emit_trusted_host=emit_trusted_host,\n                          annotate=annotate,\n                          generate_hashes=generate_hashes,\n                          default_index_url=repository.DEFAULT_INDEX_URL,\n                          index_urls=repository.finder.index_urls,\n                          trusted_hosts=pip_options.trusted_hosts,\n                          format_control=repository.finder.format_control,\n                          allow_unsafe=allow_unsafe)\n    writer.write(results=results,\n                 unsafe_requirements=resolver.unsafe_constraints,\n                 reverse_dependencies=reverse_dependencies,\n                 primary_packages={key_from_req(ireq.req) for ireq in constraints if not ireq.constraint},\n                 markers={key_from_req(ireq.req): ireq.markers\n                          for ireq in constraints if ireq.markers},\n                 hashes=hashes)\n\n    if dry_run:\n        log.warning('Dry-run, so nothing updated.')\n\n\ndef get_pip_command():\n    # Use pip's parser for pip.conf management and defaults.\n    # General options (find_links, index_url, extra_index_url, trusted_host,\n    # and pre) are defered to pip.\n    pip_command = PipCommand()\n    pip_command.parser.add_option(cmdoptions.no_binary())\n    pip_command.parser.add_option(cmdoptions.only_binary())\n    index_opts = cmdoptions.make_option_group(\n        cmdoptions.index_group,\n        pip_command.parser,\n    )\n    pip_command.parser.insert_option_group(0, index_opts)\n    pip_command.parser.add_option(optparse.Option('--pre', action='store_true', default=False))\n\n    return pip_command\n", "path": "piptools/scripts/compile.py"}], "after_files": [{"content": "# coding: utf-8\nfrom __future__ import (absolute_import, division, print_function,\n                        unicode_literals)\n\nimport sys\n\nfrom . import click\n\n\nclass LogContext(object):\n    def __init__(self, verbosity=0):\n        self.verbosity = verbosity\n\n    def log(self, *args, **kwargs):\n        click.secho(*args, **kwargs)\n\n    def debug(self, *args, **kwargs):\n        if self.verbosity >= 1:\n            self.log(*args, **kwargs)\n\n    def info(self, *args, **kwargs):\n        if self.verbosity >= 0:\n            self.log(*args, **kwargs)\n\n    def warning(self, *args, **kwargs):\n        kwargs.setdefault('fg', 'yellow')\n        kwargs.setdefault('file', sys.stderr)\n        self.log(*args, **kwargs)\n\n    def error(self, *args, **kwargs):\n        kwargs.setdefault('fg', 'red')\n        kwargs.setdefault('file', sys.stderr)\n        self.log(*args, **kwargs)\n\n\nlog = LogContext()\n", "path": "piptools/logging.py"}, {"content": "# coding: utf-8\nfrom __future__ import (absolute_import, division, print_function,\n                        unicode_literals)\n\nimport optparse\nimport os\nimport sys\nimport tempfile\n\nfrom .._compat import (\n    install_req_from_line,\n    parse_requirements,\n    cmdoptions,\n    Command,\n)\n\nfrom .. import click\nfrom ..exceptions import PipToolsError\nfrom ..logging import log\nfrom ..repositories import LocalRequirementsRepository, PyPIRepository\nfrom ..resolver import Resolver\nfrom ..utils import (dedup, is_pinned_requirement, key_from_req, UNSAFE_PACKAGES)\nfrom ..writer import OutputWriter\n\nDEFAULT_REQUIREMENTS_FILE = 'requirements.in'\n\n\nclass PipCommand(Command):\n    name = 'PipCommand'\n\n\n@click.command()\n@click.version_option()\n@click.option('-v', '--verbose', count=True, help=\"Show more output\")\n@click.option('-q', '--quiet', count=True, help=\"Give less output\")\n@click.option('-n', '--dry-run', is_flag=True, help=\"Only show what would happen, don't change anything\")\n@click.option('-p', '--pre', is_flag=True, default=None, help=\"Allow resolving to prereleases (default is not)\")\n@click.option('-r', '--rebuild', is_flag=True, help=\"Clear any caches upfront, rebuild from scratch\")\n@click.option('-f', '--find-links', multiple=True, help=\"Look for archives in this directory or on this HTML page\", envvar='PIP_FIND_LINKS')  # noqa\n@click.option('-i', '--index-url', help=\"Change index URL (defaults to PyPI)\", envvar='PIP_INDEX_URL')\n@click.option('--extra-index-url', multiple=True, help=\"Add additional index URL to search\", envvar='PIP_EXTRA_INDEX_URL')  # noqa\n@click.option('--cert', help=\"Path to alternate CA bundle.\")\n@click.option('--client-cert', help=\"Path to SSL client certificate, a single file containing the private key and the certificate in PEM format.\")  # noqa\n@click.option('--trusted-host', multiple=True, envvar='PIP_TRUSTED_HOST',\n              help=\"Mark this host as trusted, even though it does not have \"\n                   \"valid or any HTTPS.\")\n@click.option('--header/--no-header', is_flag=True, default=True,\n              help=\"Add header to generated file\")\n@click.option('--index/--no-index', is_flag=True, default=True,\n              help=\"Add index URL to generated file\")\n@click.option('--emit-trusted-host/--no-emit-trusted-host', is_flag=True,\n              default=True, help=\"Add trusted host option to generated file\")\n@click.option('--annotate/--no-annotate', is_flag=True, default=True,\n              help=\"Annotate results, indicating where dependencies come from\")\n@click.option('-U', '--upgrade', is_flag=True, default=False,\n              help='Try to upgrade all dependencies to their latest versions')\n@click.option('-P', '--upgrade-package', 'upgrade_packages', nargs=1, multiple=True,\n              help=\"Specify particular packages to upgrade.\")\n@click.option('-o', '--output-file', nargs=1, type=str, default=None,\n              help=('Output file name. Required if more than one input file is given. '\n                    'Will be derived from input file otherwise.'))\n@click.option('--allow-unsafe', is_flag=True, default=False,\n              help=\"Pin packages considered unsafe: {}\".format(', '.join(sorted(UNSAFE_PACKAGES))))\n@click.option('--generate-hashes', is_flag=True, default=False,\n              help=\"Generate pip 8 style hashes in the resulting requirements file.\")\n@click.option('--max-rounds', default=10,\n              help=\"Maximum number of rounds before resolving the requirements aborts.\")\n@click.argument('src_files', nargs=-1, type=click.Path(exists=True, allow_dash=True))\ndef cli(verbose, quiet, dry_run, pre, rebuild, find_links, index_url, extra_index_url,\n        cert, client_cert, trusted_host, header, index, emit_trusted_host, annotate,\n        upgrade, upgrade_packages, output_file, allow_unsafe, generate_hashes,\n        src_files, max_rounds):\n    \"\"\"Compiles requirements.txt from requirements.in specs.\"\"\"\n    log.verbosity = verbose - quiet\n\n    if len(src_files) == 0:\n        if os.path.exists(DEFAULT_REQUIREMENTS_FILE):\n            src_files = (DEFAULT_REQUIREMENTS_FILE,)\n        elif os.path.exists('setup.py'):\n            src_files = ('setup.py',)\n            if not output_file:\n                output_file = 'requirements.txt'\n        else:\n            raise click.BadParameter((\"If you do not specify an input file, \"\n                                      \"the default is {} or setup.py\").format(DEFAULT_REQUIREMENTS_FILE))\n\n    if len(src_files) == 1 and src_files[0] == '-':\n        if not output_file:\n            raise click.BadParameter('--output-file is required if input is from stdin')\n\n    if len(src_files) > 1 and not output_file:\n        raise click.BadParameter('--output-file is required if two or more input files are given.')\n\n    if output_file:\n        dst_file = output_file\n    else:\n        base_name = src_files[0].rsplit('.', 1)[0]\n        dst_file = base_name + '.txt'\n\n    if upgrade and upgrade_packages:\n        raise click.BadParameter('Only one of --upgrade or --upgrade-package can be provided as an argument.')\n\n    ###\n    # Setup\n    ###\n\n    pip_command = get_pip_command()\n\n    pip_args = []\n    if find_links:\n        for link in find_links:\n            pip_args.extend(['-f', link])\n    if index_url:\n        pip_args.extend(['-i', index_url])\n    if extra_index_url:\n        for extra_index in extra_index_url:\n            pip_args.extend(['--extra-index-url', extra_index])\n    if cert:\n        pip_args.extend(['--cert', cert])\n    if client_cert:\n        pip_args.extend(['--client-cert', client_cert])\n    if pre:\n        pip_args.extend(['--pre'])\n    if trusted_host:\n        for host in trusted_host:\n            pip_args.extend(['--trusted-host', host])\n\n    pip_options, _ = pip_command.parse_args(pip_args)\n\n    session = pip_command._build_session(pip_options)\n    repository = PyPIRepository(pip_options, session)\n\n    upgrade_install_reqs = {}\n    # Proxy with a LocalRequirementsRepository if --upgrade is not specified\n    # (= default invocation)\n    if not upgrade and os.path.exists(dst_file):\n        ireqs = parse_requirements(dst_file, finder=repository.finder, session=repository.session, options=pip_options)\n        # Exclude packages from --upgrade-package/-P from the existing pins: We want to upgrade.\n        upgrade_reqs_gen = (install_req_from_line(pkg) for pkg in upgrade_packages)\n        upgrade_install_reqs = {key_from_req(install_req.req): install_req for install_req in upgrade_reqs_gen}\n\n        existing_pins = {key_from_req(ireq.req): ireq\n                         for ireq in ireqs\n                         if is_pinned_requirement(ireq) and key_from_req(ireq.req) not in upgrade_install_reqs}\n        repository = LocalRequirementsRepository(existing_pins, repository)\n\n    log.debug('Using indexes:')\n    # remove duplicate index urls before processing\n    repository.finder.index_urls = list(dedup(repository.finder.index_urls))\n    for index_url in repository.finder.index_urls:\n        log.debug('  {}'.format(index_url))\n\n    if repository.finder.find_links:\n        log.debug('')\n        log.debug('Configuration:')\n        for find_link in repository.finder.find_links:\n            log.debug('  -f {}'.format(find_link))\n\n    ###\n    # Parsing/collecting initial requirements\n    ###\n\n    constraints = []\n    for src_file in src_files:\n        is_setup_file = os.path.basename(src_file) == 'setup.py'\n        if is_setup_file or src_file == '-':\n            # pip requires filenames and not files. Since we want to support\n            # piping from stdin, we need to briefly save the input from stdin\n            # to a temporary file and have pip read that.  also used for\n            # reading requirements from install_requires in setup.py.\n            tmpfile = tempfile.NamedTemporaryFile(mode='wt', delete=False)\n            if is_setup_file:\n                from distutils.core import run_setup\n                dist = run_setup(src_file)\n                tmpfile.write('\\n'.join(dist.install_requires))\n            else:\n                tmpfile.write(sys.stdin.read())\n            tmpfile.flush()\n            constraints.extend(parse_requirements(\n                tmpfile.name, finder=repository.finder, session=repository.session, options=pip_options))\n        else:\n            constraints.extend(parse_requirements(\n                src_file, finder=repository.finder, session=repository.session, options=pip_options))\n\n    constraints.extend(upgrade_install_reqs.values())\n\n    # Filter out pip environment markers which do not match (PEP496)\n    constraints = [req for req in constraints\n                   if req.markers is None or req.markers.evaluate()]\n\n    # Check the given base set of constraints first\n    Resolver.check_constraints(constraints)\n\n    try:\n        resolver = Resolver(constraints, repository, prereleases=pre,\n                            clear_caches=rebuild, allow_unsafe=allow_unsafe)\n        results = resolver.resolve(max_rounds=max_rounds)\n        if generate_hashes:\n            hashes = resolver.resolve_hashes(results)\n        else:\n            hashes = None\n    except PipToolsError as e:\n        log.error(str(e))\n        sys.exit(2)\n\n    log.debug('')\n\n    ##\n    # Output\n    ##\n\n    # Compute reverse dependency annotations statically, from the\n    # dependency cache that the resolver has populated by now.\n    #\n    # TODO (1a): reverse deps for any editable package are lost\n    #            what SHOULD happen is that they are cached in memory, just\n    #            not persisted to disk!\n    #\n    # TODO (1b): perhaps it's easiest if the dependency cache has an API\n    #            that could take InstallRequirements directly, like:\n    #\n    #                cache.set(ireq, ...)\n    #\n    #            then, when ireq is editable, it would store in\n    #\n    #              editables[egg_name][link_without_fragment] = deps\n    #              editables['pip-tools']['git+...ols.git@future'] = {'click>=3.0', 'six'}\n    #\n    #            otherwise:\n    #\n    #              self[as_name_version_tuple(ireq)] = {'click>=3.0', 'six'}\n    #\n    reverse_dependencies = None\n    if annotate:\n        reverse_dependencies = resolver.reverse_dependencies(results)\n\n    writer = OutputWriter(src_files, dst_file, dry_run=dry_run,\n                          emit_header=header, emit_index=index,\n                          emit_trusted_host=emit_trusted_host,\n                          annotate=annotate,\n                          generate_hashes=generate_hashes,\n                          default_index_url=repository.DEFAULT_INDEX_URL,\n                          index_urls=repository.finder.index_urls,\n                          trusted_hosts=pip_options.trusted_hosts,\n                          format_control=repository.finder.format_control,\n                          allow_unsafe=allow_unsafe)\n    writer.write(results=results,\n                 unsafe_requirements=resolver.unsafe_constraints,\n                 reverse_dependencies=reverse_dependencies,\n                 primary_packages={key_from_req(ireq.req) for ireq in constraints if not ireq.constraint},\n                 markers={key_from_req(ireq.req): ireq.markers\n                          for ireq in constraints if ireq.markers},\n                 hashes=hashes)\n\n    if dry_run:\n        log.warning('Dry-run, so nothing updated.')\n\n\ndef get_pip_command():\n    # Use pip's parser for pip.conf management and defaults.\n    # General options (find_links, index_url, extra_index_url, trusted_host,\n    # and pre) are defered to pip.\n    pip_command = PipCommand()\n    pip_command.parser.add_option(cmdoptions.no_binary())\n    pip_command.parser.add_option(cmdoptions.only_binary())\n    index_opts = cmdoptions.make_option_group(\n        cmdoptions.index_group,\n        pip_command.parser,\n    )\n    pip_command.parser.insert_option_group(0, index_opts)\n    pip_command.parser.add_option(optparse.Option('--pre', action='store_true', default=False))\n\n    return pip_command\n", "path": "piptools/scripts/compile.py"}]}