@@ -25,6 +25,37 @@ impl builtins::Command for PrintfCommand {
25
25
& self ,
26
26
context : commands:: ExecutionContext < ' _ > ,
27
27
) -> Result < crate :: builtins:: ExitCode , crate :: error:: Error > {
28
+ let result = self . evaluate ( & context) ?;
29
+
30
+ if let Some ( variable_name) = & self . output_variable {
31
+ expansion:: assign_to_named_parameter ( context. shell , variable_name, result) . await ?;
32
+ } else {
33
+ write ! ( context. stdout( ) , "{result}" ) ?;
34
+ context. stdout ( ) . flush ( ) ?;
35
+ }
36
+
37
+ return Ok ( builtins:: ExitCode :: Success ) ;
38
+ }
39
+ }
40
+
41
+ impl PrintfCommand {
42
+ fn evaluate (
43
+ & self ,
44
+ context : & commands:: ExecutionContext < ' _ > ,
45
+ ) -> Result < String , crate :: error:: Error > {
46
+ // Special-case common format string: "%s".
47
+ if self . format == "%s" && self . args . len ( ) == 1 {
48
+ return Ok ( self . args [ 0 ] . clone ( ) ) ;
49
+ }
50
+
51
+ self . evaluate_via_external_command ( context)
52
+ }
53
+
54
+ #[ allow( clippy:: unwrap_in_result) ]
55
+ fn evaluate_via_external_command (
56
+ & self ,
57
+ context : & commands:: ExecutionContext < ' _ > ,
58
+ ) -> Result < String , crate :: error:: Error > {
28
59
// TODO: Don't call external printf command.
29
60
let mut cmd = std:: process:: Command :: new ( "printf" ) ;
30
61
cmd. env_clear ( ) ;
@@ -39,21 +70,12 @@ impl builtins::Command for PrintfCommand {
39
70
write ! ( context. stderr( ) , "{stderr}" ) ?;
40
71
context. stderr ( ) . flush ( ) ?;
41
72
42
- if !output. status . success ( ) {
43
- #[ allow( clippy:: cast_possible_truncation) ]
44
- #[ allow( clippy:: cast_sign_loss) ]
45
- return Ok ( builtins:: ExitCode :: Custom (
46
- output. status . code ( ) . unwrap ( ) as u8
47
- ) ) ;
48
- }
49
-
50
- if let Some ( variable_name) = & self . output_variable {
51
- expansion:: assign_to_named_parameter ( context. shell , variable_name, stdout) . await ?;
73
+ if output. status . success ( ) {
74
+ Ok ( stdout)
52
75
} else {
53
- write ! ( context. stdout( ) , "{stdout}" ) ?;
54
- context. stdout ( ) . flush ( ) ?;
76
+ Err ( crate :: error:: Error :: PrintfFailure (
77
+ output. status . code ( ) . unwrap ( ) ,
78
+ ) )
55
79
}
56
-
57
- return Ok ( builtins:: ExitCode :: Success ) ;
58
80
}
59
81
}
0 commit comments