ronantakizawa/codereview-bench huggingface dataset:
Repository: pallets/click
File: src/click/_unicodefun.py (Python)

Code before:
                "This system lists some UTF-8 supporting locales that"
                " you can pick from. The following suitable locales"
                " were discovered: {locales}"
            ).format(locales=", ".join(sorted(good_locales)))

        bad_locale = None
        for locale in os.environ.get("LC_ALL"), os.environ.get("LANG"):
            if locale and locale.lower().endswith((".utf-8", ".utf8")):
                bad_locale = locale
            if locale is not None:
                break
        if bad_locale is not None:
            extra += _(
                "\n\nClick discovered that you exported a UTF-8 locale"
                " but the locale system could not pick up from it"
                " because it does not exist. The exported locale is"
                " {locale!r} but it is not supported"
            ).format(local=bad_locale)

    message = _(
        "Click will abort further execution because Python was"
        " configured to use ASCII as encoding for the environment."
        " Consult https://click.palletsprojects.com/unicode-support/"
        " for mitigation steps."
    )
    raise RuntimeError(f"{message}{extra}")


Review comment (suggestion):
```suggestion
    raise RuntimeError(message+extra)
```

seems a bit pointless to use an f-string to concatenate two string variables..

Code after:
            extra.append(
                _(
                    "This system supports the C.UTF-8 locale which is"
                    " recommended. You might be able to resolve your"
                    " issue by exporting the following environment"
                    " variables:"
                )
            )
            extra.append("    export LC_ALL=C.UTF-8\n    export LANG=C.UTF-8")
        else:
            extra.append(
                _(
                    "This system lists some UTF-8 supporting locales"
                    " that you can pick from. The following suitable"
                    " locales were discovered: {locales}"
                ).format(locales=", ".join(sorted(good_locales)))
            )

        bad_locale = None
        for locale in os.environ.get("LC_ALL"), os.environ.get("LANG"):
            if locale and locale.lower().endswith((".utf-8", ".utf8")):
                bad_locale = locale
            if locale is not None:
                break
        if bad_locale is not None:
            extra.append(
                _(
                    "Click discovered that you exported a UTF-8 locale"
                    " but the locale system could not pick up from it"
                    " because it does not exist. The exported locale is"
                    " {locale!r} but it is not supported."
                ).format(locale=bad_locale)
            )

    raise RuntimeError("\n\n".join(extra))
Repository: pallets/click
File: tests/test_basic.py (Python)

Code before:

    cli = click.Group(commands=[sub])
    result = runner.invoke(cli, ["sub"])
    assert result.output == "sub"


@pytest.mark.parametrize(
    ("values", "expect"),
    [
        ("--foo=no value", "FOO:[no value]"),
        ("--foo=42", "FOO:[42]"),
        ("--foo", "Option '--foo' requires an argument."),
        ("--foo=", "FOO:[]"),
        ("--foo=\N{SNOWMAN}", "FOO:[\N{SNOWMAN}]"),
    ],
)
def test_basic_option(runner, values, expect):
    @click.command()
    @click.option("--foo", default="no value")
    def cli(foo):
        click.echo(f"FOO:[{foo}]")

    result = runner.invoke(cli, [values])

    assert result.exception is None
    assert result.return_value == expect


@pytest.mark.parametrize(
    ("values", "expect"),
    [
        ("--foo=42", "FOO:[84]"),
        ("--foo=23", "FOO:[46]"),
        ("--foo=bar", "Invalid value for '--foo': 'bar' is not a valid integer."),
    ],
)
def test_int_option(runner, values, expect):
    @click.command()
    @click.option("--foo", default="no value")
    def cli(foo):
        click.echo(f"FOO:[{foo * 2}]")

    result = runner.invoke(cli, [values])

    assert result.exception is None
    assert result.return_value == expect


