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

Issue:
Duplicate Boolean flag options "--foo/--foo" are not detected (defaults to False)
I ran into an issue where I had the code:

    @click.option( "--print-verbose-info/--print-verbose-info", help="...", default=False )

...and running `cli.py --print-verbose-info` was apparently defaulting over to the `False` value.  Totally my mistake (it should have been `--no-print-verbose-info`), but it'd be nice to get a warning/error for boolean values which match exactly (ie: cannot be set to true).

It was kindof tricky to diagnose b/c I assumed that the `--print-verbose-info` that I was passing on the CLI was triggering the `True` path, not the `False` path, and usually Click option parsing is pretty bulletproof so it took a while to find that copy/paste problem.

This would be a `good-first-issue`, I'm submitting it now more as a reminder to maybe follow-up on it and figure out the appropriate P.R.


Discussion:
untested, but probably something like this?

```
diff --git a/click/core.py b/click/core.py
index 36004fe..edddd9f 100644
--- a/click/core.py
+++ b/click/core.py
@@ -1731,6 +1731,8 @@ class Option(Parameter):
                     second = second.lstrip()
                     if second:
                         secondary_opts.append(second.lstrip())
+                    if first == second:
+                        raise TypeError('Boolean options cannot use the same flag for true and false.')
                 else:
                     possible_names.append(split_opt(decl))
                     opts.append(decl)
```
I will work on this

Resolving patch:
diff --git a/src/click/core.py b/src/click/core.py
--- a/src/click/core.py
+++ b/src/click/core.py
@@ -1840,6 +1840,11 @@ def _parse_decls(self, decls, expose_value):
                     second = second.lstrip()
                     if second:
                         secondary_opts.append(second.lstrip())
+                    if first == second:
+                        raise ValueError(
+                            f"Boolean option {decl!r} cannot use the"
+                            " same flag for true/false."
+                        )
                 else:
                     possible_names.append(split_opt(decl))
                     opts.append(decl)


Test patch:
diff --git a/tests/test_options.py b/tests/test_options.py
--- a/tests/test_options.py
+++ b/tests/test_options.py
@@ -565,3 +565,8 @@ def cmd(**kwargs):
         if form.startswith("-"):
             result = runner.invoke(cmd, [form])
             assert result.output == "True\n"
+
+
+def test_flag_duplicate_names(runner):
+    with pytest.raises(ValueError, match="cannot use the same flag for true/false"):
+        click.Option(["--foo/--foo"], default=False)
Repository: pallets/click

Issue:
Trailing blanks in envvars of boolean options cause otherwise valid values to be rejected
### Actual Behavior

When defining a boolean option that also can be set via envvar, trailing blanks in the envvar value cause otherwise valid values to be rejected with this error message:

```
Error: Invalid value for '--something': true  is not a valid boolean
```
Because the value is shown in the error message unquoted, the trailing blank cannot easily be seen, but it is there.

Why is this an issue?

Invoking the command on Linux/macOS as follows does not trigger the issue:
```
$ SOMETHING=true command 
```

However, invoking it like this on Windows does trigger the issue:
```
> set SOMETHING=true & command
```

Apparently, Windows sets the envvar with a trailing blank in this case.

The issue can be circumvented like this:
```
> set SOMETHING=true& command
```

Here is the code that causes this behavior:

click/types.py at line 406:
```
class BoolParamType(ParamType):
    name = "boolean"

    def convert(self, value, param, ctx):
        if isinstance(value, bool):
            return bool(value)
        value = value.lower()
        if value in ("true", "t", "1", "yes", "y"):
            return True
        elif value in ("false", "f", "0", "no", "n"):
            return False
        self.fail("{!r} is not a valid boolean".format(value), param, ctx)

    def __repr__(self):
        return "BOOL"
```
### Expected Behavior

I would like to see click strip any leading or trailing blanks from the boolean envvar before it is evaluated.

### Environment

* Python version: any
* Click version: 7.1.2



Discussion:

Resolving patch:
diff --git a/src/click/types.py b/src/click/types.py
--- a/src/click/types.py
+++ b/src/click/types.py
@@ -497,11 +497,15 @@ class BoolParamType(ParamType):
     def convert(self, value, param, ctx):
         if isinstance(value, bool):
             return bool(value)
-        value = value.lower()
-        if value in {"1", "true", "t", "yes", "y", "on"}:
+
+        norm = value.strip().lower()
+
+        if norm in {"1", "true", "t", "yes", "y", "on"}:
             return True
-        elif value in {"0", "false", "f", "no", "n", "off"}:
+
+        if norm in {"0", "false", "f", "no", "n", "off"}:
             return False
