nebius/SWE-rebench-V2-PRs huggingface dataset:
Repository: googleapis/gapic-generator-go
Pull request #32 (2018-10-12 01:23:43)

sample: properly fail on error


Patch:
diff --git a/cmd/gen-go-sample/main.go b/cmd/gen-go-sample/main.go
index 8ea1f1a..8a8e0e4 100644
--- a/cmd/gen-go-sample/main.go
+++ b/cmd/gen-go-sample/main.go
@@ -343,12 +343,16 @@ func (g *generator) genSample(ifaceName, methName, regTag string, valSet SampleV
 	}
 
 	p("  flag.Parse()")
-	p("  sample%s(%s)", methName, flagArgs(argNames))
+	p("  if err := sample%s(%s); err != nil {", methName, flagArgs(argNames))
+	p("    log.Fatal(err)")
+	p("  }")
 	p("}")
 	p("")
 
 	g.imports[inSpec] = true
 	g.imports[pbinfo.ImportSpec{Path: "flag"}] = true
+	g.imports[pbinfo.ImportSpec{Path: "fmt"}] = true
+	g.imports[pbinfo.ImportSpec{Path: "log"}] = true
 	return nil
 }
 


Test patch:
diff --git a/cmd/gen-go-sample/testdata/sample.want b/cmd/gen-go-sample/testdata/sample.want
index dd57572..fec677e 100644
--- a/cmd/gen-go-sample/testdata/sample.want
+++ b/cmd/gen-go-sample/testdata/sample.want
@@ -19,6 +19,7 @@ import(
  "context"
  "flag"
  "fmt"
+ "log"
 
 foo "path.to/client/foo"
 foopb "path.to/pb/foo"
@@ -65,6 +66,8 @@ func main() {
 	arg0 := flag.Int64("arg0", 42, "")
 	arg1 := flag.String("arg1", "foobar", "")
 	flag.Parse()
-	sampleMyMethod(*arg0, *arg1)
+	if err := sampleMyMethod(*arg0, *arg1); err != nil {
+		log.Fatal(err)
+	}
 }
Repository: googleapis/gapic-generator-go
Pull request #33 (2018-10-12 21:22:49)

sample: accept argument name from config


Patch:
diff --git a/cmd/gen-go-sample/gapic.go b/cmd/gen-go-sample/gapic.go
index 9fb9397..9ad2457 100644
--- a/cmd/gen-go-sample/gapic.go
+++ b/cmd/gen-go-sample/gapic.go
@@ -43,8 +43,8 @@ type SampleParameter struct {
 }
 
 type SampleAttribute struct {
-	Parameter      string
-	SampleArgument bool `yaml:"sample_argument"`
+	Parameter          string
+	SampleArgumentName string `yaml:"sample_argument_name"`
 }
 
 type GAPICSample struct {
diff --git a/cmd/gen-go-sample/main.go b/cmd/gen-go-sample/main.go
index 83a149c..7b2150d 100644
--- a/cmd/gen-go-sample/main.go
+++ b/cmd/gen-go-sample/main.go
@@ -234,11 +234,11 @@ func (g *generator) genSample(ifaceName, methName, regTag string, valSet SampleV
 			return errors.E(err, "can't set default value: %q", def)
 		}
 	}
-	for i, attr := range valSet.Parameters.Attributes {
-		if !attr.SampleArgument {
+	for _, attr := range valSet.Parameters.Attributes {
+		if attr.SampleArgumentName == "" {
 			continue
 		}
-		name := fmt.Sprintf("arg%d", i)
+		name := snakeToCamel(attr.SampleArgumentName)
 		subTree, err := itree.parseSampleArgPath(attr.Parameter, g.descInfo, name)
 		if err != nil {
 			return errors.E(err, "can't set sample function argument: %q", attr.Parameter)


Test patch:
diff --git a/cmd/gen-go-sample/main_test.go b/cmd/gen-go-sample/main_test.go
index b462f99..14110df 100644
--- a/cmd/gen-go-sample/main_test.go
+++ b/cmd/gen-go-sample/main_test.go
@@ -107,8 +107,8 @@ func TestSample(t *testing.T) {
 				`f = "in a oneof"`,
 			},
 			Attributes: []SampleAttribute{
-				{"a.x", true},
-				{"b", true},
+				{"a.x", "the_x"},
+				{"b", "the_b"},
 			},
 		},
 		OnSuccess: []OutputSpec{
diff --git a/cmd/gen-go-sample/testdata/sample.want b/cmd/gen-go-sample/testdata/sample.want
index fec677e..bf6f9d4 100644
--- a/cmd/gen-go-sample/testdata/sample.want
+++ b/cmd/gen-go-sample/testdata/sample.want
@@ -26,21 +26,21 @@ foopb "path.to/pb/foo"
 )
 // [START awesome_region]
 
-func sampleMyMethod(arg0 int64, arg1 string) error {
+func sampleMyMethod(theX int64, theB string) error {
 	ctx := context.Background()
 	c, err := foo.NewClient(ctx)
 	if err != nil {
 		return err
 	}
 
-// arg0 := 42
-// arg1 := "foobar"
+// theX := 42
+// theB := "foobar"
 req := &foopb.InputType{
 	A: &foopb.AType{
-		X: arg0,
+		X: theX,
 		Y: 3.14159,
 	},
-	B: arg1,
+	B: theB,
 	E: foopb.AType_FOO,
 	Group: &foopb.InputType_F{
 		F: "in a oneof",
@@ -63,10 +63,10 @@ req := &foopb.InputType{
 // [END awesome_region]
 
 func main() {
-	arg0 := flag.Int64("arg0", 42, "")
-	arg1 := flag.String("arg1", "foobar", "")
+	theX := flag.Int64("theX", 42, "")
+	theB := flag.String("theB", "foobar", "")
 	flag.Parse()
-	if err := sampleMyMethod(*arg0, *arg1); err != nil {
+	if err := sampleMyMethod(*theX, *theB); err != nil {
 		log.Fatal(err)
 	}
 }
Repository: googleapis/gapic-generator-go
Pull request #77 (2019-01-09 18:29:55)

gapic: change autogen notice header
Per [standardized autogen notice comment](https://github.com/golang/go/issues/13560#issuecomment-288457920)


Patch:
diff --git a/internal/license/license.go b/internal/license/license.go
index 99fd8bc..0fa0d25 100644
--- a/internal/license/license.go
+++ b/internal/license/license.go
@@ -28,6 +28,6 @@ const Apache = `// Copyright %d Google LLC
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-// AUTO-GENERATED CODE. DO NOT EDIT.
+// Code generated by protoc-gen-go_gapic. DO NOT EDIT.
 
 `


Test patch:
diff --git a/cmd/gen-go-sample/testdata/sample_empty.want b/cmd/gen-go-sample/testdata/sample_empty.want
index ece887b..3a9260f 100644
--- a/cmd/gen-go-sample/testdata/sample_empty.want
+++ b/cmd/gen-go-sample/testdata/sample_empty.want
@@ -12,7 +12,7 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-// AUTO-GENERATED CODE. DO NOT EDIT.
+// Code generated by protoc-gen-go_gapic. DO NOT EDIT.
 
 package main
 import(
diff --git a/cmd/gen-go-sample/testdata/sample_paging.want b/cmd/gen-go-sample/testdata/sample_paging.want
index c7a22c2..d3e5b67 100644
--- a/cmd/gen-go-sample/testdata/sample_paging.want
+++ b/cmd/gen-go-sample/testdata/sample_paging.want
@@ -12,7 +12,7 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-// AUTO-GENERATED CODE. DO NOT EDIT.
+// Code generated by protoc-gen-go_gapic. DO NOT EDIT.
 
 package main
 import(
diff --git a/cmd/gen-go-sample/testdata/sample_unary.want b/cmd/gen-go-sample/testdata/sample_unary.want
index 441550d..796ab6a 100644
--- a/cmd/gen-go-sample/testdata/sample_unary.want
+++ b/cmd/gen-go-sample/testdata/sample_unary.want
@@ -12,7 +12,7 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-// AUTO-GENERATED CODE. DO NOT EDIT.
+// Code generated by protoc-gen-go_gapic. DO NOT EDIT.
 
 package main
 import(
diff --git a/internal/gengapic/testdata/doc_file.want b/internal/gengapic/testdata/doc_file.want
index 84eb845..45f67e2 100644
--- a/internal/gengapic/testdata/doc_file.want
+++ b/internal/gengapic/testdata/doc_file.want
@@ -12,7 +12,7 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-// AUTO-GENERATED CODE. DO NOT EDIT.
+// Code generated by protoc-gen-go_gapic. DO NOT EDIT.
 
 // Package awesome is an auto-generated package for the
 // Awesome Foo API.
Repository: clap-rs/clap
Pull request #5692 (2024-08-21 20:07:11)

fix(complete): Allow completing '.'
<!--
Thanks for helping out!

Please link the appropriate issue from your PR.

If you don't have an issue, we'd recommend starting with one first so the PR can focus on the
implementation (unless its an obvious bug or documentation fix that will have
little conversation).
-->



Patch:
diff --git a/clap_complete/src/engine/custom.rs b/clap_complete/src/engine/custom.rs
index 10c15f38..51da696f 100644
--- a/clap_complete/src/engine/custom.rs
+++ b/clap_complete/src/engine/custom.rs
@@ -259,6 +259,10 @@ pub(crate) fn complete_path(
     };
     debug!("complete_path: search_root={search_root:?}, prefix={prefix:?}");
 
+    if value_os.is_empty() && is_wanted(&search_root) {
+        completions.push(".".into());
+    }
+
     for entry in std::fs::read_dir(&search_root)
         .ok()
         .into_iter()


Test patch:
diff --git a/clap_complete/tests/testsuite/engine.rs b/clap_complete/tests/testsuite/engine.rs
index 56410a22..a4211183 100644
--- a/clap_complete/tests/testsuite/engine.rs
+++ b/clap_complete/tests/testsuite/engine.rs
@@ -616,6 +616,41 @@ d_dir/
     );
 }
 
+#[test]
+fn suggest_value_path_dir() {
+    let testdir = snapbox::dir::DirRoot::mutable_temp().unwrap();
+    let testdir_path = testdir.path().unwrap();
+    fs::write(testdir_path.join("a_file"), "").unwrap();
+    fs::write(testdir_path.join("b_file"), "").unwrap();
+    fs::create_dir_all(testdir_path.join("c_dir")).unwrap();
+    fs::create_dir_all(testdir_path.join("d_dir")).unwrap();
+
+    let mut cmd = Command::new("dynamic")
+        .arg(
+            clap::Arg::new("input")
+                .long("input")
+                .short('i')
+                .add(ArgValueCompleter::new(
+                    PathCompleter::dir().current_dir(testdir_path.to_owned()),
+                )),
+        )
+        .args_conflicts_with_subcommands(true);
+
+    assert_data_eq!(
+        complete!(cmd, "--input [TAB]", current_dir = Some(testdir_path)),
+        snapbox::str![[r#"
+.
+c_dir/
+d_dir/
+"#]],
+    );
+
+    assert_data_eq!(
+        complete!(cmd, "--input c[TAB]", current_dir = Some(testdir_path)),
+        snapbox::str!["c_dir/"],
+    );
+}
+
 #[test]
 fn suggest_custom_arg_value() {
     fn custom_completer() -> Vec<CompletionCandidate> {
Repository: clap-rs/clap
Pull request #5735 (2024-09-18 13:24:55)

chore: add the missing symbol
<!--
Thanks for helping out!

Please link the appropriate issue from your PR.

If you don't have an issue, we'd recommend starting with one first so the PR can focus on the
implementation (unless its an obvious bug or documentation fix that will have
little conversation).
-->



Patch:
diff --git a/clap_derive/src/derives/args.rs b/clap_derive/src/derives/args.rs
index d6fecc01..04928db2 100644
--- a/clap_derive/src/derives/args.rs
+++ b/clap_derive/src/derives/args.rs
@@ -230,7 +230,7 @@ pub(crate) fn gen_augment(
                 let next_display_order = item.next_display_order();
                 let flatten_group_assert = if matches!(**ty, Ty::Option) {
                     quote_spanned! { kind.span()=>
-                        <#inner_type as clap::Args>::group_id().expect("cannot `#[flatten]` an `Option<Args>` with `#[group(skip)]");
+                        <#inner_type as clap::Args>::group_id().expect("cannot `#[flatten]` an `Option<Args>` with `#[group(skip)]`");
                     }
                 } else {
                     quote! {}


Test patch:
diff --git a/tests/derive/flatten.rs b/tests/derive/flatten.rs
index 95ad43e2..6a1414e6 100644
--- a/tests/derive/flatten.rs
+++ b/tests/derive/flatten.rs
@@ -257,7 +257,7 @@ fn docstrings_ordering_with_multiple_clap_partial() {
 }
 
 #[test]
-#[should_panic = "cannot `#[flatten]` an `Option<Args>` with `#[group(skip)]"]
+#[should_panic = "cannot `#[flatten]` an `Option<Args>` with `#[group(skip)]`"]
 fn flatten_skipped_group() {
     #[derive(clap::Parser, Debug)]
     struct Cli {
Repository: clap-rs/clap
Pull request #5836 (2024-12-03 17:57:17)

fix(assert): Prevent arguments from requiring self
It's non-sensical for an argument to require itself, so it must be a mistake, and should be prevented.

This is arguably a breaking change, but of the spacebar heating kind.

Let me know if I should add any tests for this.

epage: > Let me know if I should add any tests for this.

Please do.

Generally, we recommend PRs be structured as
- A test commit **where the tests pass**, showing the existing behavior
- A behavior change that updates the test so to continues to pass

This
- Makes the behavior change obvious to the reviewer and outsiders
- Helps verify the test

In this case, its going to be a little more obvious, so we might be able to let it slide (in my ideal world, I'd even break out that argument unpacking into its own refactor commit).
omertuc: Makes sense, will do that

Patch:
diff --git a/clap_builder/src/builder/debug_asserts.rs b/clap_builder/src/builder/debug_asserts.rs
index 9e6154ab..001ef8a1 100644
--- a/clap_builder/src/builder/debug_asserts.rs
+++ b/clap_builder/src/builder/debug_asserts.rs
@@ -139,12 +139,18 @@ pub(crate) fn assert_app(cmd: &Command) {
         }
 
         // requires, r_if, r_unless
-        for req in &arg.requires {
+        for (_predicate, req_id) in &arg.requires {
             assert!(
-                cmd.id_exists(&req.1),
+                &arg.id != req_id,
+                "Argument {} cannot require itself",
+                arg.get_id()
+            );
+
+            assert!(
+                cmd.id_exists(req_id),
                 "Command {}: Argument or group '{}' specified in 'requires*' for '{}' does not exist",
                 cmd.get_name(),
-                req.1,
+                req_id,
                 arg.get_id(),
             );
         }


Test patch:
diff --git a/tests/builder/require.rs b/tests/builder/require.rs
index ea0f09f5..14592ad0 100644
--- a/tests/builder/require.rs
+++ b/tests/builder/require.rs
@@ -1478,3 +1478,11 @@ For more information, try '--help'.
 ";
     utils::assert_output(cmd, "test --require-first --second", EXPECTED, true);
 }
+
+#[test]
+#[should_panic = "Argument flag cannot require itself"]
+fn requires_self() {
+    let _result = Command::new("flag_required")
+        .arg(arg!(-f --flag "some flag").requires("flag"))
+        .try_get_matches_from(vec![""]);
+}
Repository: clap-rs/clap
Pull request #5838 (2024-12-05 15:14:58)

fix(lex): allow `E` in scientific notation
This PR allows an `E` in scientific notation. Currently only `e` is allowed.



Patch:
diff --git a/clap_lex/src/lib.rs b/clap_lex/src/lib.rs
index c0ba47e3..4ff58710 100644
--- a/clap_lex/src/lib.rs
+++ b/clap_lex/src/lib.rs
@@ -505,9 +505,9 @@ fn is_number(arg: &str) -> bool {
             // optional exponent, and only if it's not the first character.
             b'.' if !seen_dot && position_of_e.is_none() && i > 0 => seen_dot = true,
 
-            // Allow an exponent `e` but only at most one after the first
+            // Allow an exponent `e`/`E` but only at most one after the first
             // character.
-            b'e' if position_of_e.is_none() && i > 0 => position_of_e = Some(i),
+            b'e' | b'E' if position_of_e.is_none() && i > 0 => position_of_e = Some(i),
 
             _ => return false,
         }


Test patch:
diff --git a/clap_lex/tests/testsuite/parsed.rs b/clap_lex/tests/testsuite/parsed.rs
index 4ee944cb..6bc42ca2 100644
--- a/clap_lex/tests/testsuite/parsed.rs
+++ b/clap_lex/tests/testsuite/parsed.rs
@@ -120,7 +120,7 @@ fn to_short() {
 
 #[test]
 fn is_negative_number() {
-    for number in ["-10.0", "-1", "-100", "-3.5", "-1e10", "-1.3e10"] {
+    for number in ["-10.0", "-1", "-100", "-3.5", "-1e10", "-1.3e10", "-1E10"] {
         let raw = clap_lex::RawArgs::new(["bin", number]);
         let mut cursor = raw.cursor();
         assert_eq!(raw.next_os(&mut cursor), Some(OsStr::new("bin")));
@@ -142,7 +142,9 @@ fn is_positive_number() {
 
 #[test]
 fn is_not_number() {
-    for number in ["--10.0", "-..", "-2..", "-e", "-1e", "-1e10.2", "-.2"] {
+    for number in [
+        "--10.0", "-..", "-2..", "-e", "-1e", "-1e10.2", "-.2", "-E", "-1E", "-1E10.2",
+    ] {
         let raw = clap_lex::RawArgs::new(["bin", number]);
         let mut cursor = raw.cursor();
         assert_eq!(raw.next_os(&mut cursor), Some(OsStr::new("bin")));
Repository: clap-rs/clap
Pull request #5846 (2024-12-16 06:03:57)

fix(complete): remove duplicate bash subcmd cases caused by aliases
Visible alias completions were causing duplicate case conditions when offering subcommand completions, due to the fact that they share the same function name as the command they are aliasing. This commit deduplicates them so as to not redefine the exact same case statement logic.

<!--
Thanks for helping out!

Please link the appropriate issue from your PR.

If you don't have an issue, we'd recommend starting with one first so the PR can focus on the
implementation (unless its an obvious bug or documentation fix that will have
little conversation).
-->



Patch:
diff --git a/clap_complete/src/aot/shells/bash.rs b/clap_complete/src/aot/shells/bash.rs
index d2834019..6d0be2d2 100644
--- a/clap_complete/src/aot/shells/bash.rs
+++ b/clap_complete/src/aot/shells/bash.rs
@@ -132,6 +132,7 @@ fn subcommand_details(cmd: &Command) -> String {
         .collect::<Vec<_>>();
 
     scs.sort();
+    scs.dedup();
 
     subcmd_dets.extend(scs.iter().map(|sc| {
         format!(


Test patch:
diff --git a/clap_complete/tests/snapshots/sub_subcommands.bash b/clap_complete/tests/snapshots/sub_subcommands.bash
index a6a46635..6651d025 100644
--- a/clap_complete/tests/snapshots/sub_subcommands.bash
+++ b/clap_complete/tests/snapshots/sub_subcommands.bash
@@ -152,20 +152,6 @@ _my-app() {
             COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
             return 0
             ;;
-        my__app__some_cmd)
-            opts="-h -V --help --version sub_cmd help"
-            if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then
-                COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
-                return 0
-            fi
-            case "${prev}" in
-                *)
-                    COMPREPLY=()
-                    ;;
-            esac
-            COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
-            return 0
-            ;;
         my__app__some_cmd__help)
             opts="sub_cmd help"
             if [[ ${cur} == -* || ${COMP_CWORD} -eq 3 ]] ; then
Repository: clap-rs/clap
Pull request #5941 (2025-03-08 05:08:19)

feat(builder): Add `clap::Error::remove` and a test
#5935

The added test covers both `Error::insert` and `Error::remove`.

If we merge this after #5942, I could make the new test use the same `assert_error` as the other ones (though I'm not sure that would be better, up to you). I could also make `assert_error` take `&Error`, but that changes a lot of call sites.



Patch:
diff --git a/clap_builder/src/error/mod.rs b/clap_builder/src/error/mod.rs
index eb59ec26..5e2cc466 100644
--- a/clap_builder/src/error/mod.rs
+++ b/clap_builder/src/error/mod.rs
@@ -203,6 +203,16 @@ impl<F: ErrorFormatter> Error<F> {
         self.inner.context.insert(kind, value)
     }
 
+    /// Remove a piece of context, return the old value if any
+    ///
+    /// The context is currently implemented in a vector, so `remove` takes
+    /// linear time.
+    #[inline(never)]
+    #[cfg(feature = "error-context")]
+    pub fn remove(&mut self, kind: ContextKind) -> Option<ContextValue> {
+        self.inner.context.remove(&kind)
+    }
+
     /// Should the message be written to `stdout` or not?
     #[inline]
     pub fn use_stderr(&self) -> bool {


Test patch:
diff --git a/tests/builder/error.rs b/tests/builder/error.rs
index 5af6ea5e..1de60f7b 100644
--- a/tests/builder/error.rs
+++ b/tests/builder/error.rs
@@ -203,6 +203,51 @@ For more information, try '--help'.
     assert_error(err, expected_kind, message, true);
 }
 
+#[test]
+#[cfg(feature = "error-context")]
+fn edit_error() {
+    use clap::error::{ContextKind, ContextValue};
+    use snapbox::assert_data_eq;
+
+    let cmd = Command::new("rg").arg(arg!([PATTERN]));
+
+    let res = cmd.try_get_matches_from(["rg", "--foo"]);
+    assert!(res.is_err());
+    let mut err = res.unwrap_err();
+
+    let orig_message = str![[r#"
+error: unexpected argument '--foo' found
+
+  tip: to pass '--foo' as a value, use '-- --foo'
+
+Usage: rg [PATTERN]
+
+For more information, try '--help'.
+
+"#]];
+    assert_data_eq!(err.to_string(), orig_message);
+
+    assert!(err.remove(ContextKind::Suggested).is_some());
+    assert!(err.remove(ContextKind::Suggested).is_none());
+    assert!(err
+        .insert(
+            ContextKind::SuggestedArg,
+            ContextValue::String("--bar".to_string())
+        )
+        .is_none());
+    let edited_message = str![[r#"
+error: unexpected argument '--foo' found
+
+  tip: a similar argument exists: '--bar'
+
+Usage: rg [PATTERN]
+
+For more information, try '--help'.
+
+"#]];
+    assert_data_eq!(err.to_string(), edited_message);
+}
+
 #[test]
 #[cfg(feature = "error-context")]
 #[cfg(feature = "suggestions")]
Repository: clap-rs/clap
Pull request #5965 (2025-04-02 00:51:43)

(chore) update quote
<!--
Thanks for helping out!

Please link the appropriate issue from your PR.

If you don't have an issue, we'd recommend starting with one first so the PR can focus on the
implementation (unless its an obvious bug or documentation fix that will have
little conversation).
-->



Patch:
diff --git a/clap_builder/src/builder/debug_asserts.rs b/clap_builder/src/builder/debug_asserts.rs
index 28ef70eb..cafa9db1 100644
--- a/clap_builder/src/builder/debug_asserts.rs
+++ b/clap_builder/src/builder/debug_asserts.rs
@@ -733,7 +733,7 @@ fn assert_arg(arg: &Arg) {
         );
         assert!(
             arg.is_takes_value_set(),
-            "Argument '{}` is positional and it must take a value but action is {:?}{}",
+            "Argument '{}' is positional and it must take a value but action is {:?}{}",
             arg.get_id(),
             arg.get_action(),
             if arg.get_id() == Id::HELP {


Test patch:
diff --git a/tests/builder/multiple_values.rs b/tests/builder/multiple_values.rs
index 27e9c0a1..a56372c0 100644
--- a/tests/builder/multiple_values.rs
+++ b/tests/builder/multiple_values.rs
@@ -1843,7 +1843,7 @@ For more information, try '--help'.
 }
 
 #[test]
-#[should_panic = "Argument 'pos` is positional and it must take a value but action is SetTrue"]
+#[should_panic = "Argument 'pos' is positional and it must take a value but action is SetTrue"]
 fn disallow_positionals_without_values() {
     let cmd = Command::new("test").arg(Arg::new("pos").num_args(0));
     cmd.debug_assert();
Repository: clap-rs/clap
Pull request #3834 (2022-06-15 03:39:30)

fix: default_value_os_t
Fixes `default_value_os_t` which was broken in https://github.com/clap-rs/clap/pull/3829


Patch:
diff --git a/clap_derive/src/attrs.rs b/clap_derive/src/attrs.rs
index fb35d31f..3c685fbe 100644
--- a/clap_derive/src/attrs.rs
+++ b/clap_derive/src/attrs.rs
@@ -594,7 +594,7 @@ impl Attrs {
                         quote_spanned!(ident.span()=> {
                             static DEFAULT_VALUE: clap::once_cell::sync::Lazy<::std::ffi::OsString> = clap::once_cell::sync::Lazy::new(|| {
                                 let val: #ty = #val;
-                                ::std::ffi::OsString = val.into()
+                                ::std::ffi::OsString::from(val)
                             });
                             &*DEFAULT_VALUE
                         })


Test patch:
diff --git a/tests/derive/default_value.rs b/tests/derive/default_value.rs
index fc07e4c1..6a78f8d6 100644
--- a/tests/derive/default_value.rs
+++ b/tests/derive/default_value.rs
@@ -1,3 +1,5 @@
+use std::path::PathBuf;
+
 use clap::{CommandFactory, Parser};
 
 use crate::utils;
@@ -44,6 +46,30 @@ fn auto_default_value_t() {
     assert!(help.contains("[default: 0]"));
 }
 
+#[test]
+fn default_value_os_t() {
+    #[derive(Parser, PartialEq, Debug)]
+    struct Opt {
+        #[clap(value_parser, default_value_os_t = PathBuf::from("abc.def"))]
+        arg: PathBuf,
+    }
+    assert_eq!(
+        Opt {
+            arg: PathBuf::from("abc.def")
+        },
+        Opt::try_parse_from(&["test"]).unwrap()
+    );
+    assert_eq!(
+        Opt {
+            arg: PathBuf::from("ghi")
+        },
+        Opt::try_parse_from(&["test", "ghi"]).unwrap()
+    );
+
+    let help = utils::get_long_help::<Opt>();
+    assert!(help.contains("[default: abc.def]"));
+}
+
 #[test]
 fn detect_os_variant() {
     #![allow(unused_parens)] // needed for `as_ref` call