def test_uuid_option(runner):
    @click.command()
    @click.option(

Review comment (suggestion):
`return_value` is only set when running in `standalone_mode=False`, you can test `result.output` in this case.

Code after:
    cli = click.Group(commands=[sub])
    result = runner.invoke(cli, ["sub"])
    assert result.output == "sub"


@pytest.mark.parametrize(
    ("args", "expect"),
    [
        ([], "S:[no value]"),
        (["--s=42"], "S:[42]"),
        (["--s"], "Error: Option '--s' requires an argument."),
        (["--s="], "S:[]"),
        (["--s=\N{SNOWMAN}"], "S:[\N{SNOWMAN}]"),
    ],
)
def test_string_option(runner, args, expect):
    @click.command()
    @click.option("--s", default="no value")
    def cli(s):
        click.echo(f"S:[{s}]")

    result = runner.invoke(cli, args)
    assert expect in result.output

    if expect.startswith("Error:"):
        assert result.exception is not None
    else:
        assert result.exception is None


@pytest.mark.parametrize(
    ("args", "expect"),
    [
        ([], "I:[84]"),
        (["--i=23"], "I:[46]"),
        (["--i=x"], "Error: Invalid value for '--i': 'x' is not a valid integer."),
    ],
)
def test_int_option(runner, args, expect):
    @click.command()
    @click.option("--i", default=42)
    def cli(i):
        click.echo(f"I:[{i * 2}]")

    result = runner.invoke(cli, args)
    assert expect in result.output

    if expect.startswith("Error:"):
        assert result.exception is not None
    else:
        assert result.exception is None
Repository: pallets/click
File: src/click/decorators.py (Python)

Code before:

    if help is None:
        help = inspect.getdoc(f)
    else:
        help = inspect.cleandoc(help)

    attrs["help"] = help
    return cls(
        name=name or f.__name__.lower().replace("_", "-"),
        callback=f,
        params=params,
        **attrs,
    )


@t.overload
def command(
    name: t.Optional[str] = None,
    cls: t.Optional[t.Type[Command]] = None,
    **attrs: t.Any,
) -> t.Callable[[F], Command]:
    ...


@t.overload
def command(  # noqa: F811
    name: t.Callable,
    cls: t.Optional[t.Type[Command]] = None,
    **attrs: t.Any,
) -> Command:
    ...


def command(  # noqa: F811
    name: t.Union[str, t.Callable, None] = None,
    cls: t.Optional[t.Type[Command]] = None,
    **attrs: t.Any,
) -> t.Union[Command, t.Callable[[F], Command]]:
    r"""Creates a new :class:`Command` and uses the decorated function as
    callback.  This will also automatically attach all decorated
    :func:`option`\s and :func:`argument`\s as parameters to the command.

    The name of the command defaults to the name of the function with
    underscores replaced by dashes.  If you want to change that, you can
    pass the intended name as the first argument.

    All keyword arguments are forwarded to the underlying command class.

    Once decorated the function turns into a :class:`Command` instance
    that can be invoked as a command line utility or be attached to a
    command :class:`Group`.

Review comment (suggestion):
I'm surprised the `noqa: F811` is needed - https://github.com/PyCQA/pyflakes/pull/435 looks like flake8 should be able to detect `@overload` usage and not trigger this error..

Code after:

    if help is None:
        help = inspect.getdoc(f)
    else:
        help = inspect.cleandoc(help)

    attrs["help"] = help
    return cls(
        name=name or f.__name__.lower().replace("_", "-"),
        callback=f,
        params=params,
        **attrs,
    )


@t.overload
def command(
    name: t.Optional[str] = None,
    cls: t.Optional[t.Type[Command]] = None,
    **attrs: t.Any,
) -> t.Callable[[F], Command]:
    ...


@t.overload
def command(
    name: t.Callable,
    cls: t.Optional[t.Type[Command]] = None,
    **attrs: t.Any,
) -> Command:
    ...


def command(
    name: t.Union[str, t.Callable, None] = None,
    cls: t.Optional[t.Type[Command]] = None,
    **attrs: t.Any,
) -> t.Union[Command, t.Callable[[F], Command]]:
    r"""Creates a new :class:`Command` and uses the decorated function as
    callback.  This will also automatically attach all decorated
    :func:`option`\s and :func:`argument`\s as parameters to the command.

    The name of the command defaults to the name of the function with
    underscores replaced by dashes.  If you want to change that, you can
    pass the intended name as the first argument.

    All keyword arguments are forwarded to the underlying command class.

    Once decorated the function turns into a :class:`Command` instance
    that can be invoked as a command line utility or be attached to a
    command :class:`Group`.
Repository: pallets/click
File: src/click/decorators.py (Python)

Code before:
        raise TypeError("Attempted to convert a callback into a command twice.")

    try:
        params = f.__click_params__  # type: ignore
        params.reverse()
        del f.__click_params__  # type: ignore
    except AttributeError:
        params = []

    help = attrs.get("help")

    if help is None:
        help = inspect.getdoc(f)
    else:
        help = inspect.cleandoc(help)

    attrs["help"] = help
    return cls(
        name=name or f.__name__.lower().replace("_", "-"),
        callback=f,
        params=params,
        **attrs,
    )


@t.overload
def command(
    name: t.Optional[str] = None,
    cls: t.Optional[t.Type[Command]] = None,
    **attrs: t.Any,
) -> t.Callable[[F], Command]:
    ...


@t.overload
def command(  # noqa: F811
    name: t.Callable,
    cls: t.Optional[t.Type[Command]] = None,
    **attrs: t.Any,
) -> Command:
    ...


def command(  # noqa: F811
    name: t.Union[str, t.Callable, None] = None,
    cls: t.Optional[t.Type[Command]] = None,
    **attrs: t.Any,
) -> t.Union[Command, t.Callable[[F], Command]]:
    r"""Creates a new :class:`Command` and uses the decorated function as
    callback.  This will also automatically attach all decorated
    :func:`option`\s and :func:`argument`\s as parameters to the command.

Review comment (suggestion):
Add `import typing` and use `@typing.overload` for this specific case, I've been doing the same elsewhere around the pallets code.

Code after:
        raise TypeError("Attempted to convert a callback into a command twice.")

    try:
        params = f.__click_params__  # type: ignore
        params.reverse()
        del f.__click_params__  # type: ignore
    except AttributeError:
        params = []

    help = attrs.get("help")

    if help is None:
        help = inspect.getdoc(f)
    else:
        help = inspect.cleandoc(help)

    attrs["help"] = help
    return cls(
        name=name or f.__name__.lower().replace("_", "-"),
        callback=f,
        params=params,
        **attrs,
    )


@t.overload
def command(
    name: t.Optional[str] = None,
    cls: t.Optional[t.Type[Command]] = None,
    **attrs: t.Any,
) -> t.Callable[[F], Command]:
    ...


@t.overload
def command(
    name: t.Callable,
    cls: t.Optional[t.Type[Command]] = None,
    **attrs: t.Any,
) -> Command:
    ...


def command(
    name: t.Union[str, t.Callable, None] = None,
    cls: t.Optional[t.Type[Command]] = None,
    **attrs: t.Any,
) -> t.Union[Command, t.Callable[[F], Command]]:
    r"""Creates a new :class:`Command` and uses the decorated function as
    callback.  This will also automatically attach all decorated
    :func:`option`\s and :func:`argument`\s as parameters to the command.
Repository: pallets/click
File: tests/test_types.py (Python)

Code before:
        "cli",
        params=[click.Argument(["p"], type=click.Path(path_type=cls))],
        callback=lambda p: p,
    )
    result = runner.invoke(cli, ["a/b/c.txt"], standalone_mode=False)
    assert result.exception is None
    assert result.return_value == expect


