Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
132 changes: 89 additions & 43 deletions crates/bashkit/src/builtins/cuttr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

use async_trait::async_trait;

use super::{Builtin, BuiltinHelper, Context, read_text_file};
use super::{Builtin, BuiltinHelper, Context, read_stream_file};
use crate::error::Result;
use crate::fs::vfs_join;
use crate::interpreter::ExecResult;
Expand Down Expand Up @@ -33,7 +33,46 @@ impl BuiltinHelper for Cut {
#[derive(PartialEq)]
enum CutMode {
Fields,
/// `-c`: UTF-8 characters; an invalid byte counts as one character.
Chars,
/// `-b`: bytes.
Bytes,
}

/// Selection units of a line: one per UTF-8 char, one per invalid byte.
/// Input stays bytes end to end, so `cut` never rewrites a Latin-1 or
/// binary line to U+FFFD (L-STREAM-001 does not apply to cut).
fn char_units(line: &[u8]) -> Vec<&[u8]> {
let mut units = Vec::new();
for chunk in line.utf8_chunks() {
let valid = chunk.valid();
let mut start = 0;
for ch in valid.chars() {
let end = start + ch.len_utf8();
units.push(&valid.as_bytes()[start..end]);
start = end;
}
units.extend(chunk.invalid().chunks(1));
}
units
}

/// Split `line` on every occurrence of `delim` (non-empty).
fn split_bytes<'a>(line: &'a [u8], delim: &[u8]) -> Vec<&'a [u8]> {
let mut parts = Vec::new();
let mut start = 0;
let mut i = 0;
while i + delim.len() <= line.len() {
if &line[i..i + delim.len()] == delim {
parts.push(&line[start..i]);
i += delim.len();
start = i;
} else {
i += 1;
}
}
parts.push(&line[start..]);
parts
}

