1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
//! getopt - parse command options (POSIX compliant)
//!
//! Parses command-line options and outputs them in normalized form.
extern crate alloc;
use alloc::vec::Vec;
use crate::io;
use super::get_arg;
/// getopt - parse command options (POSIX compliant)
///
/// POSIX: Parses command-line options and outputs them in normalized form.
/// Usage: getopt optstring parameters...
/// Outputs: normalized options, then "--", then non-option arguments.
///
/// # Synopsis
/// ```text
/// getopt optstring parameters...
/// ```
///
/// # Exit Status
/// - 0: Success
/// - >0: Invalid option encountered
pub fn getopt(argc: i32, argv: *const *const u8) -> i32 {
if argc < 2 {
io::write_str(2, b"getopt: missing optstring\n");
return 1;
}
let optstring = match unsafe { get_arg(argv, 1) } {
Some(s) => s,
None => return 1,
};
let mut options: Vec<Vec<u8>> = Vec::new();
let mut operands: Vec<&[u8]> = Vec::new();
let mut i = 2;
let mut error = false;
while i < argc as usize {
let arg = match unsafe { get_arg(argv, i as i32) } {
Some(a) => a,
None => break,
};
if arg == b"--" {
// End of options
i += 1;
while i < argc as usize {
if let Some(a) = unsafe { get_arg(argv, i as i32) } {
operands.push(a);
}
i += 1;
}
break;
} else if arg.starts_with(b"-") && arg.len() > 1 && arg[1] != b'-' {
// Short options
let mut j = 1;
while j < arg.len() {
let opt = arg[j];
let opt_pos = optstring.iter().position(|&c| c == opt);
match opt_pos {
Some(pos) => {
// Check if option takes an argument
let takes_arg = pos + 1 < optstring.len() && optstring[pos + 1] == b':';
if takes_arg {
if j + 1 < arg.len() {
// Argument is attached: -oARG
let mut opt_str = Vec::with_capacity(3);
opt_str.push(b'-');
opt_str.push(opt);
options.push(opt_str);
let arg_val: Vec<u8> = arg[j + 1..].to_vec();
options.push(arg_val);
break;
} else {
// Argument is next parameter
i += 1;
let mut opt_str = Vec::with_capacity(3);
opt_str.push(b'-');
opt_str.push(opt);
options.push(opt_str);
if let Some(next_arg) = unsafe { get_arg(argv, i as i32) } {
options.push(next_arg.to_vec());
} else {
io::write_str(2, b"getopt: option requires an argument -- ");
io::write_all(2, &[opt]);
io::write_str(2, b"\n");
error = true;
}
break;
}
} else {
// Option without argument
let mut opt_str = Vec::with_capacity(3);
opt_str.push(b'-');
opt_str.push(opt);
options.push(opt_str);
}
}
None => {
io::write_str(2, b"getopt: invalid option -- ");
io::write_all(2, &[opt]);
io::write_str(2, b"\n");
error = true;
}
}
j += 1;
}
} else {
// Non-option argument
operands.push(arg);
}
i += 1;
}
// Output options
let mut first = true;
for opt in &options {
if !first {
io::write_str(1, b" ");
}
// Quote if contains spaces
if opt.contains(&b' ') || opt.contains(&b'\t') {
io::write_str(1, b"'");
io::write_all(1, opt);
io::write_str(1, b"'");
} else {
io::write_all(1, opt);
}
first = false;
}
// Output separator
if !first {
io::write_str(1, b" ");
}
io::write_str(1, b"--");
// Output operands
for op in &operands {
io::write_str(1, b" ");
if op.contains(&b' ') || op.contains(&b'\t') {
io::write_str(1, b"'");
io::write_all(1, op);
io::write_str(1, b"'");
} else {
io::write_all(1, op);
}
}
io::write_str(1, b"\n");
if error { 1 } else { 0 }
}
#[cfg(test)]
mod tests {
extern crate std;
use std::process::Command;
use std::path::PathBuf;
fn get_armybox_path() -> PathBuf {
if let Ok(path) = std::env::var("ARMYBOX_PATH") {
return PathBuf::from(path);
}
let manifest_dir = std::env::var("CARGO_MANIFEST_DIR")
.map(PathBuf::from)
.unwrap_or_else(|_| std::env::current_dir().unwrap());
let release = manifest_dir.join("target/release/armybox");
if release.exists() { return release; }
manifest_dir.join("target/debug/armybox")
}
#[test]
fn test_getopt_basic() {
let armybox = get_armybox_path();
if !armybox.exists() { return; }
let output = Command::new(&armybox)
.args(["getopt", "ab:c", "-a", "-b", "val", "arg"])
.output()
.unwrap();
assert_eq!(output.status.code(), Some(0));
let stdout = std::string::String::from_utf8_lossy(&output.stdout);
assert!(stdout.contains("-a"));
assert!(stdout.contains("-b"));
assert!(stdout.contains("--"));
}
}