@pytest.mark.skipif(not check_symlink_impl(), reason="symlink not allowed on device")
@pytest.mark.parametrize(
    ("sym_file", "abs_fun"),
    [
        (("relative_symlink",), os.path.basename),
        (("test", "absolute_symlink"), lambda x: x),
    ],
)
def test_symlink_resolution(tmpdir, sym_file, abs_fun):
    tempdir = str(tmpdir)
    real_path = os.path.join(tempdir, "test_file")
    sym_path = os.path.join(tempdir, *sym_file)

    # create dirs and files
    os.makedirs(os.path.join(tempdir, "test"), exist_ok=True)
    with open(real_path, "w"):
        pass
    os.symlink(abs_fun(real_path), sym_path)

    # test
    ctx = click.Context(click.Command("do_stuff"))
    rv = click.Path(resolve_path=True).convert(sym_path, None, ctx)
    assert rv == real_path


Review comment (suggestion):
This can be simplified as,

```python
    os.makedirs(os.path.join(tempdir, "test"), exist_ok=True)
    open(real_path, "w")
```

The `with` makes a context manager, and then closes it immediately.

Reference,

- [Python File Write](https://www.w3schools.com/python/python_file_write.asp)

Code after:
        "cli",
        params=[click.Argument(["p"], type=click.Path(path_type=cls))],
        callback=lambda p: p,
    )
    result = runner.invoke(cli, ["a/b/c.txt"], standalone_mode=False)
    assert result.exception is None
    assert result.return_value == expect