#[async_trait]
Expand Down Expand Up @@ -84,7 +123,11 @@ impl Builtin for Cut {
spec = val;
mode = CutMode::Fields;
}
'b' | 'c' => {
'b' => {
spec = val;
mode = CutMode::Bytes;
}
'c' => {
spec = val;
mode = CutMode::Chars;
}
Expand All @@ -104,40 +147,44 @@ impl Builtin for Cut {
let positions = parse_position_spec(&spec);
let out_delim = output_delimiter.unwrap_or_else(|| delimiter.to_string());

let process_line = |line: &str| -> Option<String> {
let mut delim_buf = [0u8; 4];
let delim: &[u8] = delimiter.encode_utf8(&mut delim_buf).as_bytes();
let out_delim = out_delim.into_bytes();

let select = |units: Vec<&[u8]>| -> Vec<u8> {
let resolved = resolve_positions(&positions, units.len());
if complement {
units
.iter()
.enumerate()
.filter(|(i, _)| resolved.binary_search(&(i + 1)).is_err())
.flat_map(|(_, u)| u.iter().copied())
.collect()
} else {
resolved
.iter()
.filter_map(|&p| units.get(p - 1))
.flat_map(|u| u.iter().copied())
.collect()
}
};

let process_line = |line: &[u8]| -> Option<Vec<u8>> {
match mode {
CutMode::Chars => {
let chars: Vec<char> = line.chars().collect();
let total = chars.len();
let resolved = resolve_positions(&positions, total);
let selected: Vec<char> = if complement {
chars
.iter()
.enumerate()
.filter(|(i, _)| !resolved.contains(&(i + 1)))
.map(|(_, c)| *c)
.collect()
} else {
resolved
.iter()
.filter_map(|&p| chars.get(p - 1).copied())
.collect()
};
Some(selected.into_iter().collect())
}
CutMode::Bytes => Some(select(line.chunks(1).collect())),
CutMode::Chars => Some(select(char_units(line))),
CutMode::Fields => {
let parts = split_bytes(line, delim);
// Lines without a delimiter print whole unless -s.
if !line.contains(delimiter) {
return (!only_delimited).then(|| line.to_string());
if parts.len() == 1 {
return (!only_delimited).then(|| line.to_vec());
}
let parts: Vec<&str> = line.split(delimiter).collect();
let total = parts.len();
let resolved = resolve_positions(&positions, total);
let selected: Vec<&str> = if complement {
let resolved = resolve_positions(&positions, parts.len());
let selected: Vec<&[u8]> = if complement {
parts
.iter()
.enumerate()
.filter(|(i, _)| !resolved.contains(&(i + 1)))
.filter(|(i, _)| resolved.binary_search(&(i + 1)).is_err())
.map(|(_, s)| *s)
.collect()
} else {
Expand All @@ -146,36 +193,35 @@ impl Builtin for Cut {
.filter_map(|&f| parts.get(f - 1).copied())
.collect()
};
Some(selected.join(&out_delim))
Some(selected.join(out_delim.as_slice()))
}
}
};

let mut output = String::new();
let line_sep = if zero_terminated { '\0' } else { '\n' };
let out_sep = if zero_terminated { "\0" } else { "\n" };
let mut output: Vec<u8> = Vec::new();
let line_sep = if zero_terminated { b'\0' } else { b'\n' };

let process_input = |text: &str, output: &mut String| {
let body = text.strip_suffix(line_sep).unwrap_or(text);
let process_input = |text: &[u8], output: &mut Vec<u8>| {
if text.is_empty() {
return;
}
for line in body.split(line_sep) {
let body = text.strip_suffix(&[line_sep]).unwrap_or(text);
for line in body.split(|&b| b == line_sep) {
if let Some(result) = process_line(line) {
output.push_str(&result);
output.push_str(out_sep);
output.extend_from_slice(&result);
output.push(line_sep);
}
}
};

if files.is_empty() || files.iter().all(|f| f.as_str() == "-") {
if let Some(stdin) = ctx.stdin {
if let Some(stdin) = ctx.stdin_bytes() {
process_input(stdin, &mut output);
}
} else {
for file in &files {
if file.as_str() == "-" {
if let Some(stdin) = ctx.stdin {
if let Some(stdin) = ctx.stdin_bytes() {
process_input(stdin, &mut output);
}
continue;
Expand All @@ -187,15 +233,15 @@ impl Builtin for Cut {
vfs_join(ctx.cwd, file)
};

let text = match read_text_file(&*ctx.fs, &path, "cut").await {
let data = match read_stream_file(&*ctx.fs, &path, "cut").await {
Ok(t) => t,
Err(e) => return Ok(*e),
};
process_input(&text, &mut output);
process_input(data.as_bytes(), &mut output);
}
}

Ok(ExecResult::ok(output))
Ok(ExecResult::ok_bytes(output))
}
}

Expand Down
6 changes: 2 additions & 4 deletions crates/bashkit/src/builtins/hextools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -738,10 +738,8 @@ impl Builtin for Xxd {
};

if opts.reverse {
let bytes = xxd_reverse(&data, opts.plain);
// Output raw bytes as lossy UTF-8
let output = String::from_utf8_lossy(&bytes).to_string();
Ok(ExecResult::ok(output))
// Raw bytes: `xxd -r` exists to rebuild binary data.
Ok(ExecResult::ok_bytes(xxd_reverse(&data, opts.plain)))
} else {
let output = xxd_dump(&data, &opts);
Ok(ExecResult::ok(output))
Expand Down
10 changes: 6 additions & 4 deletions crates/bashkit/src/builtins/pipeline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -780,21 +780,23 @@ impl Builtin for Tee {
.map(|vs| vs.map(|v| v.to_string_lossy().into_owned()).collect())
.unwrap_or_default();

let input = ctx.stdin.map(|stdin| &**stdin).unwrap_or("");
// Bytes, not text: tee is a passthrough and must not rewrite invalid
// UTF-8 (a Latin-1 CSV, a binary blob) to U+FFFD.
let input = ctx.stdin_bytes().unwrap_or_default();

for file in &files {
// tee(1): "If a FILE is -, it refers to a file named - ."
// The codegen output documents the same in `after_help`.
let path = resolve_path(ctx.cwd, file);

if append {
ctx.fs.append_file(&path, input.as_bytes()).await?;
ctx.fs.append_file(&path, input).await?;
} else {
ctx.fs.write_file(&path, input.as_bytes()).await?;
ctx.fs.write_file(&path, input).await?;
}
}

Ok(ExecResult::ok(input.to_string()))
Ok(ExecResult::ok_bytes(input.to_vec()))
}
}

Expand Down
35 changes: 34 additions & 1 deletion crates/bashkit/src/builtins/sortuniq.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use std::cmp::Ordering;

use async_trait::async_trait;

use super::{Builtin, Context, read_text_file};
use super::{Builtin, Context, read_text_file, resolve_path};
use crate::error::Result;
use crate::fs::vfs_join;
use crate::interpreter::ExecResult;
Expand Down Expand Up @@ -981,6 +981,39 @@ impl Builtin for Sort {
files.push("-".to_string());
}
let line_sep = if zero_terminated { '\0' } else { '\n' };

// `sort -o FILE FILE` rewrites its own input. Text builtins decode
// invalid UTF-8 with U+FFFD (L-STREAM-001), so a Latin-1 or binary
// FILE would be silently destroyed; refuse instead, like `sed -i`
// (L-SED-003). Writing to a different file stays lossy-but-safe.
if let Some(ref outfile) = output_file {
// Canonicalize both sides (normalize + follow symlinks) so `./f`,
// `d/../f`, `/cwd/f` and `ln -s f link` all match, like GNU's
// stat-based same-file check. Unresolvable paths fall back to the
// lexical form (a missing -o target cannot alias an input).
let fs = ctx.fs.as_ref();
let lexical_out = resolve_path(ctx.cwd, outfile);
let out_path = crate::fs::canonicalize(fs, &lexical_out)
.await
.unwrap_or(lexical_out);
for file in files.iter().filter(|f| f.as_str() != "-") {
let lexical = resolve_path(ctx.cwd, file);
let path = crate::fs::canonicalize(fs, &lexical)
.await
.unwrap_or(lexical);
if path != out_path {
Comment thread
chaliy marked this conversation as resolved.
Resolved
Comment thread
chaliy marked this conversation as resolved.
Resolved
continue;
}
if let Ok(bytes) = ctx.fs.read_file(&path).await
&& std::str::from_utf8(&bytes).is_err()
{
return Ok(sort_err(format!(
"sort: cannot rewrite {file}: not a valid UTF-8 text file\n"
)));
}
}
}

let mut streams: Vec<Vec<String>> = Vec::new();
for file in &files {
let text = if file == "-" {
Expand Down
30 changes: 13 additions & 17 deletions crates/bashkit/src/builtins/split.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

use async_trait::async_trait;

use super::{Builtin, Context, read_text_file, resolve_path};
use super::{Builtin, Context, read_stream_file, resolve_path};
use crate::error::Result;
use crate::interpreter::ExecResult;

Expand Down Expand Up @@ -80,12 +80,14 @@ impl Builtin for Split {
let file = positional.first().copied().unwrap_or("-");
let prefix = positional.get(1).copied().unwrap_or("x");

let input = if file == "-" {
ctx.stdin.map(ToString::to_string).unwrap_or_default()
// Bytes end to end: pieces must concatenate back to the exact input,
// whatever its encoding or line endings.
let input: Vec<u8> = if file == "-" {
ctx.stdin_bytes().unwrap_or_default().to_vec()
} else {
let path = resolve_path(ctx.cwd, file);
match read_text_file(ctx.fs.as_ref(), &path, "split").await {
Ok(text) => text,
match read_stream_file(ctx.fs.as_ref(), &path, "split").await {
Ok(data) => data.into_bytes(),
Err(_) => {
return Ok(ExecResult::err(
format!(
Expand All @@ -109,7 +111,7 @@ impl Builtin for Split {
));
}
let chunk_size = input.len().div_ceil(n);
let bytes = input.as_bytes();
let bytes = input.as_slice();
let mut pos = 0;
while pos < bytes.len() {
let end = (pos + chunk_size).min(bytes.len());
Expand All @@ -121,7 +123,7 @@ impl Builtin for Split {
}
} else if let Some(size) = bytes_per_file {
// Split by byte size
let bytes = input.as_bytes();
let bytes = input.as_slice();
let mut pos = 0;
while pos < bytes.len() {
let end = (pos + size).min(bytes.len());
Expand All @@ -134,21 +136,15 @@ impl Builtin for Split {
} else {
// Split by lines
let n = lines_per_file.unwrap_or(1000);
let lines: Vec<&str> = input.lines().collect();
// Each line keeps its own terminator (`\r\n` stays intact).
let lines: Vec<&[u8]> = input.split_inclusive(|&b| b == b'\n').collect();
let mut pos = 0;
while pos < lines.len() {
let end = (pos + n).min(lines.len());
let suffix = make_suffix(file_index, numeric_suffix);
let out_path = resolve_path(ctx.cwd, &format!("{}{}", prefix, suffix));
let chunk = lines[pos..end].join("\n");
let chunk_with_newline = if end < lines.len() || input.ends_with('\n') {
format!("{}\n", chunk)
} else {
chunk
};
ctx.fs
.write_file(&out_path, chunk_with_newline.as_bytes())
.await?;
let chunk = lines[pos..end].concat();
ctx.fs.write_file(&out_path, &chunk).await?;
file_index += 1;
pos = end;
}
Expand Down
Loading
Loading