+
         self.fail(f"{value!r} is not a valid boolean value.", param, ctx)
 
     def __repr__(self):


Test patch:
diff --git a/tests/test_options.py b/tests/test_options.py
--- a/tests/test_options.py
+++ b/tests/test_options.py
@@ -164,6 +164,17 @@ def cmd(arg):
     assert result.output == "foo|bar\n"
 
 
+def test_trailing_blanks_boolean_envvar(runner):
+    @click.command()
+    @click.option("--shout/--no-shout", envvar="SHOUT")
+    def cli(shout):
+        click.echo(f"shout: {shout!r}")
+
+    result = runner.invoke(cli, [], env={"SHOUT": " true "})
+    assert result.exit_code == 0
+    assert result.output == "shout: True\n"
+
+
 def test_multiple_default_help(runner):
     @click.command()
     @click.option("--arg1", multiple=True, default=("foo", "bar"), show_default=True)
Repository: pallets/click

Issue:
Generated help with aliased group shows abbreviated command in usage
The typical AliasGroup class overrides the get_command method and returns a matching sub command; however, when help is displayed, the usage information shows the matched abbreviated subcommand instead of the full subcommand name. After debugging, I found that the context.info_name contains the the abbreviated sub command name. I think when a sub-command context is being created, it should use the full command name for this field rather than what the user typed.


Discussion:
I believe line 1280 in core.py should be:

        return cmd.name, cmd, args[1:]

instead of:

        return cmd_name, cmd, args[1:]


Resolving patch:
diff --git a/src/click/core.py b/src/click/core.py
--- a/src/click/core.py
+++ b/src/click/core.py
@@ -1346,7 +1346,7 @@ def resolve_command(self, ctx, args):
                 self.parse_args(ctx, ctx.args)
             ctx.fail(f"No such command '{original_cmd_name}'.")
 