@pytest.mark.skipif(not check_symlink_impl(), reason="symlink not allowed on device")
@pytest.mark.parametrize(
    ("sym_file", "abs_fun"),
    [
        (("relative_symlink",), os.path.basename),
        (("test", "absolute_symlink"), lambda x: x),
    ],
)
def test_symlink_resolution(tmpdir, sym_file, abs_fun):
    """This test ensures symlinks are properly resolved by click"""
    tempdir = str(tmpdir)
    real_path = os.path.join(tempdir, "test_file")
    sym_path = os.path.join(tempdir, *sym_file)

    # create dirs and files
    os.makedirs(os.path.join(tempdir, "test"), exist_ok=True)
    open(real_path, "w").close()
    os.symlink(abs_fun(real_path), sym_path)

    # test
    ctx = click.Context(click.Command("do_stuff"))
    rv = click.Path(resolve_path=True).convert(sym_path, None, ctx)
    assert rv == real_path
Repository: pallets/click
File: src/click/decorators.py (Python)

Code before:
    """

    def decorator(f: F) -> F:
        def new_func(*args, **kwargs):  # type: ignore
            ctx = get_current_context()
            obj = ctx.meta[key]
            return ctx.invoke(f, obj, *args, **kwargs)

        return update_wrapper(t.cast(F, new_func), f)

    if doc_description is None:
        doc_description = f"the {key!r} key from :attr:`click.Context.meta`"

    decorator.__doc__ = (
        f"Decorator that passes {doc_description} as the first argument"
        " to the decorated function."
    )
    return decorator


CmdType = t.TypeVar("CmdType", bound=Command)


@t.overload
def command(
    __name: t.Callable[..., t.Any],
) -> Command:
    ...


@t.overload
def command(
    name: t.Optional[str] = None,
    **attrs: t.Any,
) -> t.Callable[..., Command]:
    ...


@t.overload
def command(
    name: t.Optional[str] = None,
    cls: t.Type[CmdType] = ...,
    **attrs: t.Any,
) -> t.Callable[..., CmdType]:
    ...


def command(
    name: t.Union[str, t.Callable, None] = None,
    cls: t.Optional[t.Type[Command]] = None,
    **attrs: t.Any,

Review comment (suggestion):
```suggestion
    __func: t.Callable[..., t.Any],
```
To be consistent with changes in `core.py`.

Code after:
    """

    def decorator(f: F) -> F:
        def new_func(*args, **kwargs):  # type: ignore
            ctx = get_current_context()
            obj = ctx.meta[key]
            return ctx.invoke(f, obj, *args, **kwargs)

        return update_wrapper(t.cast(F, new_func), f)

    if doc_description is None:
        doc_description = f"the {key!r} key from :attr:`click.Context.meta`"

    decorator.__doc__ = (
        f"Decorator that passes {doc_description} as the first argument"
        " to the decorated function."
    )
    return decorator


CmdType = t.TypeVar("CmdType", bound=Command)


@t.overload
def command(
    __func: t.Callable[..., t.Any],
) -> Command:
    ...


@t.overload
def command(
    name: t.Optional[str] = None,
    **attrs: t.Any,
) -> t.Callable[..., Command]:
    ...


@t.overload
def command(
    name: t.Optional[str] = None,
    cls: t.Type[CmdType] = ...,
    **attrs: t.Any,
) -> t.Callable[..., CmdType]:
    ...


def command(
    name: t.Union[str, t.Callable, None] = None,
    cls: t.Optional[t.Type[Command]] = None,
    **attrs: t.Any,
Repository: pallets/click
File: tests/test_termui.py (Python)

Code before:
        ("Confirm Password", "password\npassword\n", None, "password"),
        (True, "", "", ""),
        (False, None, None, None),
    ],
)
def test_confirmation_prompt(runner, prompt, input, default, expect):
    @click.command()
    @click.option(
        "--password",
        prompt=prompt,
        hide_input=True,
        default=default,
        confirmation_prompt=prompt,
    )
    def cli(password):
        return password

    result = runner.invoke(cli, input=input, standalone_mode=False)
    assert result.exception is None
    assert result.return_value == expect

    if prompt == "Confirm Password":
        assert "Confirm Password: " in result.output


def test_show_default_false_hides_prompt(runner):
    @click.command()
    @click.option("--arg1", show_default=False, prompt=True, default="my-default-value")
    def cmd(arg1):
        pass

    result = runner.invoke(cmd, input="my-input", standalone_mode=False)
    assert "my-default-value" not in result.output


