@@ -35,14 +35,26 @@ pub enum OutputFormat {
3535
3636impl OutputFormat {
3737 /// Parse from a string argument.
38- pub fn from_str ( s : & str ) -> Self {
38+ ///
39+ /// Returns `Ok(format)` for known values, or `Err(unknown_value)` if the
40+ /// string is not recognised. Call sites should warn the user on `Err` and
41+ /// decide whether to fall back to JSON or surface an error.
42+ pub fn parse ( s : & str ) -> Result < Self , String > {
3943 match s. to_lowercase ( ) . as_str ( ) {
40- "table" => Self :: Table ,
41- "yaml" | "yml" => Self :: Yaml ,
42- "csv" => Self :: Csv ,
43- _ => Self :: Json ,
44+ "json" => Ok ( Self :: Json ) ,
45+ "table" => Ok ( Self :: Table ) ,
46+ "yaml" | "yml" => Ok ( Self :: Yaml ) ,
47+ "csv" => Ok ( Self :: Csv ) ,
48+ other => Err ( other. to_string ( ) ) ,
4449 }
4550 }
51+
52+ /// Parse from a string argument, falling back to JSON for unknown values.
53+ ///
54+ /// Prefer `parse()` at call sites where you want to surface a warning.
55+ pub fn from_str ( s : & str ) -> Self {
56+ Self :: parse ( s) . unwrap_or ( Self :: Json )
57+ }
4658}
4759
4860/// Format a JSON value according to the specified output format.
@@ -374,6 +386,25 @@ mod tests {
374386 assert_eq ! ( OutputFormat :: from_str( "unknown" ) , OutputFormat :: Json ) ;
375387 }
376388
389+ #[ test]
390+ fn test_output_format_parse_known ( ) {
391+ assert_eq ! ( OutputFormat :: parse( "json" ) , Ok ( OutputFormat :: Json ) ) ;
392+ assert_eq ! ( OutputFormat :: parse( "table" ) , Ok ( OutputFormat :: Table ) ) ;
393+ assert_eq ! ( OutputFormat :: parse( "yaml" ) , Ok ( OutputFormat :: Yaml ) ) ;
394+ assert_eq ! ( OutputFormat :: parse( "yml" ) , Ok ( OutputFormat :: Yaml ) ) ;
395+ assert_eq ! ( OutputFormat :: parse( "csv" ) , Ok ( OutputFormat :: Csv ) ) ;
396+ // Case-insensitive
397+ assert_eq ! ( OutputFormat :: parse( "JSON" ) , Ok ( OutputFormat :: Json ) ) ;
398+ assert_eq ! ( OutputFormat :: parse( "TABLE" ) , Ok ( OutputFormat :: Table ) ) ;
399+ }
400+
401+ #[ test]
402+ fn test_output_format_parse_unknown_returns_err ( ) {
403+ assert ! ( OutputFormat :: parse( "bogus" ) . is_err( ) ) ;
404+ assert_eq ! ( OutputFormat :: parse( "bogus" ) . unwrap_err( ) , "bogus" ) ;
405+ assert ! ( OutputFormat :: parse( "" ) . is_err( ) ) ;
406+ }
407+
377408 #[ test]
378409 fn test_format_json ( ) {
379410 let val = json ! ( { "name" : "test" } ) ;
0 commit comments