-        return cmd_name, cmd, args[1:]
+        return cmd.name, cmd, args[1:]
 
     def get_command(self, ctx, cmd_name):
         """Given a context and a command name, this returns a


Test patch:
diff --git a/tests/test_commands.py b/tests/test_commands.py
--- a/tests/test_commands.py
+++ b/tests/test_commands.py
@@ -258,6 +258,22 @@ def sync():
     assert result.output == "no subcommand, use default\nin subcommand\n"
 
 
+def test_aliased_command_canonical_name(runner):
+    class AliasedGroup(click.Group):
+        def get_command(self, ctx, cmd_name):
+            return push
+
+    cli = AliasedGroup()
+
+    @cli.command()
+    def push():
+        click.echo("push command")
+
+    result = runner.invoke(cli, ["pu", "--help"])
+    assert not result.exception
+    assert result.output.startswith("Usage: root push [OPTIONS]")
+
+
 def test_unprocessed_options(runner):
     @click.command(context_settings=dict(ignore_unknown_options=True))
     @click.argument("args", nargs=-1, type=click.UNPROCESSED)
Repository: pallets/click

Issue:
BOOL should accept "on" and "off"
The `BOOL` parameter type should accept & convert the strings "on" and "off".  With this change, `BOOL` would support all of the boolean strings that `configparser` supports.


Discussion:

Resolving patch:
diff --git a/src/click/types.py b/src/click/types.py
--- a/src/click/types.py
+++ b/src/click/types.py
@@ -387,11 +387,11 @@ def convert(self, value, param, ctx):
         if isinstance(value, bool):
             return bool(value)
         value = value.lower()
-        if value in ("true", "t", "1", "yes", "y"):
+        if value in {"1", "true", "t", "yes", "y", "on"}:
             return True
-        elif value in ("false", "f", "0", "no", "n"):
+        elif value in {"0", "false", "f", "no", "n", "off"}:
             return False
-        self.fail(f"{value} is not a valid boolean", param, ctx)
+        self.fail(f"{value!r} is not a valid boolean value.", param, ctx)
 
     def __repr__(self):
         return "BOOL"


Test patch:
diff --git a/tests/test_basic.py b/tests/test_basic.py
--- a/tests/test_basic.py
+++ b/tests/test_basic.py
@@ -1,5 +1,8 @@
 import os
 import uuid
+from itertools import chain
+
+import pytest
 
 import click
 
@@ -198,27 +201,24 @@ def cli(flag):
         assert result.output == f"{default}\n"
 
 
-def test_boolean_conversion(runner):
-    for default in True, False:
-
-        @click.command()
-        @click.option("--flag", default=default, type=bool)
-        def cli(flag):
-            click.echo(flag)
-
-        for value in "true", "t", "1", "yes", "y":
-            result = runner.invoke(cli, ["--flag", value])
-            assert not result.exception
-            assert result.output == "True\n"
+@pytest.mark.parametrize(
+    ("value", "expect"),
+    chain(
+        ((x, "True") for x in ("1", "true", "t", "yes", "y", "on")),
+        ((x, "False") for x in ("0", "false", "f", "no", "n", "off")),
+    ),
+)
+def test_boolean_conversion(runner, value, expect):
+    @click.command()
+    @click.option("--flag", type=bool)
+    def cli(flag):
+        click.echo(flag, nl=False)
 
-        for value in "false", "f", "0", "no", "n":
-            result = runner.invoke(cli, ["--flag", value])
-            assert not result.exception
-            assert result.output == "False\n"
+    result = runner.invoke(cli, ["--flag", value])
+    assert result.output == expect
 
-        result = runner.invoke(cli, [])
-        assert not result.exception
-        assert result.output == f"{default}\n"
+    result = runner.invoke(cli, ["--flag", value.title()])
+    assert result.output == expect
 
 
 def test_file_option(runner):
Repository: pallets/click

Issue:
click.launch(wait=True) does not appear to work
### Expected Behavior

When calling `click.launch(wait=True)`, if I interpret the documentation correctly, `click.launch(wait=True)` should wait (block) for the user to close the launched program.

From https://click.palletsprojects.com/en/7.x/api/#click.launch:
> wait – waits for the program to stop.

In fact, whatever the value of `wait`, the behavior does not change.

What I'm trying to accomplish is to generate a temp file in my CLI app, let the user look at it using `click.launch`, then have the temp file deleted once the viewing program is closed.

```python
# test.py
# Assume exisiting ./test.txt file

import click
 
@click.command()
def main():
    print('Entering main.')
    click.launch('./test.txt', wait=True)
    print('Leaving main.')
 
if __name__ == '__main__':
     main()
```

```
> python test.py
> Entering main.
(file opens in program)
(user closes program)
> Leaving main.
```

### Actual Behavior
```
> python test.py
> Entering main.
> Leaving main.
(file opens in program)
```

### Environment

* Python version: 3.7.5 (default, Nov  7 2019, 10:50:52) 
* Click version: 7.1.2

Had a look in the source. I'm on linux, so xdg-open is being called, and that never blocks. click always returns `0` if `wait == False`, and the return code of xdg-open if `wait == True`.



Discussion:
There's nothing we can do for this. If xdg-open is non-blocking, then it sounds like the only thing wait can do is what it does: ignore the return if it's False, or get the return as soon as it's returned and pass that on if it's True.
Hmm, too bad, I was hoping there was a fix possible, if there was a blocking alternative to xdg-open.

One way would be to get the mimetype with `xdg-mime filetype /path/to/file`, then use` xdg-query default <mimetype>` to get the default application `.desktop` file name.

Find the file in XDG_DATA_DIRS (/applications subfolder). The `.desktop` file would then have to be parsed to find the command for the application, then launch a blocking subprocess with the application using the proper command.

But this is complicated, and I think it's probably not in click's scope.

Maybe a small change in the docs to clarify will do.

Resolving patch:
diff --git a/src/click/termui.py b/src/click/termui.py
--- a/src/click/termui.py
+++ b/src/click/termui.py
@@ -658,7 +658,9 @@ def launch(url, wait=False, locate=False):
     .. versionadded:: 2.0
 
     :param url: URL or filename of the thing to launch.
-    :param wait: waits for the program to stop.
+    :param wait: Wait for the program to exit before returning. This
+        only works if the launched program blocks. In particular,
+        ``xdg-open`` on Linux does not block.
     :param locate: if this is set to `True` then instead of launching the
                    application associated with the URL it will attempt to
                    launch a file manager with the file located.  This


Test patch:
Repository: pallets/click

Issue:
shell completion is case sensitive, even with click.Choice(case_sensitive=False)
### Expected Behavior

Since I set case_sensitive to False, I would expect shell completions to search without case sensitivity.

```python
import click
from click._bashcomplete import get_choices

options = ['Paul', 'Simon', 'Art', 'Garfunkel']

@click.command()
@click.option('--opt', type=click.Choice(options))
def demo():
    pass

completions = list(get_choices(demo, 'dummy', ['--opt'], 'gar'))
assert len(completions) == 1, "expected to find 'Garfunkel' as a completion item"
```

### Actual Behavior

No completions are found. However, if I change the `incomplete` parameter to `"Gar"`, one completion is found as expected.

### Environment

* Python version: 3.7.7
* Click version: 7.0 (but I've reviewed the code on master and it doesn't seem to have a fix)



Discussion:
Should be straightforward to fix, happy to review a PR.
I'll be happy to look into this!

Resolving patch:
diff --git a/src/click/types.py b/src/click/types.py
--- a/src/click/types.py
+++ b/src/click/types.py
@@ -274,7 +274,14 @@ def shell_complete(self, ctx, param, incomplete):
         from click.shell_completion import CompletionItem
 
         str_choices = map(str, self.choices)
-        return [CompletionItem(c) for c in str_choices if c.startswith(incomplete)]
+
+        if self.case_sensitive:
+            matched = (c for c in str_choices if c.startswith(incomplete))
+        else:
+            incomplete = incomplete.lower()
+            matched = (c for c in str_choices if c.lower().startswith(incomplete))
+
+        return [CompletionItem(c) for c in matched]
 
 
 class DateTime(ParamType):


Test patch:
diff --git a/tests/test_shell_completion.py b/tests/test_shell_completion.py
--- a/tests/test_shell_completion.py
+++ b/tests/test_shell_completion.py
@@ -304,3 +304,13 @@ def complete(ctx, param, incomplete):
         env={"COMP_WORDS": "", "COMP_CWORD": "0", "_CLI_COMPLETE": "bash_complete"},
     )
     assert result.output == "plain,a\nplain,b\n"
+
+
+@pytest.mark.parametrize(("value", "expect"), [(False, ["Au", "al"]), (True, ["al"])])
+def test_choice_case_sensitive(value, expect):
+    cli = Command(
+        "cli",
+        params=[Option(["-a"], type=Choice(["Au", "al", "Bc"], case_sensitive=value))],
+    )
+    completions = _get_words(cli, ["-a"], "a")
+    assert completions == expect
Repository: pallets/click

Issue:
Automatic short help should also take linebreak into account
PEP257 defines a summary line for [multi-line docstrings](https://www.python.org/dev/peps/pep-0257/#multi-line-docstrings) just like a [one-line docstring](https://www.python.org/dev/peps/pep-0257/#one-line-docstrings) to be a phrase ending in a period.

Click automatically uses everything up to the first period to be the short help, independent how many lines it spans.

Consider the following:
```
import click

@click.group()
def grp():
    pass

@grp.command()
def cmd1():
    """First sentence. Second sentence."""

@grp.command()
def cmd2():
    """Summary line without a period
   
    First real sentence. Another sentence.
    """
```
```
$ python3 foo.py  --help
Usage: foo.py [OPTIONS] COMMAND [ARGS]...

Options:
  --help  Show this message and exit.

Commands:
  cmd1  First sentence.
  cmd2  Summary line without a period First real...
```
To me it would feel more natural:
1. to take the first line as short help, independent of punctuation OR
1. to look for an ending of a phrase or linebreak, whichever comes first.

Both would allow for summary lines without the requirement to end in a period. While this would violate PEP257, I would consider it a gray area, as that summary line is used as short help in a list of commands and I have a use case where a company style guide requires such lists **not** to end in periods.

I'd be happy to provide a pull request for either solution, if it would be accepted.


Discussion:
I know this was from a while ago, but I think it's a good idea to stop at either a period or newline. If you guys think it's worth implementing can I code it as part of hacktoberfest?
No need to ask to work on an issue. As long as the issue is not assigned to anyone and doesn't have have a linked open PR (both can be seen in the sidebar), anyone is welcome to work on any issue.

Resolving patch:
diff --git a/src/click/utils.py b/src/click/utils.py
--- a/src/click/utils.py
+++ b/src/click/utils.py
@@ -49,6 +49,9 @@ def make_str(value):
 
 def make_default_short_help(help, max_length=45):
     """Return a condensed version of help string."""
+    line_ending = help.find("\n\n")
+    if line_ending != -1:
+        help = help[:line_ending]
     words = help.split()
     total_length = 0
     result = []


Test patch:
diff --git a/tests/test_basic.py b/tests/test_basic.py
--- a/tests/test_basic.py
+++ b/tests/test_basic.py
@@ -528,3 +528,22 @@ def nope():
     assert result.exit_code == 0
     assert "subgroup" not in result.output
     assert "nope" not in result.output
+
+
+def test_summary_line(runner):
+    @click.group()
+    def cli():
+        pass
+
+    @cli.command()
+    def cmd():
+        """
+        Summary line without period
+
+        Here is a sentence. And here too.
+        """
+        pass
+
+    result = runner.invoke(cli, ["--help"])
+    assert "Summary line without period" in result.output
+    assert "Here is a sentence." not in result.output
Repository: pallets/click

Issue:
Use of deprecated & insecure tempfile.mktemp()
### Expected Behavior

_tempfilepager() in _termui_impl.py uses a depreciated function that is considered insecure by the core [Python team](https://docs.python.org/3/library/tempfile.html#tempfile.mktemp). It is recommended to use mkstemp() instead. 

```python
import tempfile
filename = tempfile.mkstemp()  # Suggested replacement
```

### Actual Behavior

Python's warning: 

> Use of this function may introduce a security hole in your program. By the time you get around to doing anything with the file name it returns, someone else may have beaten you to the punch.

```python
import tempfile
filename = tempfile.mktemp()  # Depreciated and insecure
```

### Environment

* Python version: 3.8.5
* Click version: 7.1.2



Discussion:
Please see our guidelines for responsibly reporting security issues: https://github.com/pallets/click/security/policy

Resolving patch:
diff --git a/src/click/_termui_impl.py b/src/click/_termui_impl.py
--- a/src/click/_termui_impl.py
+++ b/src/click/_termui_impl.py
@@ -424,7 +424,7 @@ def _tempfilepager(generator, cmd, color):
     """Page through text by invoking a program on a temporary file."""
     import tempfile
 
-    filename = tempfile.mktemp()
+    filename = tempfile.mkstemp()
     # TODO: This never terminates if the passed generator never terminates.
     text = "".join(generator)
     if not color:


Test patch:
Repository: pallets/click

Issue:
Styled output support for JupyterLab
Not sure if this's a goal. But some issues mention support for Jupyter Notebook, and I'm not sure why it doesn't work in Jupyter Lab. It prints fine, but with no styling.

* Python 3.7.1
* Click 7.0
* Jupyter Lab 0.35.4


Discussion:
duplicate of #1186 
based on the comment in #1186 this one has to reopen as its a different kernel with a different io stream
I have successfully duplicated the issue on JupyterLab in Windows:
Input:

```python
import click

print(click.style('Hello World!', fg='green', bold=True, underline=True))
click.echo(click.style('Hello World!', fg='green', bold=True, underline=True))
click.echo(click.style('ATTENTION!', blink=True))
click.echo(click.style('Some things', reverse=True, fg='cyan'))
```
Output:

![image](https://user-images.githubusercontent.com/35740094/96667930-a712df80-1377-11eb-8047-fd678f2f627d.png)

So we don't have any styling whatsoever here, which is expected. 
Interestingly enough I found another inconsistency that's not just limited to JupyterLab, passing the same input into a test file gives us the following result.

![image](https://user-images.githubusercontent.com/35740094/96668043-e9d4b780-1377-11eb-8a3e-a278c25b0f88.png)

Using `print` leads to the expected style, with bold and underline, whereas using `click.echo` does not enable them.
This was pointed out in the following comment -> https://github.com/pallets/click/pull/1186#issuecomment-478637599
You'll have to be more specific about how you're writing to a file for me to say, but at least the `print` behavior is expected. `click.echo` checks the stream to see if it should strip the color codes, `print` does not. That's the whole issue, there's a special check to tell it that Jupyter kernel streams are ok, but it still doesn't detect JupyterLab streams.
Roger that! I'll get right on it, thanks for the clarification.

Resolving patch:
diff --git a/src/click/_compat.py b/src/click/_compat.py
--- a/src/click/_compat.py
+++ b/src/click/_compat.py
@@ -471,11 +471,6 @@ def strip_ansi(value):
 
 
 def _is_jupyter_kernel_output(stream):
-    if WIN:
-        # TODO: Couldn't test on Windows, should't try to support until
-        # someone tests the details wrt colorama.
-        return
-
     while isinstance(stream, (_FixupStream, _NonClosingTextIOWrapper)):
         stream = stream._stream
 
@@ -521,7 +516,7 @@ def auto_wrap_for_ansi(
 
         strip = should_strip_ansi(stream, color)
         ansi_wrapper = colorama.AnsiToWin32(stream, strip=strip)
-        rv = ansi_wrapper.stream
+        rv = t.cast(t.TextIO, ansi_wrapper.stream)
         _write = rv.write
 
         def _safe_write(s):


Test patch:
diff --git a/tests/test_compat.py b/tests/test_compat.py
--- a/tests/test_compat.py
+++ b/tests/test_compat.py
@@ -1,10 +1,6 @@
-import pytest
-
 from click._compat import should_strip_ansi
-from click._compat import WIN
 
 
-@pytest.mark.xfail(WIN, reason="Jupyter not tested/supported on Windows")
 def test_is_jupyter_kernel_output():
     class JupyterKernelFakeStream:
         pass