1use super::*;
4
5pub(crate) fn head_str(s: &str, max: usize) -> &str {
7 let mut c = max.min(s.len());
8 while c > 0 && !s.is_char_boundary(c) {
9 c -= 1;
10 }
11 s.get(..c).unwrap_or("")
12}
13
14pub(crate) fn unquote(v: &Value) -> String {
15 let s = v.to_string();
16 if s.starts_with('"') && s.ends_with('"') {
17 s.get(1..s.len() - 1).map(String::from).unwrap_or(s)
18 } else {
19 s
20 }
21}
22
23pub(crate) fn resolve_path(env: &Env, path: &str) -> Result<String, String> {
24 let mut abs_path = if path.starts_with('/') {
25 String::from(path)
26 } else {
27 if let Some(Value::Str(cwd)) = env.get("cwd") {
28 if cwd.ends_with('/') {
29 alloc::format!("{}{}", cwd, path)
30 } else {
31 alloc::format!("{}/{}", cwd, path)
32 }
33 } else {
34 alloc::format!("/user/{}", path) }
36 };
37
38 if let Some(sandbox) = &env.sandbox {
40 if let Some(safe_path) = sandbox.resolve_path(&abs_path) {
41 abs_path = safe_path;
42 } else {
43 return Err(alloc::format!(
44 "Permission denied: Access to '{}' is restricted by the sandbox",
45 abs_path
46 ));
47 }
48 }
49
50 Ok(abs_path)
51}
52
53pub(crate) fn builtin_ls(env: &mut Env, args: &[AST]) -> Result<Value, String> {
54 let vals = eval_args(env, args)?;
55 let mut show_hidden = false;
56 let mut show_details = false;
57 let mut target_dir = if let Some(Value::Str(c)) = env.get("cwd") {
58 c.clone()
59 } else {
60 String::from("/user/")
61 };
62
63 for val in vals {
64 match val {
65 Value::Str(s) => {
66 let unquoted = unquote(&Value::Str(s));
67 if unquoted.starts_with('-') {
68 if unquoted.contains('a') {
69 show_hidden = true;
70 }
71 if unquoted.contains('l') {
72 show_details = true;
73 }
74 } else {
75 target_dir = unquoted;
76 }
77 }
78 _ => return Err(String::from("Invalid argument for ls")),
79 }
80 }
81
82 let safe_cwd = resolve_path(env, &target_dir)?;
83 let fs = crate::kernel::fs::get_fs();
84 let files = fs.list_dir(&safe_cwd);
85 let mut out = alloc::format!("Listing {}:\n", safe_cwd);
86 for file in files {
87 let name = file.get_filename();
88 let simple_name = if let Some(idx) = name.rfind('/') {
89 name.get(idx + 1..).unwrap_or(name)
90 } else {
91 name
92 };
93 if !show_hidden && simple_name.starts_with('.') {
94 continue;
95 }
96 let f_size = file.size;
97 if show_details {
98 out.push_str(&alloc::format!(
99 " - {} ({} bytes) labels:[{}]\n",
100 simple_name,
101 f_size,
102 file.get_labels()
103 ));
104 } else {
105 out.push_str(&alloc::format!(" - {} ({})\n", simple_name, f_size));
106 }
107 }
108 Ok(Value::Str(out))
109}
110
111pub(crate) fn builtin_cd(env: &mut Env, args: &[AST]) -> Result<Value, String> {
112 if args.is_empty() {
113 return Err(String::from("USAGE: cd(\"path\")"));
114 }
115 let path = unquote(&eval(env, &args[0])?);
116 let new_path = resolve_path(env, &path)?;
117 env.set(String::from("cwd"), Value::Str(new_path.clone()));
118 Ok(Value::Str(alloc::format!("Changed dir to {}", new_path)))
119}
120
121pub(crate) fn builtin_pwd(env: &mut Env, _args: &[AST]) -> Result<Value, String> {
122 let cwd = if let Some(Value::Str(c)) = env.get("cwd") {
123 c.clone()
124 } else {
125 String::from("/user/")
126 };
127 Ok(Value::Str(cwd))
128}
129
130pub(crate) fn builtin_mkdir(env: &mut Env, args: &[AST]) -> Result<Value, String> {
131 let vals = eval_args(env, args)?;
132 if vals.is_empty() {
133 return Err(String::from("USAGE: mkdir(\"path\")"));
134 }
135 let raw_path = unquote(&vals[0]);
136 let path = resolve_path(env, &raw_path)?;
137
138 let keep_file = if path.ends_with('/') {
139 alloc::format!("{}.keep", path)
140 } else {
141 alloc::format!("{}/.keep", path)
142 };
143
144 let fs = crate::kernel::fs::get_fs();
145 if fs.save_file(&keep_file, &[], "dir").is_ok() {
146 Ok(Value::Str(alloc::format!(
147 "SUCCESS: Created directory '{}'",
148 path
149 )))
150 } else {
151 Err(String::from("ERROR: Failed to create directory"))
152 }
153}
154
155pub(crate) fn builtin_cp(env: &mut Env, args: &[AST]) -> Result<Value, String> {
156 let vals = eval_args(env, args)?;
157 if vals.len() < 2 {
158 return Err(String::from("USAGE: cp(\"src\" \"dst\")"));
159 }
160 let src_raw = unquote(&vals[0]);
161 let dst_raw = unquote(&vals[1]);
162 let src_path = resolve_path(env, &src_raw)?;
163 let dst_path = resolve_path(env, &dst_raw)?;
164
165 let fs = crate::kernel::fs::get_fs();
166 match fs.read_file_checked(&src_path) {
167 Ok(Some((meta, content))) => {
168 if fs.save_file(&dst_path, &content, meta.get_labels()).is_ok() {
169 Ok(Value::Str(alloc::format!(
170 "SUCCESS: Copied '{}' to '{}'",
171 src_path,
172 dst_path
173 )))
174 } else {
175 Err(String::from("ERROR: Failed to save destination file"))
176 }
177 }
178 Ok(None) => Err(alloc::format!(
179 "ERROR: Source file '{}' not found",
180 src_path
181 )),
182 Err(e) => Err(alloc::format!(
183 "ERROR: Failed to read source file '{}': {}",
184 src_path,
185 e
186 )),
187 }
188}
189
190pub(crate) fn builtin_mv(env: &mut Env, args: &[AST]) -> Result<Value, String> {
191 let vals = eval_args(env, args)?;
192 if vals.len() < 2 {
193 return Err(String::from("USAGE: mv(\"src\" \"dst\")"));
194 }
195 let src_raw = unquote(&vals[0]);
196 let dst_raw = unquote(&vals[1]);
197 let src_path = resolve_path(env, &src_raw)?;
198 let dst_path = resolve_path(env, &dst_raw)?;
199
200 let fs = crate::kernel::fs::get_fs();
201 if let Ok(()) = fs.rename_file(&src_path, &dst_path) {
203 return Ok(Value::Str(alloc::format!(
204 "SUCCESS: Moved '{}' to '{}'",
205 src_path,
206 dst_path
207 )));
208 }
209
210 match fs.read_file_checked(&src_path) {
212 Ok(Some((meta, content))) => {
213 if fs.save_file(&dst_path, &content, meta.get_labels()).is_ok() {
214 if let Err(e) = fs.delete_file(&src_path) {
217 return Err(alloc::format!(
218 "ERROR: Copied to '{}' but could not remove '{}': {}",
219 dst_path,
220 src_path,
221 e
222 ));
223 }
224 Ok(Value::Str(alloc::format!(
225 "SUCCESS: Moved '{}' to '{}'",
226 src_path,
227 dst_path
228 )))
229 } else {
230 Err(String::from("ERROR: Failed to save destination file"))
231 }
232 }
233 Ok(None) => Err(alloc::format!(
234 "ERROR: Source file '{}' not found",
235 src_path
236 )),
237 Err(e) => Err(alloc::format!(
238 "ERROR: Failed to read source file '{}': {}",
239 src_path,
240 e
241 )),
242 }
243}
244
245pub(crate) fn builtin_rm(env: &mut Env, args: &[AST]) -> Result<Value, String> {
246 let vals = eval_args(env, args)?;
247 if vals.is_empty() {
248 return Err(String::from("USAGE: rm(\"path\")"));
249 }
250 let raw_path = unquote(&vals[0]);
251 let path = resolve_path(env, &raw_path)?;
252
253 let fs = crate::kernel::fs::get_fs();
254 if fs.delete_file(&path).is_ok() {
255 Ok(Value::Str(alloc::format!(
256 "SUCCESS: Removed file '{}'",
257 path
258 )))
259 } else {
260 Err(alloc::format!(
261 "ERROR: Failed to remove file '{}' or not found",
262 path
263 ))
264 }
265}
266
267pub(crate) fn builtin_cat(env: &mut Env, args: &[AST]) -> Result<Value, String> {
268 let vals = eval_args(env, args)?;
269 if vals.is_empty() {
270 return Err(String::from("USAGE: cat(\"path\"[, generation])"));
271 }
272 let raw_path = unquote(&vals[0]);
273 let path = resolve_path(env, &raw_path)?;
274
275 if let Some(v) = vals.get(1) {
277 let gen = arg_u64(v).ok_or_else(|| String::from("ERROR: Invalid generation"))?;
278 let _guard = crate::kernel::fs::FS_LOCK.lock();
279 let fs = crate::kernel::fs::get_fs();
280 return match fs.read_version(&path, gen) {
281 Ok(Some((_, content))) => String::from_utf8(content)
282 .map(Value::Str)
283 .map_err(|_| String::from("ERROR: Binary or invalid UTF-8 content")),
284 Ok(None) => Err(alloc::format!(
285 "ERROR: '{}' has no readable version at generation {} (see versions)",
286 path, gen
287 )),
288 Err(e) => Err(alloc::format!("ERROR: Failed to read '{}' at generation {}: {}", path, gen, e)),
289 };
290 }
291
292 let fs = crate::kernel::fs::get_fs();
293 match fs.read_file_checked(&path) {
294 Ok(Some((_, content))) => {
295 let content_str = core::str::from_utf8(&content)
296 .map_err(|_| String::from("ERROR: Binary or invalid UTF-8 content"))?;
297 Ok(Value::Str(String::from(content_str)))
298 }
299 Ok(None) => Err(alloc::format!("ERROR: File '{}' not found", path)),
300 Err(e) => Err(alloc::format!("ERROR: Failed to read file '{}': {}", path, e)),
301 }
302}
303
304pub(crate) fn builtin_grep(env: &mut Env, args: &[AST]) -> Result<Value, String> {
305 let vals = eval_args(env, args)?;
306 if vals.len() < 2 {
307 return Err(String::from("USAGE: grep(\"pattern\" \"path\")"));
308 }
309 let pattern = unquote(&vals[0]);
310 let raw_path = unquote(&vals[1]);
311 let path = resolve_path(env, &raw_path)?;
312
313 let fs = crate::kernel::fs::get_fs();
314 match fs.read_file_checked(&path) {
315 Ok(Some((_, content))) => {
316 let content_str = core::str::from_utf8(&content)
317 .map_err(|_| String::from("ERROR: Binary or invalid UTF-8 content"))?;
318
319 let mut matching_lines = String::new();
320 for (i, line) in content_str.lines().enumerate() {
321 if line.contains(&pattern) {
322 matching_lines.push_str(&alloc::format!("{}: {}\n", i + 1, line));
323 }
324 }
325 Ok(Value::Str(matching_lines))
326 }
327 Ok(None) => Err(alloc::format!("ERROR: File '{}' not found", path)),
328 Err(e) => Err(alloc::format!("ERROR: Failed to read file '{}': {}", path, e)),
329 }
330}
331
332pub(crate) fn builtin_head(env: &mut Env, args: &[AST]) -> Result<Value, String> {
333 let vals = eval_args(env, args)?;
334 if vals.is_empty() {
335 return Err(String::from("USAGE: head(\"path\" [lines])"));
336 }
337 let raw_path = unquote(&vals[0]);
338 let path = resolve_path(env, &raw_path)?;
339
340 let mut num_lines = 10;
341 if vals.len() > 1 {
342 if let Value::Num(n) = &vals[1] {
343 num_lines = n.to_string().parse::<usize>().unwrap_or(10);
344 }
345 }
346
347 let fs = crate::kernel::fs::get_fs();
348 match fs.read_file_checked(&path) {
349 Ok(Some((_, content))) => {
350 let content_str = core::str::from_utf8(&content)
351 .map_err(|_| String::from("ERROR: Binary or invalid UTF-8 content"))?;
352
353 let mut out = String::new();
354 for line in content_str.lines().take(num_lines) {
355 out.push_str(line);
356 out.push('\n');
357 }
358 Ok(Value::Str(out))
359 }
360 Ok(None) => Err(alloc::format!("ERROR: File '{}' not found", path)),
361 Err(e) => Err(alloc::format!("ERROR: Failed to read file '{}': {}", path, e)),
362 }
363}
364
365pub(crate) fn builtin_tail(env: &mut Env, args: &[AST]) -> Result<Value, String> {
366 let vals = eval_args(env, args)?;
367 if vals.is_empty() {
368 return Err(String::from("USAGE: tail(\"path\" [lines])"));
369 }
370 let raw_path = unquote(&vals[0]);
371 let path = resolve_path(env, &raw_path)?;
372
373 let mut num_lines = 10;
374 if vals.len() > 1 {
375 if let Value::Num(n) = &vals[1] {
376 num_lines = n.to_string().parse::<usize>().unwrap_or(10);
377 }
378 }
379
380 let fs = crate::kernel::fs::get_fs();
381 match fs.read_file_checked(&path) {
382 Ok(Some((_, content))) => {
383 let content_str = core::str::from_utf8(&content)
384 .map_err(|_| String::from("ERROR: Binary or invalid UTF-8 content"))?;
385
386 let lines: Vec<&str> = content_str.lines().collect();
387 let start = if lines.len() > num_lines {
388 lines.len() - num_lines
389 } else {
390 0
391 };
392
393 let mut out = String::new();
394 for line in &lines[start..] {
395 out.push_str(line);
396 out.push('\n');
397 }
398 Ok(Value::Str(out))
399 }
400 Ok(None) => Err(alloc::format!("ERROR: File '{}' not found", path)),
401 Err(e) => Err(alloc::format!("ERROR: Failed to read file '{}': {}", path, e)),
402 }
403}
404
405pub(crate) fn builtin_save(env: &mut Env, args: &[AST]) -> Result<Value, String> {
406 let vals = eval_args(env, args)?;
407 if vals.len() < 2 {
408 return Err(String::from("USAGE: save(\"name\" \"data\" [\"labels\"])"));
409 }
410 let raw_filename = unquote(&vals[0]);
411 let filename = resolve_path(env, &raw_filename)?;
412 let content = unquote(&vals[1]);
413 let labels = if vals.len() > 2 {
414 unquote(&vals[2])
415 } else {
416 String::new()
417 };
418
419 let fs = crate::kernel::fs::get_fs();
420 if fs.save_file(&filename, content.as_bytes(), &labels).is_ok() {
421 Ok(Value::Str(alloc::format!(
422 "SUCCESS: Saved file '{}'",
423 filename
424 )))
425 } else {
426 Err(String::from("ERROR: Failed to save file"))
427 }
428}
429
430pub(crate) fn builtin_show(env: &mut Env, args: &[AST]) -> Result<Value, String> {
431 let vals = eval_args(env, args)?;
432 if vals.is_empty() {
433 return Err(String::from("USAGE: show(\"filename\")"));
434 }
435 let raw_filename = unquote(&vals[0]);
436 let filename = resolve_path(env, &raw_filename)?;
437
438 let fs = crate::kernel::fs::get_fs();
439 match fs.read_file_checked(&filename) {
440 Ok(Some((meta, content))) => {
441 let content_str = unsafe { core::str::from_utf8_unchecked(&content) };
442 Ok(Value::Str(alloc::format!(
443 "FILE: '{}' | LABELS: [{}]\nDATA: {}",
444 filename,
445 meta.get_labels(),
446 content_str
447 )))
448 }
449 Ok(None) => Err(alloc::format!("ERROR: File '{}' not found", filename)),
450 Err(e) => Err(alloc::format!(
451 "ERROR: Failed to read file '{}': {}",
452 filename,
453 e
454 )),
455 }
456}
457
458pub(crate) fn builtin_find(env: &mut Env, args: &[AST]) -> Result<Value, String> {
459 let vals = eval_args(env, args)?;
460 if vals.is_empty() {
461 return Err(String::from("USAGE: find(\"label1[,label2]\" [\"and\"|\"or\"])"));
462 }
463 let label_query = unquote(&vals[0]);
464 let mode = if vals.len() > 1 {
465 unquote(&vals[1]).to_ascii_lowercase()
466 } else {
467 String::from("and")
468 };
469 let match_all = mode != "or";
470
471 let label_slices: alloc::vec::Vec<&str> = label_query
472 .split(',')
473 .map(|s| s.trim())
474 .filter(|s| !s.is_empty())
475 .collect();
476
477 if label_slices.is_empty() {
478 return Err(String::from("ERROR: No valid search labels provided"));
479 }
480
481 let fs = crate::kernel::fs::get_fs();
482 let files = fs.find_by_labels(&label_slices, match_all);
483 if !files.is_empty() {
484 let mut out = alloc::format!(
485 "FOUND {} file(s) for label(s) [{}] (mode: {}):\n",
486 files.len(),
487 label_query,
488 if match_all { "AND" } else { "OR" }
489 );
490 for file in files {
491 let f_size = file.size;
492 out.push_str(&alloc::format!(
493 " - {} ({} bytes) labels:[{}]\n",
494 file.get_filename(),
495 f_size,
496 file.get_labels()
497 ));
498 }
499 Ok(Value::Str(out))
500 } else {
501 Ok(Value::Str(alloc::format!(
502 "No files found matching label(s) [{}]",
503 label_query
504 )))
505 }
506}
507
508pub(crate) fn builtin_addlabel(env: &mut Env, args: &[AST]) -> Result<Value, String> {
509 let vals = eval_args(env, args)?;
510 if vals.len() < 2 {
511 return Err(String::from("USAGE: addlabel(\"filename\" \"label\")"));
512 }
513 let raw_filename = unquote(&vals[0]);
514 let filename = resolve_path(env, &raw_filename)?;
515 let new_label = unquote(&vals[1]);
516
517 let fs = crate::kernel::fs::get_fs();
518 let all_files = fs.list_files();
519 let meta_opt = all_files.into_iter().find(|m| m.get_filename() == filename);
520 let Some(meta) = meta_opt else {
521 return Err(alloc::format!("ERROR: File '{}' not found", filename));
522 };
523
524 let old_labels = meta.get_labels();
525 let labels_list: alloc::vec::Vec<&str> = old_labels.split(',').map(|s| s.trim()).collect();
526 if labels_list.contains(&new_label.as_str()) {
527 return Ok(Value::Str(alloc::format!(
528 "Label '{}' already exists on '{}'",
529 new_label,
530 filename
531 )));
532 }
533
534 let joined_labels = if old_labels.is_empty() {
535 new_label.clone()
536 } else {
537 alloc::format!("{},{}", old_labels, new_label)
538 };
539
540 match fs.update_labels(&filename, &joined_labels) {
541 Ok(()) => Ok(Value::Str(alloc::format!(
542 "SUCCESS: Added label '{}' to '{}'",
543 new_label,
544 filename
545 ))),
546 Err(e) => Err(alloc::format!(
547 "ERROR: Failed to update labels for '{}': {}",
548 filename,
549 e
550 )),
551 }
552}
553
554pub(crate) fn builtin_setlabel(env: &mut Env, args: &[AST]) -> Result<Value, String> {
555 let vals = eval_args(env, args)?;
556 if vals.len() < 2 {
557 return Err(String::from("USAGE: setlabel(\"filename\" \"labels\")"));
558 }
559 let raw_filename = unquote(&vals[0]);
560 let filename = resolve_path(env, &raw_filename)?;
561 let new_labels = unquote(&vals[1]);
562
563 let fs = crate::kernel::fs::get_fs();
564 match fs.update_labels(&filename, &new_labels) {
565 Ok(()) => Ok(Value::Str(alloc::format!(
566 "SUCCESS: Set labels for '{}' to [{}]",
567 filename,
568 new_labels
569 ))),
570 Err(e) => Err(alloc::format!(
571 "ERROR: Failed to set labels for '{}': {}",
572 filename,
573 e
574 )),
575 }
576}
577
578pub(crate) fn builtin_labels(env: &mut Env, args: &[AST]) -> Result<Value, String> {
579 let vals = eval_args(env, args)?;
580 let fs = crate::kernel::fs::get_fs();
581 if vals.is_empty() {
582 let all_labels = fs.list_all_labels();
583 if all_labels.is_empty() {
584 return Ok(Value::Str(String::from("No labels found in filesystem.")));
585 }
586 let mut out = alloc::format!("Total {} unique label(s):\n", all_labels.len());
587 for l in all_labels {
588 out.push_str(&alloc::format!(" - {}\n", l));
589 }
590 Ok(Value::Str(out))
591 } else {
592 let raw_filename = unquote(&vals[0]);
593 let filename = resolve_path(env, &raw_filename)?;
594 let all_files = fs.list_files();
595 let meta_opt = all_files.into_iter().find(|m| m.get_filename() == filename);
596 match meta_opt {
597 Some(meta) => Ok(Value::Str(alloc::format!(
598 "Labels for '{}': [{}]",
599 filename,
600 meta.get_labels()
601 ))),
602 None => Err(alloc::format!("ERROR: File '{}' not found", filename)),
603 }
604 }
605}
606
607pub(crate) fn builtin_rename(env: &mut Env, args: &[AST]) -> Result<Value, String> {
608 builtin_mv(env, args)
609}
610
611pub(crate) fn builtin_truncate(env: &mut Env, args: &[AST]) -> Result<Value, String> {
612 let vals = eval_args(env, args)?;
613 if vals.len() < 2 {
614 return Err(String::from("USAGE: truncate(\"filename\" size)"));
615 }
616 let raw_filename = unquote(&vals[0]);
617 let filename = resolve_path(env, &raw_filename)?;
618 let size = match &vals[1] {
619 Value::Num(n) => {
620 let s = n.to_string();
621 s.parse::<usize>().map_err(|_| String::from("ERROR: Invalid size"))?
622 }
623 v => {
624 let s = unquote(v);
625 s.parse::<usize>().map_err(|_| String::from("ERROR: Invalid size"))?
626 }
627 };
628
629 let fs = crate::kernel::fs::get_fs();
630 match fs.truncate_file(&filename, size) {
631 Ok(()) => Ok(Value::Str(alloc::format!(
632 "SUCCESS: Truncated '{}' to {} bytes",
633 filename,
634 size
635 ))),
636 Err(e) => Err(alloc::format!("ERROR: Failed to truncate '{}': {}", filename, e)),
637 }
638}
639
640pub(crate) fn builtin_stat(env: &mut Env, args: &[AST]) -> Result<Value, String> {
641 let vals = eval_args(env, args)?;
642 if vals.is_empty() {
643 return Err(String::from("USAGE: stat(\"filename\")"));
644 }
645 let raw_filename = unquote(&vals[0]);
646 let filename = resolve_path(env, &raw_filename)?;
647
648 let fs = crate::kernel::fs::get_fs();
649 match fs.stat_file(&filename) {
650 Ok(st) => {
651 let mut dict = alloc::collections::BTreeMap::new();
652 dict.insert(String::from("filename"), Value::Str(st.filename));
653 dict.insert(String::from("size"), Value::Num(BigInt::from_i64(st.size as i64)));
654 dict.insert(String::from("labels"), Value::Str(st.labels));
655 dict.insert(String::from("extent_count"), Value::Num(BigInt::from_i64(st.extent_count as i64)));
656 dict.insert(String::from("sector_count"), Value::Num(BigInt::from_i64(st.sector_count as i64)));
657 dict.insert(String::from("has_overflow"), Value::Bool(st.has_overflow));
658 Ok(Value::Dict(dict))
659 }
660 Err(e) => Err(alloc::format!("ERROR: Failed to stat '{}': {}", filename, e)),
661 }
662}
663
664pub(crate) fn builtin_corrupt(env: &mut Env, args: &[AST]) -> Result<Value, String> {
665 let vals = eval_args(env, args)?;
666 if vals.is_empty() {
667 return Err(String::from("USAGE: corrupt(sector)"));
668 }
669
670 let sector = match &vals[0] {
671 Value::Num(n) => {
672 let s = n.to_string();
673 s.parse::<usize>().unwrap_or(0)
674 }
675 v => {
676 let s = unquote(v);
677 s.parse::<usize>().unwrap_or(0)
678 }
679 };
680
681 let fs = crate::kernel::fs::get_fs();
682 if fs.device.force_corrupt_raw_sector(sector).is_ok() {
683 Ok(Value::Str(alloc::format!(
684 "DEBUG: Sector {} on RAMDisk corrupted successfully!",
685 sector
686 )))
687 } else {
688 Err(String::from("ERROR: Failed to corrupt sector"))
689 }
690}
691
692fn arg_u64(v: &Value) -> Option<u64> {
695 match v {
696 Value::Num(n) => n.to_string().parse::<u64>().ok(),
697 v => unquote(v).parse::<u64>().ok(),
698 }
699}
700
701pub(crate) fn builtin_versions(env: &mut Env, args: &[AST]) -> Result<Value, String> {
703 let vals = eval_args(env, args)?;
704 if vals.is_empty() {
705 return Err(String::from("USAGE: versions(\"filename\")"));
706 }
707 let path = resolve_path(env, &unquote(&vals[0]))?;
708 let _guard = crate::kernel::fs::FS_LOCK.lock();
709 let fs = crate::kernel::fs::get_fs();
710 let vs = fs.list_versions(&path).map_err(|e| alloc::format!("ERROR: versions '{}': {}", path, e))?;
711 let mut out = Vec::new();
712 for v in vs {
713 let mut d = alloc::collections::BTreeMap::new();
714 d.insert(String::from("generation"), Value::Num(BigInt::from_i64(v.generation as i64)));
715 d.insert(String::from("mtime"), Value::Num(BigInt::from_i64(v.mtime as i64)));
716 d.insert(String::from("size"), Value::Num(BigInt::from_i64(v.size as i64)));
717 d.insert(String::from("deleted"), Value::Bool(v.deleted));
718 d.insert(String::from("labels"), Value::Str(v.labels));
719 out.push(Value::Dict(d));
720 }
721 Ok(Value::List(out))
722}
723
724pub(crate) fn builtin_restore(env: &mut Env, args: &[AST]) -> Result<Value, String> {
726 let vals = eval_args(env, args)?;
727 if vals.len() < 2 {
728 return Err(String::from("USAGE: restore(\"filename\", generation)"));
729 }
730 let path = resolve_path(env, &unquote(&vals[0]))?;
731 let gen = arg_u64(&vals[1]).ok_or_else(|| String::from("ERROR: Invalid generation"))?;
732 let _guard = crate::kernel::fs::FS_LOCK.lock();
733 let fs = crate::kernel::fs::get_fs();
734 fs.restore_version(&path, gen)
735 .map(|()| Value::Str(alloc::format!("SUCCESS: Restored '{}' from generation {}", path, gen)))
736 .map_err(|e| alloc::format!("ERROR: restore '{}': {}", path, e))
737}
738
739pub(crate) fn builtin_snapshot(env: &mut Env, args: &[AST]) -> Result<Value, String> {
741 let vals = eval_args(env, args)?;
742 let name = vals.first().map(unquote).unwrap_or_default();
743 let _guard = crate::kernel::fs::FS_LOCK.lock();
744 let fs = crate::kernel::fs::get_fs();
745 fs.create_snapshot(&name)
746 .map(|g| Value::Num(BigInt::from_i64(g as i64)))
747 .map_err(|e| alloc::format!("ERROR: snapshot: {}", e))
748}
749
750pub(crate) fn builtin_snapshots(_env: &mut Env, _args: &[AST]) -> Result<Value, String> {
752 let _guard = crate::kernel::fs::FS_LOCK.lock();
753 let fs = crate::kernel::fs::get_fs();
754 let snaps = fs.list_snapshots().map_err(|e| alloc::format!("ERROR: snapshots: {}", e))?;
755 let mut out = Vec::new();
756 for sn in snaps {
757 let mut d = alloc::collections::BTreeMap::new();
758 d.insert(String::from("generation"), Value::Num(BigInt::from_i64(sn.generation as i64)));
759 d.insert(String::from("time"), Value::Num(BigInt::from_i64(sn.time as i64)));
760 d.insert(String::from("name"), Value::Str(sn.name));
761 d.insert(String::from("pinned"), Value::Bool(sn.pinned));
762 out.push(Value::Dict(d));
763 }
764 Ok(Value::List(out))
765}
766
767pub(crate) fn builtin_pin(env: &mut Env, args: &[AST]) -> Result<Value, String> {
769 let vals = eval_args(env, args)?;
770 let gen = vals.first().and_then(arg_u64).ok_or_else(|| String::from("USAGE: pin(generation[, true|false])"))?;
771 let on = !matches!(vals.get(1), Some(Value::Bool(false)));
772 let _guard = crate::kernel::fs::FS_LOCK.lock();
773 let fs = crate::kernel::fs::get_fs();
774 let max = fs.max_pins();
775 fs.pin_snapshot(gen, on)
776 .map(|()| Value::Str(alloc::format!("SUCCESS: snapshot {} {} (max pins {})", gen, if on { "pinned" } else { "unpinned" }, max)))
777 .map_err(|e| alloc::format!("ERROR: pin {}: {}", gen, e))
778}
779
780pub(crate) fn builtin_gc(_env: &mut Env, _args: &[AST]) -> Result<Value, String> {
782 let _guard = crate::kernel::fs::FS_LOCK.lock();
783 let fs = crate::kernel::fs::get_fs();
784 let r = fs.collect_garbage().map_err(|e| alloc::format!("ERROR: gc: {}", e))?;
785 Ok(Value::Str(alloc::format!(
786 "GC: freed {} sectors, dropped {} old deletions and {} unused chunk index entries",
787 r.freed, r.tombstones_dropped, r.index_entries_dropped
788 )))
789}
790
791pub(crate) fn builtin_fsck(_env: &mut Env, _args: &[AST]) -> Result<Value, String> {
792 let _guard = crate::kernel::fs::FS_LOCK.lock();
793 let fs = crate::kernel::fs::get_fs();
794 match fs.fsck() {
795 Ok(report) => {
796 let status_str = if report.is_healthy { "HEALTHY (PASS)" } else { "ATTENTION (CORRUPTED SECTORS DETECTED)" };
797 Ok(Value::Str(alloc::format!(
798 "SylFS Integrity Report:\n\
799 - Status: {}\n\
800 - Total Usable Sectors: {}\n\
801 - Used Sectors: {}\n\
802 - Files Count: {}\n\
803 - Extents Total: {}\n\
804 - Indexed Nodes: {}\n\
805 - Corrupted Sectors: {}\n\
806 - Unallocated References: {}\n\
807 - Double References: {}\n\
808 - Leaked Sectors: {}",
809 status_str,
810 report.total_sectors,
811 report.used_sectors,
812 report.file_count,
813 report.extent_count,
814 report.btree_node_count,
815 report.corrupted_sectors,
816 report.unallocated_refs,
817 report.double_refs,
818 report.leaked_sectors
819 )))
820 }
821 Err(e) => Err(alloc::format!("ERROR: fsck failed: {}", e)),
822 }
823}
824
825pub(crate) fn builtin_keymap(env: &mut Env, args: &[AST]) -> Result<Value, String> {
826 let vals = eval_args(env, args)?;
827 if let Some(ctx) = &env.context {
828 if vals.is_empty() {
829 let app = crate::apps::keymap::KeymapApp::new();
830 let win = crate::kernel::window_mgr::Window::new(
831 200,
832 150,
833 400,
834 500,
835 "Keymap & Checker",
836 alloc::boxed::Box::new(app),
837 );
838 crate::kernel::window_mgr::get_instance().add_window(win);
839 return Ok(Value::Str(String::from("Launched Keymap App")));
840 }
841 let layout_name = unquote(&vals[0]);
842 if let Some(layout) = crate::kernel::keyboard::KeyboardLayout::parse(&layout_name) {
843 unsafe {
844 let kbd = &mut **ctx;
845 kbd.set_layout(layout);
846 }
847 Ok(Value::Str(alloc::format!(
848 "SUCCESS: Keyboard layout switched to {}",
849 layout_name
850 )))
851 } else {
852 Err(String::from("USAGE: keymap(\"us\"|\"js\")"))
853 }
854 } else {
855 Err(String::from("OS Context not available for keymap command"))
856 }
857}
858
859