Review comment (suggestion):
This test name can be clearer in order to explain what does this test check.

Mybe something like "test_false_show_default_cause_no_default_display_in_prompt".

Code after:
        (True, "password\npassword", None, "password"),
        ("Confirm Password", "password\npassword\n", None, "password"),
        (True, "", "", ""),
        (False, None, None, None),
    ],
)
def test_confirmation_prompt(runner, prompt, input, default, expect):
    @click.command()
    @click.option(
        "--password",
        prompt=prompt,
        hide_input=True,
        default=default,
        confirmation_prompt=prompt,
    )
    def cli(password):
        return password

    result = runner.invoke(cli, input=input, standalone_mode=False)
    assert result.exception is None
    assert result.return_value == expect

    if prompt == "Confirm Password":
        assert "Confirm Password: " in result.output


def test_false_show_default_cause_no_default_display_in_prompt(runner):
    @click.command()
    @click.option("--arg1", show_default=False, prompt=True, default="my-default-value")
    def cmd(arg1):
        pass

    # Confirm that the default value is not included in the output when `show_default`
    # is False
    result = runner.invoke(cmd, input="my-input", standalone_mode=False)
    assert "my-default-value" not in result.output
Repository: pallets/click
File: tests/test_testing.py (Python)

Code before:

def test_isolated_runner(runner):
    with runner.isolated_filesystem() as d:
        assert os.path.exists(d)

    assert not os.path.exists(d)


def test_isolated_runner_custom_tempdir(runner, tmp_path):
    with runner.isolated_filesystem(temp_dir=tmp_path) as d:
        assert os.path.exists(d)

    assert os.path.exists(d)
    os.rmdir(d)


def test_isolation_stderr_errors():
    """Writing to stderr should escape invalid characters instead of
    raising a UnicodeEncodeError.
    """
    runner = CliRunner()

    with runner.isolation() as (_, err, _):
        click.echo("\udce2", err=True, nl=False)

        assert err.getvalue() == b"\\udce2"


def test_isolation_flushes_unflushed_stderr():
    """An un-flushed write to stderr, as with `print(..., file=sys.stderr)`, will end up
    flushed by the runner at end of invocation.
    """
    runner = CliRunner()

    with runner.isolation() as (_, err, _):
        click.echo("\udce2", err=True, nl=False)

        assert err.getvalue() == b"\\udce2"

    @click.command()
    def cli():
        # set end="", flush=False so that it's totally clear that we won't get any
        # auto-flush behaviors
        print("gyarados gyarados gyarados", file=sys.stderr, end="", flush=False)

    result = runner.invoke(cli)
    assert result.stderr == "gyarados gyarados gyarados"


Review comment (suggestion):
With my patch, stream objects yielded from `runner.isolation`, including `err`, may be closed as the context manager exits, dereferencing (hence, allowing gc to collect) its internal `StreamMixer` reference. Comparable tests already do it this way, so I'm hoping that this change is acceptable.

Code after:

def test_isolated_runner(runner):
    with runner.isolated_filesystem() as d:
        assert os.path.exists(d)

    assert not os.path.exists(d)


def test_isolated_runner_custom_tempdir(runner, tmp_path):
    with runner.isolated_filesystem(temp_dir=tmp_path) as d:
        assert os.path.exists(d)

    assert os.path.exists(d)
    os.rmdir(d)


def test_isolation_stderr_errors():
    """Writing to stderr should escape invalid characters instead of
    raising a UnicodeEncodeError.
    """
    runner = CliRunner()

    with runner.isolation() as (_, err, _):
        click.echo("\udce2", err=True, nl=False)
        assert err.getvalue() == b"\\udce2"


def test_isolation_flushes_unflushed_stderr():
    """An un-flushed write to stderr, as with `print(..., file=sys.stderr)`, will end up
    flushed by the runner at end of invocation.
    """
    runner = CliRunner()

    with runner.isolation() as (_, err, _):
        click.echo("\udce2", err=True, nl=False)
        assert err.getvalue() == b"\\udce2"

    @click.command()
    def cli():
        # set end="", flush=False so that it's totally clear that we won't get any
        # auto-flush behaviors
        print("gyarados gyarados gyarados", file=sys.stderr, end="", flush=False)

    result = runner.invoke(cli)
    assert result.stderr == "gyarados gyarados gyarados"