internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: pallets/click

Issue:
Incorrect names being picked
Docs state `By default, the name of the parameter is the first long option defined; otherwise the first short one is used`.

The implementation of this is in `_parse_decls` method of `Option` which has a line...

```python
possible_names.sort(key=lambda x: len(x[0]))
name = possible_names[-1][1].replace('-', '_').lower()
```

... currently [here](https://github.com/pallets/click/blob/master/click/core.py#L1570)

This invocation of `list.sort` with `key=` essentially makes every short option equal to each other and every long option equal to each other.  The original order they were defined in is subject to change.

In fact... even if it were to maintain that order, the code would actually be grabbing the __*last*__ long parameter.

Fix coming soon... I'll submit it.  I'll change the code to match the docs.


Discussion:
Please also include an example that behaves unexpectedly.
@untitaker I provided one in the merge request... but I'll re-paste here as well.

Currently an option defined as...
```python
@click.option('--ambitious', '--all', '-a', is_flag=True)
```
...will target `all` instead of `ambitious`

I get an error `TypeError: batch() got an unexpected keyword argument 'all'`

Resolving patch:
diff --git a/click/core.py b/click/core.py
--- a/click/core.py
+++ b/click/core.py
@@ -1548,8 +1548,8 @@ def _parse_decls(self, decls, expose_value):
                     opts.append(decl)
 
         if name is None and possible_names:
-            possible_names.sort(key=lambda x: len(x[0]))
-            name = possible_names[-1][1].replace('-', '_').lower()
+            possible_names.sort(key=lambda x: -len(x[0]))  # group long options first
+            name = possible_names[0][1].replace('-', '_').lower()
             if not isidentifier(name):
                 name = None
 


Test patch:
diff --git a/tests/test_options.py b/tests/test_options.py
--- a/tests/test_options.py
+++ b/tests/test_options.py
@@ -335,3 +335,25 @@ def cli_alt(warnings):
     assert result.output == 'False\n'
     result = runner.invoke(cli_alt, ['-w'])
     assert result.output == 'True\n'
+
+@pytest.mark.parametrize('option_args,expected', [
+    (['--aggressive', '--all', '-a'], 'aggressive'),
+    (['--first', '--second', '--third', '-a', '-b', '-c'], 'first'),
+    (['--apple', '--banana', '--cantaloupe', '-a', '-b', '-c'], 'apple'),
+    (['--cantaloupe', '--banana', '--apple', '-c', '-b', '-a'], 'cantaloupe'),
+    (['-a', '-b', '-c'], 'a'),
+    (['-c', '-b', '-a'], 'c'),
+    (['-a', '--apple', '-b', '--banana', '-c', '--cantaloupe'], 'apple'),
+    (['-c', '-a', '--cantaloupe', '-b', '--banana', '--apple'], 'cantaloupe'),
+])
+def test_multiple_long_options(runner, option_args, expected):
+    @click.command()
+    @click.option(*option_args, is_flag=True)
+    def cmd(**kwargs):
+        click.echo(str(kwargs[expected]))
+
+    assert cmd.params[0].name == expected
+
+    for form in option_args:
+        result = runner.invoke(cmd, [form])
+        assert result.output == 'True\n'
Repository: pallets/click

Issue:
Support for bright colors
It would be nice to support bright ANSI colors as well. I have a use case where the bright color scheme, particularly for a standard Windows Command Prompt would be beneficial. I am happy to work on a Pull Request if this is something that you would consider adding. 


Discussion:

Resolving patch:
diff --git a/click/termui.py b/click/termui.py
--- a/click/termui.py
+++ b/click/termui.py
@@ -16,8 +16,25 @@
 # functions to customize how they work.
 visible_prompt_func = raw_input
 
-_ansi_colors = ('black', 'red', 'green', 'yellow', 'blue', 'magenta',
-                'cyan', 'white', 'reset')
+_ansi_colors = {
+    'black': 30,
+    'red': 31,
+    'green': 32,
+    'yellow': 33,
+    'blue': 34,
+    'magenta': 35,
+    'cyan': 36,
+    'white': 37,
+    'reset': 39,
+    'bright_black': 90,
+    'bright_red': 91,
+    'bright_green': 92,
+    'bright_yellow': 93,
+    'bright_blue': 94,
+    'bright_magenta': 95,
+    'bright_cyan': 96,
+    'bright_white': 97,
+}
 _ansi_reset_all = '\033[0m'
 
 
@@ -368,10 +385,21 @@ def style(text, fg=None, bg=None, bold=None, dim=None, underline=None,
     * ``magenta``
     * ``cyan``
     * ``white`` (might be light gray)
+    * ``bright_black``
+    * ``bright_red``
+    * ``bright_green``
+    * ``bright_yellow``
+    * ``bright_blue``
+    * ``bright_magenta``
+    * ``bright_cyan``
+    * ``bright_white``
     * ``reset`` (reset the color code only)
 
     .. versionadded:: 2.0
 
+    .. versionadded:: 7.0
+       Added support for bright colors.
+
     :param text: the string to style with ansi codes.
     :param fg: if provided this will become the foreground color.
     :param bg: if provided this will become the background color.
@@ -390,13 +418,13 @@ def style(text, fg=None, bg=None, bold=None, dim=None, underline=None,
     bits = []
     if fg:
         try:
-            bits.append('\033[%dm' % (_ansi_colors.index(fg) + 30))
-        except ValueError:
+            bits.append('\033[%dm' % (_ansi_colors[fg]))
+        except KeyError:
             raise TypeError('Unknown color %r' % fg)
     if bg:
         try:
-            bits.append('\033[%dm' % (_ansi_colors.index(bg) + 40))
-        except ValueError:
+            bits.append('\033[%dm' % (_ansi_colors[bg] + 10))
+        except KeyError:
             raise TypeError('Unknown color %r' % bg)
     if bold is not None:
         bits.append('\033[%dm' % (1 if bold else 22))
diff --git a/examples/colors/colors.py b/examples/colors/colors.py
--- a/examples/colors/colors.py
+++ b/examples/colors/colors.py
@@ -2,7 +2,9 @@
 
 
 all_colors = 'black', 'red', 'green', 'yellow', 'blue', 'magenta', \
-             'cyan', 'white'
+             'cyan', 'white', 'bright_black', 'bright_red', \
+             'bright_green', 'bright_yellow', 'bright_blue', \
+             'bright_magenta', 'bright_cyan', 'bright_white'
 
 
 @click.command()


Test patch:
Repository: pallets/click

Issue:
File('x') should default to stdout not stdin
Using click 6.7 + Python 3.6.0 :: Anaconda custom (64-bit)

If I create option with parameters `type=click.File('w') default='-'` Then the value defaults to `sys.stdout`. But when I create it with `type=click.File('x') default='-'` it defaults to `sys.stdin`. In my opinion it should default also to `sys.stdout` becase `x` file mode is also for writing (with exclusive file creation).

Run this script for proof:
```python
#!/usr/bin/env python3
import sys
import click


@click.command()
@click.option('--file', '-f', type=click.File('x'), default='-')
def cli(file):
    print('stdin:', file == sys.stdin)
    print('stdout:', file == sys.stdout)

if __name__ == '__main__':
    cli()
```
Output is:

```
$ ./test.py
stdin: True
stdout: False

```


Discussion:

Resolving patch:
diff --git a/click/_compat.py b/click/_compat.py
--- a/click/_compat.py
+++ b/click/_compat.py
@@ -423,7 +423,7 @@ def open_stream(filename, mode='r', encoding=None, errors='strict',
     # Standard streams first.  These are simple because they don't need
     # special handling for the atomic flag.  It's entirely ignored.
     if filename == '-':
-        if 'w' in mode:
+        if any(m in mode for m in ['w', 'a', 'x']):
             if 'b' in mode:
                 return get_binary_stdout(), False
             return get_text_stdout(encoding=encoding, errors=errors), False


Test patch:
Repository: pallets/click

Issue:
Can't build documentation with python 3
```
> make html
...
Exception occurred:
  File "/home/user/click-6.7/docs/clickdoctools.py", line 73, in isolation
    if isinstance(input, unicode):
NameError: name 'unicode' is not defined
```



Discussion:
if you build it with autodoc or sphinx - try to exclude all modules that can't be imported with `automock_import` in conf.py.


I'm sorry, I think I'm missing the exact syntax.

Hi @remort , sorry I don't get it. Would you please explain in more details? I also have the same issue building doc with Python 3.6.5. Thanks.

Resolving patch:
diff --git a/docs/clickdoctools.py b/docs/clickdoctools.py
--- a/docs/clickdoctools.py
+++ b/docs/clickdoctools.py
@@ -17,6 +17,13 @@
 from sphinx.domains import Domain
 from sphinx.util.compat import Directive
 
+PY2 = sys.version_info[0] == 2
+
+if PY2:
+    text_type = unicode
+else:
+    text_type = str
+    
 
 class EchoingStdin(object):
 
@@ -70,7 +77,7 @@ def dummy_call(*args, **kwargs):
 
 @contextlib.contextmanager
 def isolation(input=None, env=None):
-    if isinstance(input, unicode):
+    if isinstance(input, text_type):
         input = input.encode('utf-8')
     input = StringIO(input or '')
     output = StringIO()


Test patch:
Repository: pallets/click

Issue:
Google App Engine ImportError: No module named msvcrt
Because Click was added to [Flask 0.11](http://flask.pocoo.org/docs/0.11/) for the [New Command Line Interface](http://flask.pocoo.org/docs/0.11/cli/), and Click imports the Windows only module [msvcrt](https://docs.python.org/2/library/msvcrt.html), and the [Google App Engine local development server](https://cloud.google.com/appengine/docs/python/tools/using-local-server) doesn't contain this module, an import error is thrown.

![image](https://cloud.githubusercontent.com/assets/2013388/15935738/36ee00b6-2e1d-11e6-85a7-3b04de953659.png)

I've [created a workaround](https://github.com/gae-init/gae-init/pull/527) for the [gae-init project](https://github.com/gae-init/gae-init) (by modifying the App Engine config file), but it would be best to have a fix come directly from Flask/Click since there are likely many more people who will experience this issue when using Flask 0.11 with Google App Engine.



Discussion:
Flask Issue:
https://github.com/pallets/flask/issues/1901

Oh man. GAE keeps annoying me :( I will see if i can fix this.


Resolving patch:
diff --git a/click/_compat.py b/click/_compat.py
--- a/click/_compat.py
+++ b/click/_compat.py
@@ -7,8 +7,11 @@
 
 
 PY2 = sys.version_info[0] == 2
-WIN = sys.platform.startswith('win')
 CYGWIN = sys.platform.startswith('cygwin')
+# Determine local App Engine environment, per Google's own suggestion
+APP_ENGINE = ('APPENGINE_RUNTIME' in os.environ and
+              'Development/' in os.environ['SERVER_SOFTWARE'])
+WIN = sys.platform.startswith('win') and not APP_ENGINE
 DEFAULT_COLUMNS = 80
 
 


Test patch:
Repository: pallets/click

Issue:
Validate *args passed to `click.option`
See https://github.com/pallets/click/issues/568



Discussion:

Resolving patch:
diff --git a/click/core.py b/click/core.py
--- a/click/core.py
+++ b/click/core.py
@@ -1324,7 +1324,7 @@ def __init__(self, param_decls=None, type=None, required=False,
         self.is_eager = is_eager
         self.metavar = metavar
         self.envvar = envvar
-        self.autocompletion =  autocompletion
+        self.autocompletion = autocompletion
 
     @property
     def human_readable_name(self):
@@ -1355,7 +1355,6 @@ def get_default(self, ctx):
     def add_to_parser(self, parser, ctx):
         pass
 
-
     def consume_value(self, ctx, opts):
         value = opts.get(self.name)
         if value is None:
@@ -1805,11 +1804,9 @@ def _parse_decls(self, decls, expose_value):
         if len(decls) == 1:
             name = arg = decls[0]
             name = name.replace('-', '_').lower()
-        elif len(decls) == 2:
-            name, arg = decls
         else:
-            raise TypeError('Arguments take exactly one or two '
-                            'parameter declarations, got %d' % len(decls))
+            raise TypeError('Arguments take exactly one '
+                            'parameter declaration, got %d' % len(decls))
         return name, [arg], []
 
     def get_usage_pieces(self, ctx):


Test patch:
diff --git a/tests/test_arguments.py b/tests/test_arguments.py
--- a/tests/test_arguments.py
+++ b/tests/test_arguments.py
@@ -1,4 +1,5 @@
 # -*- coding: utf-8 -*-
+import pytest
 import click
 from click._compat import PY2
 
@@ -287,3 +288,11 @@ def cmd(a):
     result = runner.invoke(cmd, ['3'])
     assert result.exception is not None
     assert 'argument a takes 2 values' in result.output
+
+
+def test_multiple_param_decls_not_allowed(runner):
+    with pytest.raises(TypeError):
+        @click.command()
+        @click.argument('x', click.Choice(['a', 'b']))
+        def copy(x):
+            click.echo(x)
Repository: pallets/click

Issue:
LazyFile isn't lazy for mode 'r'
The documentation for the `File` type states:

> The lazy flag controls if the file should be opened immediately or upon first IO. The default is to be non lazy for standard input and output streams as well as files opened for reading, lazy otherwise.

However, this isn't true if the file-mode is `r`. There is an explicit check
https://github.com/pallets/click/blob/ef93b49174540e72c16ad194c39947974f3d5c29/click/utils.py#L89-L93
that tries to open and close the file in lazy mode. 

This prevents using a `lazy` `File` to access files that may only come into existence later.


Discussion:
Fairly sure this is intentional. Opening in write mode has side effects, so it can be made lazy to avoid that.
If that’s the case then fair enough but the documentation should then be clear that lazy is only “really” lazy for non ‘r’ modes.

Resolving patch:
diff --git a/click/types.py b/click/types.py
--- a/click/types.py
+++ b/click/types.py
@@ -331,9 +331,12 @@ class File(ParamType):
     opened in binary mode or for writing.  The encoding parameter can be used
     to force a specific encoding.
 
-    The `lazy` flag controls if the file should be opened immediately or
-    upon first IO.  The default is to be non lazy for standard input and
-    output streams as well as files opened for reading, lazy otherwise.
+    The `lazy` flag controls if the file should be opened immediately or upon
+    first IO. The default is to be non-lazy for standard input and output
+    streams as well as files opened for reading, `lazy` otherwise. When opening a
+    file lazily for reading, it is still opened temporarily for validation, but
+    will not be held open until first IO. lazy is mainly useful when opening
+    for writing to avoid creating the file until it is needed.
 
     Starting with Click 2.0, files can also be opened atomically in which
     case all writes go into a separate file in the same folder and upon


Test patch:
Repository: pallets/click

Issue:
Add ability to truncate help text in docstrings.
I use docstrings in all of my functions to document function arguments
so it makes me sad that I couldn't exclude :param: and other tags from
my command help texts.

Here I am introducing the ability for Click to truncate help text in
docstrings using the \f form feed escaped character. I chose it
randomly.

I've been accomplishing this in my project using this decorator:

``` python
def click_truncate(click_func, **kwargs):
    """Truncate function docstrings from Click's perspective on the form-feed character.

    :param function click_func: Either click.command or click.group.
    :param dict kwargs: Extra keyword arguments to pass to click.option().

    :return: The wrapped function.
    :rtype: function
    """
    def wrapper(func):
        original = func.__doc__
        if original:
            func.__doc__ = original.split('\f', 1)[0].rstrip()
        wrapped = click_func(**kwargs)(func)
        if original:
            wrapped.__doc__ = func.__doc__ = original
        return wrapped
    return wrapper
```



Discussion:

Resolving patch:
diff --git a/click/core.py b/click/core.py
--- a/click/core.py
+++ b/click/core.py
@@ -778,6 +778,10 @@ def __init__(self, name, context_settings=None, callback=None,
         #: should show up in the help page and execute.  Eager parameters
         #: will automatically be handled before non eager ones.
         self.params = params or []
+        # if a form feed (page break) is found in the help text, truncate help
+        # text to the content preceding the first form feed
+        if help and '\f' in help:
+            help = help.split('\f', 1)[0]
         self.help = help
         self.epilog = epilog
         self.options_metavar = options_metavar


Test patch:
diff --git a/tests/test_formatting.py b/tests/test_formatting.py
--- a/tests/test_formatting.py
+++ b/tests/test_formatting.py
@@ -268,3 +268,32 @@ def cmd(param):
         'Options:',
         '  --help  Show this message and exit.'
     ]
+
+
+def test_truncating_docstring(runner):
+    @click.command()
+    @click.pass_context
+    def cli(ctx):
+        """First paragraph.
+
+        This is a very long second
+        paragraph and not correctly
+        wrapped but it will be rewrapped.
+        \f
+
+        :param click.core.Context ctx: Click context.
+        """
+
+    result = runner.invoke(cli, ['--help'], terminal_width=60)
+    assert not result.exception
+    assert result.output.splitlines() == [
+        'Usage: cli [OPTIONS]',
+        '',
+        '  First paragraph.',
+        '',
+        '  This is a very long second paragraph and not correctly',
+        '  wrapped but it will be rewrapped.',
+        '',
+        'Options:',
+        '  --help  Show this message and exit.',
+    ]
Repository: pallets/click

Issue:
getchar() fails to raise KeyboardInterrupt on Python3
On Python3 (click6.6), getchar() will just pass on Ctrl+C instead of raising a KeyboardInterrupt. I would assume this is because `ch == '\x03:` should be `ch == b'\x03'` in `_termui_impl.py`.



Discussion:
@mbr What platform were you on mac/windows/linux?
I reproduced this on Linux. It may have been happening on Windows as well, but it looks like #1108 addresses that incidentally.

Resolving patch:
diff --git a/click/_termui_impl.py b/click/_termui_impl.py
--- a/click/_termui_impl.py
+++ b/click/_termui_impl.py
@@ -527,11 +527,11 @@ def _unquote_file(url):
 
 
 def _translate_ch_to_exc(ch):
-    if ch == '\x03':
+    if ch == u'\x03':
         raise KeyboardInterrupt()
-    if ch == '\x04' and not WIN:  # Unix-like, Ctrl+D
+    if ch == u'\x04' and not WIN:  # Unix-like, Ctrl+D
         raise EOFError()
-    if ch == '\x1a' and WIN:      # Windows, Ctrl+Z
+    if ch == u'\x1a' and WIN:      # Windows, Ctrl+Z
         raise EOFError()
 
 
@@ -612,7 +612,8 @@ def raw_terminal():
     def getchar(echo):
         with raw_terminal() as fd:
             ch = os.read(fd, 32)
+            ch = ch.decode(get_best_encoding(sys.stdin), 'replace')
             if echo and isatty(sys.stdout):
                 sys.stdout.write(ch)
             _translate_ch_to_exc(ch)
-            return ch.decode(get_best_encoding(sys.stdin), 'replace')
+            return ch


Test patch:
Repository: pallets/click

Issue:
Memory Leak in _winconsole
Result of call to `CommandLineToArgvW` should be released by `LocalFree`.
Should probably also check for failure of that function call (`NULL` is returned).



Discussion:
@mitsuhiko Any idea?


Resolving patch:
diff --git a/click/_winconsole.py b/click/_winconsole.py
--- a/click/_winconsole.py
+++ b/click/_winconsole.py
@@ -17,7 +17,8 @@
 import msvcrt
 from ._compat import _NonClosingTextIOWrapper, text_type, PY2
 from ctypes import byref, POINTER, c_int, c_char, c_char_p, \
-     c_void_p, py_object, c_ssize_t, c_ulong, windll, WINFUNCTYPE
+     c_void_p, py_object, c_ssize_t, c_ulong, windll, WINFUNCTYPE, \
+     WinError
 try:
     from ctypes import pythonapi
     PyObject_GetBuffer = pythonapi.PyObject_GetBuffer
@@ -40,6 +41,8 @@
 CommandLineToArgvW = WINFUNCTYPE(
     POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(
         ('CommandLineToArgvW', windll.shell32))
+LocalFree = WINFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p)(
+    ('LocalFree', windll.kernel32))
 
 
 STDIN_HANDLE = GetStdHandle(-10)
@@ -266,7 +269,13 @@ def _hash_py_argv():
     def _get_windows_argv():
         argc = c_int(0)
         argv_unicode = CommandLineToArgvW(GetCommandLineW(), byref(argc))
-        argv = [argv_unicode[i] for i in range(0, argc.value)]
+        if not argv_unicode:
+            raise WinError()
+        try:
+            argv = [argv_unicode[i] for i in range(0, argc.value)]
+        finally:
+            LocalFree(argv_unicode)
+            del argv_unicode
 
         if not hasattr(sys, 'frozen'):
             argv = argv[1:]


Test patch:
Repository: pallets/click

Issue:
click.edit doesn't support binary
I am using python 3.7.1 and click 7, and passing a bytes object to edit causes an exception on 
https://github.com/pallets/click/blob/b4d25f807e8a98f87bc60b76839e83302a5d9f3d/click/_termui_impl.py#L439

Where bytes.endswith() cannot accept a str as an argument.

From looking at the code we could add a "binary" flag to edit() or check to see if the object is bytes and skip all the encoding business and write bytes, then read and return bytes.


Discussion:

Resolving patch:
diff --git a/click/_termui_impl.py b/click/_termui_impl.py
--- a/click/_termui_impl.py
+++ b/click/_termui_impl.py
@@ -436,17 +436,20 @@ def edit(self, text):
         import tempfile
 
         text = text or ''
-        if text and not text.endswith('\n'):
+        binary_data = type(text) in [bytes, bytearray]
+
+        if not binary_data and text and not text.endswith('\n'):
             text += '\n'
 
         fd, name = tempfile.mkstemp(prefix='editor-', suffix=self.extension)
         try:
-            if WIN:
-                encoding = 'utf-8-sig'
-                text = text.replace('\n', '\r\n')
-            else:
-                encoding = 'utf-8'
-            text = text.encode(encoding)
+            if not binary_data:
+                if WIN:
+                    encoding = 'utf-8-sig'
+                    text = text.replace('\n', '\r\n')
+                else:
+                    encoding = 'utf-8'
+                text = text.encode(encoding)
 
             f = os.fdopen(fd, 'wb')
             f.write(text)
@@ -464,7 +467,10 @@ def edit(self, text):
                 rv = f.read()
             finally:
                 f.close()
-            return rv.decode('utf-8-sig').replace('\r\n', '\n')
+            if binary_data:
+                return rv
+            else:
+                return rv.decode('utf-8-sig').replace('\r\n', '\n')
         finally:
             os.unlink(name)
 


Test patch: