exeora-cli 0.8.0

Native Exeora CLI and local tool executor
Documentation
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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
use super::path::{relative_string, resolve_in_project};
use crate::{
    error::{ErrorCode, ExeoraError},
    protocol::{MAX_GREP_MATCHES, MAX_LIST_ENTRIES, MAX_READ_BYTES},
};
use cap_std::{
    ambient_authority,
    fs::{Dir, OpenOptions},
};
use globset::{Glob, GlobMatcher};
use grep_matcher::{Match, Matcher, NoCaptures, NoError};
use grep_searcher::{BinaryDetection, SearcherBuilder, sinks};
use ignore::gitignore::{Gitignore, GitignoreBuilder};
use memchr::{memchr, memmem};
use regress::Regex;
use serde::Deserialize;
use serde_json::{Value, json};
use similar::TextDiff;
use std::{
    collections::VecDeque,
    fs,
    io::{Read, Write},
    path::{Path, PathBuf},
    sync::Arc,
};
use unicode_normalization::UnicodeNormalization;

const ALWAYS_SKIP: [&str; 5] = [".git", "node_modules", ".wrangler", "dist", ".astro"];

#[derive(Deserialize)]
struct ReadArgs {
    path: String,
    offset: Option<usize>,
    limit: Option<usize>,
}

pub async fn read_file(root: &Path, args: Value) -> Result<Value, ExeoraError> {
    let root = root.to_owned();
    tokio::task::spawn_blocking(move || {
        let args: ReadArgs = parse(args)?;
        let (real_root, relative) = resolve_in_project(&root, &args.path)?;
        let dir = open_root(&real_root)?;
        let mut file = dir.open(&relative).map_err(|error| ExeoraError::tool(format!("Could not read {}: {:?}.", relative_string(&relative), error.kind())))?;
        let mut bytes = Vec::new();
        file.read_to_end(&mut bytes).map_err(|error| ExeoraError::tool(error.to_string()))?;
        if memchr(0, &bytes[..bytes.len().min(8192)]).is_some() {
            return Err(ExeoraError::tool(format!("{} is a binary file ({} bytes). read_file only returns text.", relative_string(&relative), bytes.len())));
        }
        let text = String::from_utf8_lossy(&bytes);
        let lines: Vec<&str> = text.split('\n').collect();
        let total = if text.is_empty() { 0 } else if text.ends_with('\n') { lines.len() - 1 } else { lines.len() };
        let start = args.offset.map_or(0, |offset| offset - 1);
        if start > 0 && start >= total {
            return Err(ExeoraError::tool(format!("Offset {} is past the end of {}, which has {total} lines.", args.offset.unwrap_or_default(), relative_string(&relative))));
        }
        let end = args.limit.map_or(total, |limit| (start + limit).min(total));
        let selected = lines[start..end].join("\n");
        let (content, cut) = truncate_complete_lines(&selected, MAX_READ_BYTES);
        Ok(json!({ "path": relative_string(&relative), "content": content, "truncated": cut || end < total, "totalLines": total }))
    }).await.map_err(join_error)?
}

#[derive(Deserialize)]
struct ListArgs {
    path: Option<String>,
    recursive: Option<bool>,
    glob: Option<String>,
}

