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

Issue:
command and group decorators are untyped on strict
Summary:
The `click.command` and `click.group` decorators are currently untyped and cause typing errors on strict pyright. (I haven't tested with mypy).

Replication:
- Install click
- Install pyright

```toml
# pyproject.toml

[tool.pyright]
typeCheckingMode = "strict"
```

```py
# main.py

import click

@click.command()
def cli_main() -> None:
    ...

@click.group()
def cli_group() -> None:
    ...
```

These decorators are both unknown due to the use of `typing.Callable` with no generics. PR incoming.

Environment:
- Python version: 3.10.4
- Click version: 8.1.2



Discussion:

Resolving patch:
diff --git a/src/click/decorators.py b/src/click/decorators.py
--- a/src/click/decorators.py
+++ b/src/click/decorators.py
@@ -149,7 +149,7 @@ def command(
 
 
 def command(
-    name: t.Union[str, t.Callable, None] = None,
+    name: t.Union[str, t.Callable[..., t.Any], None] = None,
     cls: t.Optional[t.Type[Command]] = None,
     **attrs: t.Any,
 ) -> t.Union[Command, t.Callable[..., Command]]:
@@ -182,7 +182,7 @@ def command(
         appended to the end of the list.
     """
 
-    func: t.Optional[t.Callable] = None
+    func: t.Optional[t.Callable[..., t.Any]] = None
 
     if callable(name):
         func = name
@@ -228,7 +228,7 @@ def decorator(f: t.Callable[..., t.Any]) -> Command:
 
 @t.overload
 def group(
-    __func: t.Callable,
+    __func: t.Callable[..., t.Any],
 ) -> Group:
     ...
 
@@ -242,7 +242,7 @@ def group(
 
 
 def group(
-    name: t.Union[str, t.Callable, None] = None, **attrs: t.Any
+    name: t.Union[str, t.Callable[..., t.Any], None] = None, **attrs: t.Any
 ) -> t.Union[Group, t.Callable[[F], Group]]:
     """Creates a new :class:`Group` with a function as callback.  This
     works otherwise the same as :func:`command` just that the `cls`


Test patch:
Repository: pallets/click

Issue:
Shell completion doesn't work on scripts with a dot in name
I found out, that a shell completion doesn't work on scripts with a dot in their name, mainly the scripts themselves (without an entry point linked) or entry points with a dot in their name (less common). The main problem is that the dot is copied into the name of the completion variable.

MWE:
Let's have a script `/tmp/example.py`
```python
import click


@click.command()
def main():
    pass


if __name__ == '__main__':
    main()
```

Completion on this script doesn't do anything using any of reasonable variable names:
```sh
_EXAMPLE_COMPLETE=bash_source python3 /tmp/example.py
_EXAMPLEPY_COMPLETE=bash_source python3 /tmp/example.py
_EXAMPLE_PY_COMPLETE=bash_source python3 /tmp/example.py
```

I found out, click requires the variable `_EXAMPLE.PY_COMPLETE` to be set, which is not possible (at least) in bash.

It would help if the dot was replaced by an underscore, the same way a dash is handled.

Environment:

- Python version: 3.9.9
- Click version: 8.0.3



Discussion:
Completion in general will not work with filenames (`./example.py`) or modules (`python -m example`), I don't believe that's something Click can control.

While I'd discorage anyone from making an entry point script with a dot in the name (`example.hello`), there shouldn't be anything technically wrong with that, so it makes sense to support that.

The solution might be to normalize dots the same way we normalize dashes, by replacing them with underscores.
I'll be working 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
@@ -1129,9 +1129,13 @@ def _main_shell_completion(
         :param complete_var: Name of the environment variable that holds
             the completion instruction. Defaults to
             ``_{PROG_NAME}_COMPLETE``.
+
+        .. versionchanged:: 8.2.0
+            Dots (``.``) in ``prog_name`` are replaced with underscores (``_``).
         """
         if complete_var is None:
-            complete_var = f"_{prog_name}_COMPLETE".replace("-", "_").upper()
+            complete_name = prog_name.replace("-", "_").replace(".", "_")
+            complete_var = f"_{complete_name}_COMPLETE".upper()
 
         instruction = os.environ.get(complete_var)
 


Test patch:
Repository: pallets/click

Issue:
Spurious empty lines in the help output (regression)
Click since version 8.1.0 doesn't properly account for a scenario that the callback's docstring can have no "help text" part, like so:

```python
@click.command()
def callback():
    """
    \f
    More stuff.
    """
```
This results in empty lines in the output:

```
% python3 test --help
Usage: test [OPTIONS]



Options:
  --help  Show this message and exit.
```

Before 8.1.0:
```
% python3 test --help
Usage: test [OPTIONS]

Options:
  --help  Show this message and exit.
```

Environment:

- Python version: 3.9.2
- Click version: 8.1.3



Discussion:

Resolving patch:
diff --git a/src/click/core.py b/src/click/core.py
--- a/src/click/core.py
+++ b/src/click/core.py
@@ -1360,13 +1360,16 @@ def format_help(self, ctx: Context, formatter: HelpFormatter) -> None:
 
     def format_help_text(self, ctx: Context, formatter: HelpFormatter) -> None:
         """Writes the help text to the formatter if it exists."""
-        text = self.help if self.help is not None else ""
+        if self.help is not None:
+            # truncate the help text to the first form feed
+            text = inspect.cleandoc(self.help).partition("\f")[0]
+        else:
+            text = ""
 
         if self.deprecated:
             text = _("(Deprecated) {text}").format(text=text)
 
         if text:
-            text = inspect.cleandoc(text).partition("\f")[0]
             formatter.write_paragraph()
 
             with formatter.indentation():


Test patch:
diff --git a/tests/test_commands.py b/tests/test_commands.py
--- a/tests/test_commands.py
+++ b/tests/test_commands.py
@@ -95,20 +95,6 @@ def long():
     )
 
 
-def test_help_truncation(runner):
-    @click.command()
-    def cli():
-        """This is a command with truncated help.
-        \f
-
-        This text should be truncated.
-        """
-
-    result = runner.invoke(cli, ["--help"])
-    assert result.exit_code == 0
-    assert "This is a command with truncated help." in result.output
-
-
 def test_no_args_is_help(runner):
     @click.command(no_args_is_help=True)
     def cli():
diff --git a/tests/test_formatting.py b/tests/test_formatting.py
--- a/tests/test_formatting.py
+++ b/tests/test_formatting.py
@@ -296,6 +296,26 @@ def cli(ctx):
     ]
 
 
+def test_truncating_docstring_no_help(runner):
+    @click.command()
+    @click.pass_context
+    def cli(ctx):
+        """
+        \f
+
+        This text should be truncated.
+        """
+
+    result = runner.invoke(cli, ["--help"], terminal_width=60)
+    assert not result.exception
+    assert result.output.splitlines() == [
+        "Usage: cli [OPTIONS]",
+        "",
+        "Options:",
+        "  --help  Show this message and exit.",
+    ]
+
+
 def test_removing_multiline_marker(runner):
     @click.group()
     def cli():
Repository: pallets/click

Issue:
Cannot use parameterless command decorator with custom command_class

Click throws an assertion error if you try to use the parameterless command decorator on a group with a command_class defined. The error is due to the command_class being added to kwargs before the assertion for no kwargs.


# minimal repro
```
import click

class CustomCommand(click.Command):
    pass

class CustomGroup(click.Group):
    command_class = CustomCommand

@click.group(cls=CustomGroup)
def grp():
    pass

@grp.command
def cli():
    click.echo("hello custom command class")
```
## error

```
ewilliamson@ip-192-168-50-39 ~ % python minimal_repro.py
Traceback (most recent call last):
  File "/Users/ewilliamson/minimal_repro.py", line 14, in <module>
    def cli():
  File "/Users/ewilliamson/.pyenv/versions/3.10.7/lib/python3.10/site-packages/click/core.py", line 1847, in command
    assert (
AssertionError: Use 'command(**kwargs)(callable)' to provide arguments.
```

## expected
The `@grp.command` would be successfully parsed the same as without using `CustomGroup`

<!--
Describe the expected behavior that should have happened but didn't.
-->

Environment:

- Python version: `Python 3.10.7`
- Click version: `click==8.1.3`



Discussion:

Resolving patch:
diff --git a/src/click/core.py b/src/click/core.py
--- a/src/click/core.py
+++ b/src/click/core.py
@@ -1871,9 +1871,6 @@ def command(
         """
         from .decorators import command
 
-        if self.command_class and kwargs.get("cls") is None:
-            kwargs["cls"] = self.command_class
-
         func: t.Optional[t.Callable[..., t.Any]] = None
 
         if args and callable(args[0]):
@@ -1883,6 +1880,9 @@ def command(
             (func,) = args
             args = ()
 
+        if self.command_class and kwargs.get("cls") is None:
+            kwargs["cls"] = self.command_class
+
         def decorator(f: t.Callable[..., t.Any]) -> Command:
             cmd: Command = command(*args, **kwargs)(f)
             self.add_command(cmd)


Test patch:
diff --git a/tests/test_command_decorators.py b/tests/test_command_decorators.py
--- a/tests/test_command_decorators.py
+++ b/tests/test_command_decorators.py
@@ -11,6 +11,26 @@ def cli():
     assert result.output == "hello\n"
 
 
+def test_custom_command_no_parens(runner):
+    class CustomCommand(click.Command):
+        pass
+
+    class CustomGroup(click.Group):
+        command_class = CustomCommand
+
+    @click.group(cls=CustomGroup)
+    def grp():
+        pass
+
+    @grp.command
+    def cli():
+        click.echo("hello custom command class")
+
+    result = runner.invoke(cli)
+    assert result.exception is None
+    assert result.output == "hello custom command class\n"
+
+
 def test_group_no_parens(runner):
     @click.group
     def grp():
Repository: pallets/click

Issue:
`expose_value=false` causes crash when auto-completing.
setting `expose_value=false` for an argument causes crash when auto-completing.

To replicate:

```python
# example.py
import click

@click.command
@click.argument('a', expose_value=False)
def main():
    pass

main()
```

```
$ _EXAMPLE_PY_COMPLETE=zsh_complete COMP_CWORD=1 COMP_WORDS="BUG " python example.py BUG
```

you should get something like the following
``` bash
  File "/home/amir/projects/click/bug", line 13, in <module>
    gogo()
  File "/home/amir/projects/click/src/click/core.py", line 1130, in __call__
    return self.main(*args, **kwargs)
  File "/home/amir/projects/click/src/click/core.py", line 1050, in main
    self._main_shell_completion(extra, prog_name, complete_var)
  File "/home/amir/projects/click/src/click/core.py", line 1125, in _main_shell_completion
    rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction)
  File "/home/amir/projects/click/src/click/shell_completion.py", line 49, in shell_complete
    echo(comp.complete())
  File "/home/amir/projects/click/src/click/shell_completion.py", line 291, in complete
    completions = self.get_completions(args, incomplete)
  File "/home/amir/projects/click/src/click/shell_completion.py", line 272, in get_completions
    obj, incomplete = _resolve_incomplete(ctx, args, incomplete)
  File "/home/amir/projects/click/src/click/shell_completion.py", line 575, in _resolve_incomplete
    if _is_incomplete_argument(ctx, param):
  File "/home/amir/projects/click/src/click/shell_completion.py", line 439, in _is_incomplete_argument
    value = ctx.params[param.name]
KeyError: 'a'
```

I think the correct behavior is that nothing should happen or some thing should be printed to stdout. but it shouldn't crash

Environment:

- Python version: 3.10
- Click version: main


Discussion:
Changing this [line](https://github.com/pallets/click/blob/c65c6ad18471448c0fcc59ef53088787288c02cc/src/click/shell_completion.py#L439) to `ctx.params.get(param.name)` prints out the helptext for the command instead of the error, maybe preferable to changing `expose_value`.

Resolving patch:
diff --git a/src/click/shell_completion.py b/src/click/shell_completion.py
--- a/src/click/shell_completion.py
+++ b/src/click/shell_completion.py
@@ -443,7 +443,8 @@ def _is_incomplete_argument(ctx: Context, param: Parameter) -> bool:
         return False
 
     assert param.name is not None
-    value = ctx.params[param.name]
+    # Will be None if expose_value is False.
+    value = ctx.params.get(param.name)
     return (
         param.nargs == -1
         or ctx.get_parameter_source(param.name) is not ParameterSource.COMMANDLINE


Test patch:
Repository: pallets/click

Issue:
Fish autocomplete stopped working on 8.1.4
Fish autocomplete stopped working in 8.1.4. By using git bisect I was able to identify fist commit that caused the issue - https://github.com/pallets/click/commit/bcd3faaaaf03933915394f6c24d4f06d22aa8a1d

I believe the issue was caused by removing line endings with ';'. Adding them back resolves issue for me.

When executing the `eval (env _FOO_BAR_COMPLETE=fish_source foo-bar)` I get `fish: Expected end of the statement, but found end of the input`

<!--
Describe how to replicate the bug.

Include a minimal reproducible example that demonstrates the bug.
Include the full traceback if there was an exception.
-->

<!--
Describe the expected behavior that should have happened but didn't.
-->

Environment:

- Python version: 3.11.4
- Click version: 8.1.4, 8.1.5
- Fish version: 3.6.1



Discussion:
Happy to review a PR. 
@exploide 

Resolving patch:
diff --git a/src/click/shell_completion.py b/src/click/shell_completion.py
--- a/src/click/shell_completion.py
+++ b/src/click/shell_completion.py
@@ -167,25 +167,25 @@ def __getattr__(self, name: str) -> t.Any:
 """
 
 _SOURCE_FISH = """\
-function %(complete_func)s
+function %(complete_func)s;
     set -l response (env %(complete_var)s=fish_complete COMP_WORDS=(commandline -cp) \
-COMP_CWORD=(commandline -t) %(prog_name)s)
+COMP_CWORD=(commandline -t) %(prog_name)s);
 
-    for completion in $response
-        set -l metadata (string split "," $completion)
+    for completion in $response;
+        set -l metadata (string split "," $completion);
 
-        if test $metadata[1] = "dir"
-            __fish_complete_directories $metadata[2]
-        else if test $metadata[1] = "file"
-            __fish_complete_path $metadata[2]
-        else if test $metadata[1] = "plain"
-            echo $metadata[2]
-        end
-    end
-end
+        if test $metadata[1] = "dir";
+            __fish_complete_directories $metadata[2];
+        else if test $metadata[1] = "file";
+            __fish_complete_path $metadata[2];
+        else if test $metadata[1] = "plain";
+            echo $metadata[2];
+        end;
+    end;
+end;
 
 complete --no-files --command %(prog_name)s --arguments \
-"(%(complete_func)s)"
+"(%(complete_func)s)";
 """
 
 


Test patch:
Repository: pallets/click

Issue:
deprecate `__version__`  attribute
The `__version__` attribute is an old pattern from early in Python packaging. Setuptools eventually made it easier to use the pattern by allowing reading the value from the attribute at build time, and some other build backends have done the same.

However, there's no reason to expose this directly in code anymore. It's usually easier to use feature detection (`hasattr`, `try/except`) instead. `importlib.metadata.version("click")` can be used to get the version at runtime in a standard way, if it's really needed.


Discussion:

Resolving patch:
diff --git a/src/click/__init__.py b/src/click/__init__.py
--- a/src/click/__init__.py
+++ b/src/click/__init__.py
@@ -69,8 +69,6 @@
 from .utils import get_text_stream as get_text_stream
 from .utils import open_file as open_file
 
-__version__ = "8.2.0.dev0"
-
 
 def __getattr__(name: str) -> object:
     import warnings
@@ -108,4 +106,17 @@ def __getattr__(name: str) -> object:
         )
         return _OptionParser
 
+    if name == "__version__":
+        import importlib.metadata
+        import warnings
+
+        warnings.warn(
+            "The '__version__' attribute is deprecated and will be removed in"
+            " Click 9.1. Use feature detection or"
+            " 'importlib.metadata.version(\"click\")' instead.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        return importlib.metadata.version("click")
+
     raise AttributeError(name)


Test patch:
Repository: pallets/click

Issue:
Docs wrongly links PRs and Issues to flask
![image](https://github.com/pallets/click/assets/13086194/cc68ea55-7c69-4e24-a2dd-f296d54a9c61)

Environment:

- Python version: N/A
- Click version: N/A

Docs wrongly links PRs and Issues to flask
![image](https://github.com/pallets/click/assets/13086194/cc68ea55-7c69-4e24-a2dd-f296d54a9c61)

Environment:

- Python version: N/A
- Click version: N/A



Discussion:

Resolving patch:
diff --git a/docs/conf.py b/docs/conf.py
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -23,8 +23,8 @@
 autodoc_typehints = "description"
 autodoc_preserve_defaults = True
 extlinks = {
-    "issue": ("https://github.com/pallets/flask/issues/%s", "#%s"),
-    "pr": ("https://github.com/pallets/flask/pull/%s", "#%s"),
+    "issue": ("https://github.com/pallets/click/issues/%s", "#%s"),
+    "pr": ("https://github.com/pallets/click/pull/%s", "#%s"),
 }
 intersphinx_mapping = {
     "python": ("https://docs.python.org/3/", None),


Test patch:
Repository: pallets/click

Issue:
The type hint for the filename parameter to open_file is incomplete
`click.open_file(filename, …)` happily accepts a `pathlib.Path` object as the filename; it [only passes the value along][open-file-src] to either `click.utils.LazyFile(filename, …)` or `click._compat.open_stream(filename, …)`, both of which accept pathlikes. However, `open_file`'s type hints indicate that `filename` can only be a string, which causes type-checking errors when feeding it a `Path`.

[open-file-src]: https://github.com/pallets/click/blob/874ca2bc1c30d93a4ac6e36a15ed685eafe89097/src/click/utils.py#L391-L401

``` python
from pathlib import Path

import click

filename = Path("/some/path")

# Mypy gives the following error on the line with the call to open_file:
#
# error: Argument 1 to "open_file" has incompatible type "Path"; expected "str"  [arg-type]

with click.open_file(filename) as handle:
    pass
```

Both `LazyFile` and `open_stream` give their filename parameter the type `types.Union[str, os.PathLike[str]]`, so that should probably be the type accepted by `open_file`, too.

Environment:

- Python version: 3.12.1
- Click version: 8.1.7



Discussion:

Resolving patch:
diff --git a/src/click/utils.py b/src/click/utils.py
--- a/src/click/utils.py
+++ b/src/click/utils.py
@@ -353,7 +353,7 @@ def get_text_stream(
 
 
 def open_file(
-    filename: str,
+    filename: t.Union[str, "os.PathLike[str]"],
     mode: str = "r",
     encoding: t.Optional[str] = None,
     errors: t.Optional[str] = "strict",
@@ -374,7 +374,7 @@ def open_file(
         with open_file(filename) as f:
             ...
 
-    :param filename: The name of the file to open, or ``'-'`` for
+    :param filename: The name or Path of the file to open, or ``'-'`` for
         ``stdin``/``stdout``.
     :param mode: The mode in which to open the file.
     :param encoding: The encoding to decode or encode a file opened in


Test patch:
Repository: pallets/click

Issue:
Broken message about invalid argument value for template "File ... is a directory"
**User Actions**
```sh
mkdir $'my\ndir'
my-tool $'my\ndir'
```

**Expected Output**
```
Invalid value for 'PATH': File 'my\ndir' is a directory.
```


**Actual Output**
```
Invalid value for 'PATH': File 'my
dir' is a directory.
```


**Code**
```python
from pathlib import Path
from typing import Annotated

import typer


def main(path: Annotated[Path, typer.Argument(dir_okay=False)]) -> None:
    pass


if __name__ == '__main__':
    typer.run(main)
```

**Cause**
You clearly forgot `!r` on [this](https://github.com/pallets/click/blob/f8857cb03268b5b952b88b2acb3e11d9f0f7b6e4/src/click/types.py#L896) line and are using quotes instead.

Just compare these lines in [click.types](https://github.com/pallets/click/blob/f8857cb03268b5b952b88b2acb3e11d9f0f7b6e4/src/click/types.py#L870-L928):
```python
_("{name} {filename!r} does not exist.").format(
_("{name} {filename!r} is a file.").format(
_("{name} '{filename}' is a directory.").format(
_("{name} {filename!r} is not readable.").format(
_("{name} {filename!r} is not writable.").format(
_("{name} {filename!r} is not executable.").format(
```



Discussion:
I'm going to work on this at the PyCon 2024 sprints.

Resolving patch:
diff --git a/src/click/types.py b/src/click/types.py
--- a/src/click/types.py
+++ b/src/click/types.py
@@ -892,7 +892,7 @@ def convert(
                 )
             if not self.dir_okay and stat.S_ISDIR(st.st_mode):
                 self.fail(
-                    _("{name} '{filename}' is a directory.").format(
+                    _("{name} {filename!r} is a directory.").format(
                         name=self.name.title(), filename=format_filename(value)
                     ),
                     param,


Test patch:
diff --git a/tests/test_types.py b/tests/test_types.py
--- a/tests/test_types.py
+++ b/tests/test_types.py
@@ -1,5 +1,6 @@
 import os.path
 import pathlib
+import platform
 import tempfile
 
 import pytest
@@ -232,3 +233,14 @@ def test_file_surrogates(type, tmp_path):
 def test_file_error_surrogates():
     message = FileError(filename="\udcff").format_message()
     assert message == "Could not open file '�': unknown error"
+
+
+@pytest.mark.skipif(
+    platform.system() == "Windows", reason="Filepath syntax differences."
+)
+def test_invalid_path_with_esc_sequence():
+    with pytest.raises(click.BadParameter) as exc_info:
+        with tempfile.TemporaryDirectory(prefix="my\ndir") as tempdir:
+            click.Path(dir_okay=False).convert(tempdir, None, None)
+
+    assert "my\\ndir" in exc_info.value.message
Repository: dotkom/onlineweb4

Issue:
Adding 'Offline Informasjonstekster' causes error
Not really sure what this does but it casts an error saying:

Exception Type:     IntegrityError
Exception Value:    column key is not unique



Discussion:
@xolan can you take a look at this? Decide how critical this ticket is.

@lizter @OptimusCrime : How do I recreate this error?  Everything seems to be in order on my end.


Resolving patch:
diff --git a/apps/offline/admin.py b/apps/offline/admin.py
--- a/apps/offline/admin.py
+++ b/apps/offline/admin.py
@@ -8,6 +8,9 @@ class ProxyChunkAdmin(admin.ModelAdmin):
 
     readonly_fields = ['key']
 
+    def has_add_permission(self, request):
+        return False
+
     def queryset(self, request):
         offline = Chunk.objects.filter(Q(key='offline_ingress') | Q(key='offline_brodtekst'))
         return offline


Test patch:
Repository: dotkom/onlineweb4

Issue:
Bootstrap3, fiks modals on frontpage
Related to #149.

The modals are not working. Probably new syntax in BS3.



Discussion:

Resolving patch:
diff --git a/onlineweb4/settings/base.py b/onlineweb4/settings/base.py
--- a/onlineweb4/settings/base.py
+++ b/onlineweb4/settings/base.py
@@ -188,7 +188,7 @@
 }
 
 # crispy forms settings
-CRISPY_TEMPLATE_PACK = 'bootstrap'
+CRISPY_TEMPLATE_PACK = 'bootstrap3'
 
 # bootstrap messages classes
 MESSAGE_TAGS = {messages.DEBUG: 'alert-debug',


Test patch: