-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathpaste.rs
More file actions
399 lines (357 loc) · 11.6 KB
/
paste.rs
File metadata and controls
399 lines (357 loc) · 11.6 KB
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
//! paste builtin command - merge lines of files
use async_trait::async_trait;
use super::{Builtin, Context, read_text_file};
use crate::error::Result;
use crate::interpreter::ExecResult;
/// The paste builtin - merge lines of files.
///
/// Usage: paste [-d DELIM] [-s] [FILE...]
///
/// Options:
/// -d DELIM Use DELIM instead of TAB as delimiter (cycles through chars)
/// -s Paste one file at a time (serial mode)
pub struct Paste;
struct PasteOptions {
delimiters: Vec<char>,
serial: bool,
}
fn parse_paste_args(args: &[String]) -> (PasteOptions, Vec<String>) {
let mut opts = PasteOptions {
delimiters: vec!['\t'],
serial: false,
};
let mut files = Vec::new();
let mut p = super::arg_parser::ArgParser::new(args);
while !p.is_done() {
if let Some(val) = p.flag_value_opt("-d") {
opts.delimiters = parse_delim_spec(val);
} else if p.flag("-s") {
opts.serial = true;
} else if try_parse_combined_flags(&mut p, &mut opts) {
// handled combined flags like -sd,
} else if let Some(arg) = p.positional() {
files.push(arg.to_string());
}
}
if opts.delimiters.is_empty() {
opts.delimiters = vec!['\t'];
}
(opts, files)
}
/// Parse combined short flags like `-sd,` where `s` is a boolean flag
/// and `d` takes the rest of the string as its value.
fn try_parse_combined_flags(
p: &mut super::arg_parser::ArgParser<'_>,
opts: &mut PasteOptions,
) -> bool {
let arg = match p.current() {
Some(a) if a.starts_with('-') && !a.starts_with("--") && a.len() > 2 => a,
_ => return false,
};
let chars: Vec<char> = arg[1..].chars().collect();
let mut i = 0;
let mut serial = false;
let mut delimiters = None;
while i < chars.len() {
match chars[i] {
's' => {
serial = true;
i += 1;
}
'd' => {
// 'd' consumes the rest as delimiter spec
let rest: String = chars[i + 1..].iter().collect();
if !rest.is_empty() {
delimiters = Some(parse_delim_spec(&rest));
}
i = chars.len(); // consumed everything
}
_ => return false, // unknown flag char, bail out
}
}
// All chars parsed successfully — apply and advance
if serial {
opts.serial = true;
}
if let Some(d) = delimiters {
opts.delimiters = d;
}
p.advance();
true
}
fn parse_delim_spec(spec: &str) -> Vec<char> {
let mut delims = Vec::new();
let mut chars = spec.chars();
while let Some(c) = chars.next() {
if c == '\\' {
match chars.next() {
Some('n') => delims.push('\n'),
Some('t') => delims.push('\t'),
Some('\\') => delims.push('\\'),
Some('0') => delims.push('\0'),
Some(other) => delims.push(other),
None => delims.push('\\'),
}
} else {
delims.push(c);
}
}
delims
}
#[async_trait]
impl Builtin for Paste {
async fn execute(&self, ctx: Context<'_>) -> Result<ExecResult> {
let (opts, files) = parse_paste_args(ctx.args);
// Collect input sources
let mut sources: Vec<Vec<String>> = Vec::new();
if files.is_empty() {
// Read from stdin
if let Some(stdin) = ctx.stdin {
sources.push(stdin.lines().map(|l| l.to_string()).collect());
}
} else {
for file in &files {
if file == "-" {
let lines = ctx
.stdin
.map(|s| s.lines().map(|l| l.to_string()).collect())
.unwrap_or_default();
sources.push(lines);
} else {
let path = if file.starts_with('/') {
std::path::PathBuf::from(file)
} else {
ctx.cwd.join(file)
};
let text = match read_text_file(&*ctx.fs, &path, "paste").await {
Ok(t) => t,
Err(e) => return Ok(e),
};
sources.push(text.lines().map(|l| l.to_string()).collect());
}
}
}
let mut output = String::new();
if opts.serial {
// Serial mode: each file becomes one line
for source in &sources {
for (j, line) in source.iter().enumerate() {
if j > 0 {
let delim = opts.delimiters[(j - 1) % opts.delimiters.len()];
output.push(delim);
}
output.push_str(line);
}
output.push('\n');
}
} else {
// Parallel mode: merge corresponding lines
let max_lines = sources.iter().map(|s| s.len()).max().unwrap_or(0);
for i in 0..max_lines {
for (j, source) in sources.iter().enumerate() {
if j > 0 {
let delim = opts.delimiters[(j - 1) % opts.delimiters.len()];
output.push(delim);
}
if let Some(line) = source.get(i) {
output.push_str(line);
}
}
output.push('\n');
}
}
Ok(ExecResult::ok(output))
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use crate::fs::{FileSystem, InMemoryFs};
async fn run_paste(args: &[&str], stdin: Option<&str>) -> ExecResult {
let fs = Arc::new(InMemoryFs::new());
let mut variables = HashMap::new();
let env = HashMap::new();
let mut cwd = PathBuf::from("/");
let args: Vec<String> = args.iter().map(|s| s.to_string()).collect();
let ctx = Context {
args: &args,
env: &env,
variables: &mut variables,
cwd: &mut cwd,
fs,
stdin,
#[cfg(feature = "http_client")]
http_client: None,
#[cfg(feature = "git")]
git_client: None,
shell: None,
};
Paste.execute(ctx).await.unwrap()
}
async fn run_paste_with_fs(
args: &[&str],
stdin: Option<&str>,
files: &[(&str, &[u8])],
) -> ExecResult {
let fs = Arc::new(InMemoryFs::new());
for (path, content) in files {
fs.write_file(std::path::Path::new(path), content)
.await
.unwrap();
}
let mut variables = HashMap::new();
let env = HashMap::new();
let mut cwd = PathBuf::from("/");
let args: Vec<String> = args.iter().map(|s| s.to_string()).collect();
let ctx = Context {
args: &args,
env: &env,
variables: &mut variables,
cwd: &mut cwd,
fs,
stdin,
#[cfg(feature = "http_client")]
http_client: None,
#[cfg(feature = "git")]
git_client: None,
shell: None,
};
Paste.execute(ctx).await.unwrap()
}
#[tokio::test]
async fn test_paste_stdin() {
let result = run_paste(&[], Some("a\nb\nc\n")).await;
assert_eq!(result.exit_code, 0);
assert_eq!(result.stdout, "a\nb\nc\n");
}
#[tokio::test]
async fn test_paste_two_files() {
let result = run_paste_with_fs(
&["/a.txt", "/b.txt"],
None,
&[("/a.txt", b"1\n2\n3\n"), ("/b.txt", b"a\nb\nc\n")],
)
.await;
assert_eq!(result.exit_code, 0);
assert_eq!(result.stdout, "1\ta\n2\tb\n3\tc\n");
}
#[tokio::test]
async fn test_paste_uneven_files() {
let result = run_paste_with_fs(
&["/a.txt", "/b.txt"],
None,
&[("/a.txt", b"1\n2\n3\n"), ("/b.txt", b"a\nb\n")],
)
.await;
assert_eq!(result.exit_code, 0);
assert_eq!(result.stdout, "1\ta\n2\tb\n3\t\n");
}
#[tokio::test]
async fn test_paste_custom_delimiter() {
let result = run_paste_with_fs(
&["-d", ",", "/a.txt", "/b.txt"],
None,
&[("/a.txt", b"1\n2\n"), ("/b.txt", b"a\nb\n")],
)
.await;
assert_eq!(result.exit_code, 0);
assert_eq!(result.stdout, "1,a\n2,b\n");
}
#[tokio::test]
async fn test_paste_serial() {
let result = run_paste_with_fs(
&["-s", "/a.txt", "/b.txt"],
None,
&[("/a.txt", b"1\n2\n3\n"), ("/b.txt", b"a\nb\nc\n")],
)
.await;
assert_eq!(result.exit_code, 0);
assert_eq!(result.stdout, "1\t2\t3\na\tb\tc\n");
}
#[tokio::test]
async fn test_paste_serial_custom_delim() {
let result = run_paste_with_fs(
&["-s", "-d", ",", "/a.txt"],
None,
&[("/a.txt", b"x\ny\nz\n")],
)
.await;
assert_eq!(result.exit_code, 0);
assert_eq!(result.stdout, "x,y,z\n");
}
#[tokio::test]
async fn test_paste_cycling_delimiters() {
let result = run_paste_with_fs(
&["-d", ",:", "/a.txt", "/b.txt", "/c.txt"],
None,
&[
("/a.txt", b"1\n2\n"),
("/b.txt", b"a\nb\n"),
("/c.txt", b"x\ny\n"),
],
)
.await;
assert_eq!(result.exit_code, 0);
assert_eq!(result.stdout, "1,a:x\n2,b:y\n");
}
#[tokio::test]
async fn test_paste_empty_input() {
let result = run_paste(&[], Some("")).await;
assert_eq!(result.exit_code, 0);
assert_eq!(result.stdout, "");
}
#[tokio::test]
async fn test_paste_file_not_found() {
let result = run_paste(&["/nonexistent"], None).await;
assert_eq!(result.exit_code, 1);
assert!(result.stderr.contains("paste:"));
}
#[tokio::test]
async fn test_paste_combined_sd_comma() {
let result = run_paste(&["-sd,"], Some("a\nb\nc\n")).await;
assert_eq!(result.exit_code, 0);
assert_eq!(result.stdout, "a,b,c\n");
}
#[tokio::test]
async fn test_paste_combined_sd_colon() {
let result = run_paste(&["-sd:"], Some("x\ny\nz\n")).await;
assert_eq!(result.exit_code, 0);
assert_eq!(result.stdout, "x:y:z\n");
}
#[tokio::test]
async fn test_paste_stdin_dash() {
let result =
run_paste_with_fs(&["-", "/b.txt"], Some("1\n2\n"), &[("/b.txt", b"a\nb\n")]).await;
assert_eq!(result.exit_code, 0);
assert_eq!(result.stdout, "1\ta\n2\tb\n");
}
#[tokio::test]
async fn test_paste_backslash_n_delimiter() {
let result = run_paste_with_fs(
&["-d", "\\n", "-s", "/a.txt"],
None,
&[("/a.txt", b"x\ny\nz\n")],
)
.await;
assert_eq!(result.exit_code, 0);
assert_eq!(result.stdout, "x\ny\nz\n");
}
#[tokio::test]
async fn test_paste_three_files() {
let result = run_paste_with_fs(
&["/a.txt", "/b.txt", "/c.txt"],
None,
&[
("/a.txt", b"1\n2\n"),
("/b.txt", b"a\nb\n"),
("/c.txt", b"X\nY\n"),
],
)
.await;
assert_eq!(result.exit_code, 0);
assert_eq!(result.stdout, "1\ta\tX\n2\tb\tY\n");
}
}