pub async fn list_files(root: &Path, args: Value) -> Result<Value, ExeoraError> {
    let root = root.to_owned();
    tokio::task::spawn_blocking(move || {
        let args: ListArgs = parse(args)?;
        let (real_root, start) = resolve_in_project(&root, args.path.as_deref().unwrap_or("."))?;
        let glob = compile_glob(args.glob.as_deref())?;
        let mut seen = 0usize;
        let mut output = Vec::new();
        for entry in walk(&real_root, &start, args.recursive.unwrap_or(false), MAX_LIST_ENTRIES + 1)? {
            if glob.as_ref().is_some_and(|glob| !glob.is_match(&entry.relative)) { continue; }
            seen += 1;
            if output.len() >= MAX_LIST_ENTRIES { continue; }
            let mut value = json!({
                "path": relative_string(&entry.relative),
                "type": if entry.symlink { "symlink" } else if entry.directory { "directory" } else { "file" },
            });
            if !entry.directory
                && let Ok(metadata) = fs::metadata(&entry.absolute) { value["size"] = json!(metadata.len()); }
            output.push(value);
        }
        Ok(json!({ "path": if start.as_os_str().is_empty() { ".".to_owned() } else { relative_string(&start) }, "entries": output, "truncated": seen > MAX_LIST_ENTRIES }))
    }).await.map_err(join_error)?
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct GrepArgs {
    pattern: String,
    path: Option<String>,
    glob: Option<String>,
    case_insensitive: Option<bool>,
    max_results: Option<usize>,
}

pub async fn grep(root: &Path, args: Value) -> Result<Value, ExeoraError> {
    let root = root.to_owned();
    tokio::task::spawn_blocking(move || {
        let args: GrepArgs = parse(args)?;
        let (real_root, start) = resolve_in_project(&root, args.path.as_deref().unwrap_or("."))?;
        let flags = if args.case_insensitive.unwrap_or(false) {
            "i"
        } else {
            ""
        };
        let regex = Regex::with_flags(&args.pattern, flags).map_err(|error| {
            ExeoraError::new(
                ErrorCode::InvalidArguments,
                format!("Not a valid regular expression: {error}"),
            )
        })?;
        let matcher = RegressMatcher(Arc::new(regex));
        let glob = compile_glob(args.glob.as_deref())?;
        let limit = args.max_results.unwrap_or(MAX_GREP_MATCHES);
        let mut rows = Vec::new();
        let mut truncated = false;
        for entry in walk(&real_root, &start, true, 50_000)? {
            if entry.directory
                || entry.symlink
                || glob
                    .as_ref()
                    .is_some_and(|glob| !glob.is_match(&entry.relative))
            {
                continue;
            }

            let Ok((file_rows, exceeded)) = search_path(&matcher, &entry, limit - rows.len())
            else {
                continue;
            };
            rows.extend(file_rows);
            if exceeded {
                truncated = true;
                break;
            }
        }
        Ok(json!({ "matches": rows, "truncated": truncated }))
    })
    .await
    .map_err(join_error)?
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct EditArgs {
    path: String,
    old_string: String,
    new_string: String,
}

pub async fn edit_file(root: &Path, args: Value) -> Result<Value, ExeoraError> {
    let root = root.to_owned();
    tokio::task::spawn_blocking(move || {
        let args: EditArgs = parse(args)?;
        let (real_root, relative) = resolve_in_project(&root, &args.path)?;
        let dir = open_root(&real_root)?;
        let mut raw = String::new();
        dir.open(&relative)
            .and_then(|mut file| file.read_to_string(&mut raw))
            .map_err(|error| {
                ExeoraError::tool(format!(
                    "Could not edit {}: {:?}.",
                    relative_string(&relative),
                    error.kind()
                ))
            })?;
        let (bom, content) = raw
            .strip_prefix('\u{feff}')
            .map_or(("", raw.as_str()), |text| ("\u{feff}", text));
        let crlf = content
            .find("\r\n")
            .is_some_and(|crlf| content.find('\n') == Some(crlf + 1));
        let normalized = content.replace("\r\n", "\n").replace('\r', "\n");
        let old = args.old_string.replace("\r\n", "\n").replace('\r', "\n");
        let (base, index, length) = unique_match(&normalized, &old, &relative)?;
        let mut changed = base.clone();
        changed.replace_range(index..index + length, &args.new_string);
        let restored = if crlf {
            changed.replace('\n', "\r\n")
        } else {
            changed.clone()
        };
        let mut options = OpenOptions::new();
        options.write(true).truncate(true);
        let mut file = dir
            .open_with(&relative, &options)
            .map_err(|error| ExeoraError::tool(error.to_string()))?;
        file.write_all(format!("{bom}{restored}").as_bytes())
            .map_err(|error| ExeoraError::tool(error.to_string()))?;
        let path = relative_string(&relative);
        let diff = TextDiff::from_lines(&base, &changed)
            .unified_diff()
            .header(&path, &path)
            .to_string();
        Ok(json!({ "path": path, "replacements": 1, "diff": diff }))
    })
    .await
    .map_err(join_error)?
}

#[derive(Deserialize)]
struct WriteArgs {
    path: String,
    content: String,
}

pub async fn write_file(root: &Path, args: Value) -> Result<Value, ExeoraError> {
    let root = root.to_owned();
    tokio::task::spawn_blocking(move || {
        let args: WriteArgs = parse(args)?;
        let (real_root, relative) = resolve_in_project(&root, &args.path)?;
        let dir = open_root(&real_root)?;
        let existed = dir.metadata(&relative).is_ok();
        if let Some(parent) = relative.parent() { dir.create_dir_all(parent).map_err(|error| ExeoraError::tool(error.to_string()))?; }
        let mut options = OpenOptions::new();
        options.write(true).create(true).truncate(true);
        let mut file = dir.open_with(&relative, &options)
            .map_err(|error| ExeoraError::tool(error.to_string()))?;
        file.write_all(args.content.as_bytes()).map_err(|error| ExeoraError::tool(error.to_string()))?;
        Ok(json!({ "path": relative_string(&relative), "bytesWritten": args.content.len(), "created": !existed }))
    }).await.map_err(join_error)?
}

#[derive(Clone)]
struct RegressMatcher(Arc<Regex>);

impl Matcher for RegressMatcher {
    type Captures = NoCaptures;
    type Error = NoError;
    fn find_at(&self, haystack: &[u8], at: usize) -> Result<Option<Match>, NoError> {
        match std::str::from_utf8(haystack) {
            Ok(text) => Ok(self
                .0
                .find_from(text, at)
                .next()
                .map(|found| Match::new(found.start(), found.end()))),
            Err(_) => {
                let text = String::from_utf8_lossy(&haystack[at..]);
                Ok(self.0.find(&text).map(|_| Match::new(at, haystack.len())))
            }
        }
    }
    fn new_captures(&self) -> Result<NoCaptures, NoError> {
        Ok(NoCaptures::new())
    }
}

struct WalkEntry {
    absolute: PathBuf,
    relative: PathBuf,
    directory: bool,
    symlink: bool,
}

fn walk(
    root: &Path,
    start: &Path,
    recursive: bool,
    limit: usize,
) -> Result<Vec<WalkEntry>, ExeoraError> {
    let ignores = load_ignore(root);
    let mut queue = VecDeque::from([root.join(start)]);
    let mut output = Vec::new();
    while let Some(directory) = queue.pop_front() {
        let Ok(entries) = fs::read_dir(&directory) else {
            continue;
        };
        for result in entries {
            if output.len() >= limit {
                return Ok(output);
            }
            let Ok(entry) = result else {
                continue;
            };
            let name = entry.file_name();
            if ALWAYS_SKIP.iter().any(|skip| name == *skip) {
                continue;
            }
            let absolute = entry.path();
            let relative = absolute
                .strip_prefix(root)
                .unwrap_or(&absolute)
                .to_path_buf();
            let Ok(kind) = entry.file_type() else {
                continue;
            };
            let directory_entry = kind.is_dir();
            if ignores
                .matched_path_or_any_parents(&relative, directory_entry)
                .is_ignore()
            {
                continue;
            }
            output.push(WalkEntry {
                absolute: absolute.clone(),
                relative,
                directory: directory_entry,
                symlink: kind.is_symlink(),
            });
            if recursive && directory_entry && !kind.is_symlink() {
                queue.push_back(absolute);
            }
        }
    }
    Ok(output)
}

fn load_ignore(root: &Path) -> Gitignore {
    let mut builder = GitignoreBuilder::new(root);
    let _ = builder.add(root.join(".gitignore"));
    builder.build().unwrap_or_else(|_| Gitignore::empty())
}

fn search_path(
    matcher: &RegressMatcher,
    entry: &WalkEntry,
    limit: usize,
) -> Result<(Vec<Value>, bool), ExeoraError> {
    let path = relative_string(&entry.relative);
    let mut rows = Vec::new();
    let mut exceeded = false;
    let sink = sinks::Bytes(|line_number: u64, bytes: &[u8]| {
        if rows.len() >= limit {
            exceeded = true;
            return Ok(false);
        }
        let bytes = bytes.strip_suffix(b"\n").unwrap_or(bytes);
        let text = String::from_utf8_lossy(bytes);
        rows.push(json!({ "path": path, "line": line_number, "text": utf16_prefix(&text, 500) }));
        Ok(true)
    });
    SearcherBuilder::new()
        .line_number(true)
        .bom_sniffing(false)
        .binary_detection(BinaryDetection::quit(b'\0'))
        .build()
        .search_path(matcher, &entry.absolute, sink)
        .map_err(|error| ExeoraError::tool(error.to_string()))?;
    Ok((rows, exceeded))
}

fn unique_match(
    content: &str,
    old: &str,
    path: &Path,
) -> Result<(String, usize, usize), ExeoraError> {
    let finder = memmem::Finder::new(old);
    let hits: Vec<usize> = finder.find_iter(content.as_bytes()).take(2).collect();
    if hits.len() == 1 {
        return Ok((content.to_owned(), hits[0], old.len()));
    }
    let fuzzy_content: String = content
        .nfkc()
        .collect::<String>()
        .lines()
        .map(str::trim_end)
        .collect::<Vec<_>>()
        .join("\n");
    let fuzzy_old: String = old
        .nfkc()
        .collect::<String>()
        .lines()
        .map(str::trim_end)
        .collect::<Vec<_>>()
        .join("\n");
    let fuzzy_hits: Vec<usize> = memmem::Finder::new(&fuzzy_old)
        .find_iter(fuzzy_content.as_bytes())
        .take(2)
        .collect();
    match fuzzy_hits.as_slice() {
        [index] => Ok((fuzzy_content, *index, fuzzy_old.len())),
        [] => Err(ExeoraError::tool(format!(
            "Could not find the requested text in {}.",
            relative_string(path)
        ))),
        _ => Err(ExeoraError::tool(format!(
            "The requested text appears more than once in {}. Include surrounding lines to make it unique.",
            relative_string(path)
        ))),
    }
}

fn truncate_complete_lines(text: &str, max: usize) -> (String, bool) {
    if text.len() <= max {
        return (text.to_owned(), false);
    }
    let mut end = 0;
    for (index, line) in text.split('\n').enumerate() {
        let cost = line.len() + usize::from(index > 0);
        if end + cost > max {
            break;
        }
        end += cost;
    }
    (text[..end].to_owned(), true)
}

fn utf16_prefix(text: &str, max: usize) -> String {
    let mut units = 0;
    text.chars()
        .take_while(|ch| {
            let next = units + ch.len_utf16();
            if next > max {
                false
            } else {
                units = next;
                true
            }
        })
        .collect()
}
fn compile_glob(pattern: Option<&str>) -> Result<Option<GlobMatcher>, ExeoraError> {
    pattern
        .map(|value| {
            Glob::new(value)
                .map(|glob| glob.compile_matcher())
                .map_err(|error| ExeoraError::new(ErrorCode::InvalidArguments, error.to_string()))
        })
        .transpose()
}
fn open_root(root: &Path) -> Result<Dir, ExeoraError> {
    Dir::open_ambient_dir(root, ambient_authority())
        .map_err(|error| ExeoraError::tool(error.to_string()))
}
fn parse<T: for<'de> Deserialize<'de>>(value: Value) -> Result<T, ExeoraError> {
    serde_json::from_value(value)
        .map_err(|error| ExeoraError::new(ErrorCode::InvalidArguments, error.to_string()))
}
fn join_error(error: tokio::task::JoinError) -> ExeoraError {
    ExeoraError::tool(error.to_string())
}