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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
use crate::console::Console;
use crate::storage::Storage;
use async_trait::async_trait;
use endbasic_core::ast::{ArgSep, ArgSpan, BuiltinCallSpan, Value, VarType};
use endbasic_core::exec::Machine;
use endbasic_core::syms::{
CallError, CallableMetadata, CallableMetadataBuilder, Command, CommandResult,
};
use std::cell::RefCell;
use std::cmp;
use std::io;
use std::rc::Rc;
use std::str;
use time::format_description;
use super::time_format_error_to_io_error;
const CATEGORY: &str = "File system
The EndBASIC storage subsystem is organized as a collection of drives, each identified by a \
case-insensitive name. Drives can be backed by a multitude of file systems with different \
behaviors, and their targets are specified as URIs. Special targets include: memory://, which \
points to an in-memory read/write drive; and demos://, which points to a read-only drive with \
sample programs. Other targets may be available such as file:// to access a local directory or \
local:// to access web-local storage, depending on the context. The output of the MOUNT command \
can help to identify which targets are available.
All commands that operate with files take a path. Paths in EndBASIC can be of the form \
FILENAME.EXT, in which case they refer to a file in the current drive; or DRIVE:/FILENAME.EXT and \
DRIVE:FILENAME.EXT, in which case they refer to a file in the specified drive. Note that the \
slash before the file name is currently optional because EndBASIC does not support directories \
yet. Furthermore, if .EXT is missing, a .BAS extension is assumed.
Be aware that the commands below must be invoked using proper EndBASIC syntax. In particular, \
this means that path arguments must be double-quoted and multiple arguments have to be separated \
by a comma (not a space). If you have used commands like CD, DIR, or MOUNT in other contexts, \
this is likely to confuse you.
See the \"Stored program\" help topic for information on how to load, modify, and save programs.";
async fn show_dir(storage: &Storage, console: &mut dyn Console, path: &str) -> io::Result<()> {
let canonical_path = storage.make_canonical(path)?;
let files = storage.enumerate(path).await?;
let format = format_description::parse("[year]-[month]-[day] [hour]:[minute]")
.expect("Hardcoded format must be valid");
console.print("")?;
console.print(&format!(" Directory of {}", canonical_path))?;
console.print("")?;
console.print(" Modified Size Name")?;
let mut total_files = 0;
let mut total_bytes = 0;
for (name, details) in files.dirents() {
console.print(&format!(
" {} {:6} {}",
details.date.format(&format).map_err(time_format_error_to_io_error)?,
details.length,
name,
))?;
total_files += 1;
total_bytes += details.length;
}
if total_files > 0 {
console.print("")?;
}
console.print(&format!(" {} file(s), {} bytes", total_files, total_bytes))?;
if let (Some(disk_quota), Some(disk_free)) = (files.disk_quota(), files.disk_free()) {
console.print(&format!(" {} of {} bytes free", disk_free.bytes, disk_quota.bytes))?;
}
console.print("")?;
Ok(())
}
fn show_drives(storage: &Storage, console: &mut dyn Console) -> io::Result<()> {
let drive_info = storage.mounted();
let max_length = drive_info.keys().fold("Name".len(), |max, name| cmp::max(max, name.len()));
console.print("")?;
let filler = " ".repeat(max_length - "Name".len());
console.print(&format!(" Name{} Target", filler))?;
let num_drives = drive_info.len();
for (name, uri) in drive_info {
let filler = " ".repeat(max_length - name.len());
console.print(&format!(" {}{} {}", name, filler, uri))?;
}
console.print("")?;
console.print(&format!(" {} drive(s)", num_drives))?;
console.print("")?;
Ok(())
}
pub struct CdCommand {
metadata: CallableMetadata,
storage: Rc<RefCell<Storage>>,
}
impl CdCommand {
pub fn new(storage: Rc<RefCell<Storage>>) -> Rc<Self> {
Rc::from(Self {
metadata: CallableMetadataBuilder::new("CD", VarType::Void)
.with_syntax("path$")
.with_category(CATEGORY)
.with_description("Changes the current path.")
.build(),
storage,
})
}
}
#[async_trait(?Send)]
impl Command for CdCommand {
fn metadata(&self) -> &CallableMetadata {
&self.metadata
}
async fn exec(&self, span: &BuiltinCallSpan, machine: &mut Machine) -> CommandResult {
if span.args.len() != 1 {
return Err(CallError::SyntaxError);
}
let arg0 = span.args[0].expr.as_ref().expect("Single argument must be present");
match arg0.eval(machine.get_mut_symbols()).await? {
Value::Text(t) => {
self.storage.borrow_mut().cd(&t)?;
}
_ => {
return Err(CallError::ArgumentError(
arg0.start_pos(),
"CD requires a string as the path".to_owned(),
))
}
}
Ok(())
}
}
pub struct DirCommand {
metadata: CallableMetadata,
console: Rc<RefCell<dyn Console>>,
storage: Rc<RefCell<Storage>>,
}
impl DirCommand {
pub fn new(console: Rc<RefCell<dyn Console>>, storage: Rc<RefCell<Storage>>) -> Rc<Self> {
Rc::from(Self {
metadata: CallableMetadataBuilder::new("DIR", VarType::Void)
.with_syntax("[path$]")
.with_category(CATEGORY)
.with_description("Displays the list of files on the current or given path.")
.build(),
console,
storage,
})
}
}
#[async_trait(?Send)]
impl Command for DirCommand {
fn metadata(&self) -> &CallableMetadata {
&self.metadata
}
async fn exec(&self, span: &BuiltinCallSpan, machine: &mut Machine) -> CommandResult {
match span.args.as_slice() {
[] => {
show_dir(&self.storage.borrow(), &mut *self.console.borrow_mut(), "").await?;
Ok(())
}
[ArgSpan { expr: Some(path), sep: ArgSep::End, .. }] => {
match path.eval(machine.get_mut_symbols()).await? {
Value::Text(path) => {
show_dir(&self.storage.borrow(), &mut *self.console.borrow_mut(), &path)
.await?;
Ok(())
}
_ => {
return Err(CallError::ArgumentError(
path.start_pos(),
"DIR requires a string as the path".to_owned(),
))
}
}
}
_ => Err(CallError::SyntaxError),
}
}
}
pub struct MountCommand {
metadata: CallableMetadata,
console: Rc<RefCell<dyn Console>>,
storage: Rc<RefCell<Storage>>,
}
impl MountCommand {
pub fn new(console: Rc<RefCell<dyn Console>>, storage: Rc<RefCell<Storage>>) -> Rc<Self> {
Rc::from(Self {
metadata: CallableMetadataBuilder::new("MOUNT", VarType::Void)
.with_syntax("[target$ AS drive_name$]")
.with_category(CATEGORY)
.with_description(
"Lists the mounted drives or mounts a new drive.
With no arguments, prints a list of mounted drives and their targets.
With two arguments, mounts the drive_name$ to point to the target$. Drive names are specified \
without a colon at the end, and targets are given in the form of a URI.",
)
.build(),
console,
storage,
})
}
}
#[async_trait(?Send)]
impl Command for MountCommand {
fn metadata(&self) -> &CallableMetadata {
&self.metadata
}
async fn exec(&self, span: &BuiltinCallSpan, machine: &mut Machine) -> CommandResult {
match span.args.as_slice() {
[] => {
show_drives(&self.storage.borrow_mut(), &mut *self.console.borrow_mut())?;
Ok(())
}
[ArgSpan { expr: Some(target), sep: ArgSep::As, .. }, ArgSpan { expr: Some(name), sep: ArgSep::End, .. }] =>
{
let name = match name.eval(machine.get_mut_symbols()).await? {
Value::Text(t) => t,
_ => {
return Err(CallError::ArgumentError(
name.start_pos(),
"Drive name must be a string".to_owned(),
))
}
};
let target = match target.eval(machine.get_mut_symbols()).await? {
Value::Text(t) => t,
_ => {
return Err(CallError::ArgumentError(
target.start_pos(),
"Mount target must be a string".to_owned(),
))
}
};
self.storage.borrow_mut().mount(&name, &target)?;
Ok(())
}
_ => Err(CallError::SyntaxError),
}
}
}
pub struct PwdCommand {
metadata: CallableMetadata,
console: Rc<RefCell<dyn Console>>,
storage: Rc<RefCell<Storage>>,
}
impl PwdCommand {
pub fn new(console: Rc<RefCell<dyn Console>>, storage: Rc<RefCell<Storage>>) -> Rc<Self> {
Rc::from(Self {
metadata: CallableMetadataBuilder::new("PWD", VarType::Void)
.with_syntax("")
.with_category(CATEGORY)
.with_description(
"Prints the current working location.
If the EndBASIC path representing the current location is backed by a real path that is accessible \
by the underlying operating system, displays such path as well.",
)
.build(),
console,
storage,
})
}
}
#[async_trait(?Send)]
impl Command for PwdCommand {
fn metadata(&self) -> &CallableMetadata {
&self.metadata
}
async fn exec(&self, span: &BuiltinCallSpan, _machine: &mut Machine) -> CommandResult {
if !span.args.is_empty() {
return Err(CallError::SyntaxError);
}
let storage = self.storage.borrow();
let cwd = storage.cwd();
let system_cwd = storage.system_path(&cwd).expect("cwd must return a valid path");
let console = &mut *self.console.borrow_mut();
console.print("")?;
console.print(&format!(" Working directory: {}", cwd))?;
match system_cwd {
Some(path) => console.print(&format!(" System location: {}", path.display()))?,
None => console.print(" No system location available")?,
}
console.print("")?;
Ok(())
}
}
pub struct UnmountCommand {
metadata: CallableMetadata,
storage: Rc<RefCell<Storage>>,
}
impl UnmountCommand {
pub fn new(storage: Rc<RefCell<Storage>>) -> Rc<Self> {
Rc::from(Self {
metadata: CallableMetadataBuilder::new("UNMOUNT", VarType::Void)
.with_syntax("drive_name$")
.with_category(CATEGORY)
.with_description(
"Unmounts the given drive.
Drive names are specified without a colon at the end.",
)
.build(),
storage,
})
}
}
#[async_trait(?Send)]
impl Command for UnmountCommand {
fn metadata(&self) -> &CallableMetadata {
&self.metadata
}
async fn exec(&self, span: &BuiltinCallSpan, machine: &mut Machine) -> CommandResult {
if span.args.len() != 1 {
return Err(CallError::SyntaxError);
}
let arg0 = span.args[0].expr.as_ref().expect("Single argument must be present");
match arg0.eval(machine.get_mut_symbols()).await? {
Value::Text(t) => {
self.storage.borrow_mut().unmount(&t)?;
}
_ => {
return Err(CallError::ArgumentError(
arg0.start_pos(),
"Drive name must be a string".to_owned(),
))
}
}
Ok(())
}
}
pub fn add_all(
machine: &mut Machine,
console: Rc<RefCell<dyn Console>>,
storage: Rc<RefCell<Storage>>,
) {
machine.add_command(CdCommand::new(storage.clone()));
machine.add_command(DirCommand::new(console.clone(), storage.clone()));
machine.add_command(MountCommand::new(console.clone(), storage.clone()));
machine.add_command(PwdCommand::new(console.clone(), storage.clone()));
machine.add_command(UnmountCommand::new(storage));
}
#[cfg(test)]
mod tests {
use crate::storage::{DirectoryDriveFactory, DiskSpace, Drive, InMemoryDrive};
use crate::testutils::*;
use futures_lite::future::block_on;
use std::collections::BTreeMap;
#[test]
fn test_cd_ok() {
let mut t = Tester::default();
t.get_storage().borrow_mut().mount("other", "memory://").unwrap();
t.run("CD \"other:\"").check();
assert_eq!("OTHER:/", t.get_storage().borrow().cwd());
t.run("CD \"memory:/\"").check();
assert_eq!("MEMORY:/", t.get_storage().borrow().cwd());
}
#[test]
fn test_cd_errors() {
check_stmt_err("1:1: In call to CD: Drive 'A' is not mounted", "CD \"A:\"");
check_stmt_err("1:1: In call to CD: expected path$", "CD");
check_stmt_err("1:1: In call to CD: expected path$", "CD 2, 3");
check_stmt_err("1:1: In call to CD: 1:4: CD requires a string as the path", "CD 2");
}
#[test]
fn test_dir_current_empty() {
Tester::default()
.run("DIR")
.expect_prints([
"",
" Directory of MEMORY:/",
"",
" Modified Size Name",
" 0 file(s), 0 bytes",
"",
])
.check();
}
#[test]
fn test_dir_with_disk_free() {
let mut other = InMemoryDrive::default();
other.fake_disk_quota = Some(DiskSpace::new(456, 0));
other.fake_disk_free = Some(DiskSpace::new(123, 0));
let mut t = Tester::default();
t.get_storage().borrow_mut().attach("other", "z://", Box::from(other)).unwrap();
t.run("DIR \"OTHER:/\"")
.expect_prints([
"",
" Directory of OTHER:/",
"",
" Modified Size Name",
" 0 file(s), 0 bytes",
" 123 of 456 bytes free",
"",
])
.check();
}
#[test]
fn test_dir_current_entries_are_sorted() {
Tester::default()
.write_file("empty.bas", "")
.write_file("some other file.bas", "not empty\n")
.write_file("00AAA.BAS", "first\nfile\n")
.write_file("not a bas.txt", "")
.run("DIR")
.expect_prints([
"",
" Directory of MEMORY:/",
"",
" Modified Size Name",
" 2020-05-06 09:37 11 00AAA.BAS",
" 2020-05-06 09:37 0 empty.bas",
" 2020-05-06 09:37 0 not a bas.txt",
" 2020-05-06 09:37 10 some other file.bas",
"",
" 4 file(s), 21 bytes",
"",
])
.expect_file("MEMORY:/empty.bas", "")
.expect_file("MEMORY:/some other file.bas", "not empty\n")
.expect_file("MEMORY:/00AAA.BAS", "first\nfile\n")
.expect_file("MEMORY:/not a bas.txt", "")
.check();
}
#[test]
fn test_dir_other_by_argument() {
let mut other = InMemoryDrive::default();
block_on(other.put("foo.bas", "hello")).unwrap();
let mut t = Tester::default().write_file("empty.bas", "");
t.get_storage().borrow_mut().attach("other", "z://", Box::from(other)).unwrap();
let mut prints = vec![
"",
" Directory of MEMORY:/",
"",
" Modified Size Name",
" 2020-05-06 09:37 0 empty.bas",
"",
" 1 file(s), 0 bytes",
"",
];
t.run("DIR \"memory:\"")
.expect_prints(prints.clone())
.expect_file("MEMORY:/empty.bas", "")
.expect_file("OTHER:/foo.bas", "hello")
.check();
prints.extend([
"",
" Directory of OTHER:/",
"",
" Modified Size Name",
" 2020-05-06 09:37 5 foo.bas",
"",
" 1 file(s), 5 bytes",
"",
]);
t.run("DIR \"other:/\"")
.expect_prints(prints)
.expect_file("MEMORY:/empty.bas", "")
.expect_file("OTHER:/foo.bas", "hello")
.check();
}
#[test]
fn test_dir_other_by_cwd() {
let mut other = InMemoryDrive::default();
block_on(other.put("foo.bas", "hello")).unwrap();
let mut t = Tester::default().write_file("empty.bas", "");
t.get_storage().borrow_mut().attach("other", "z://", Box::from(other)).unwrap();
let mut prints = vec![
"",
" Directory of MEMORY:/",
"",
" Modified Size Name",
" 2020-05-06 09:37 0 empty.bas",
"",
" 1 file(s), 0 bytes",
"",
];
t.run("DIR")
.expect_prints(prints.clone())
.expect_file("MEMORY:/empty.bas", "")
.expect_file("OTHER:/foo.bas", "hello")
.check();
t.get_storage().borrow_mut().cd("other:/").unwrap();
prints.extend([
"",
" Directory of OTHER:/",
"",
" Modified Size Name",
" 2020-05-06 09:37 5 foo.bas",
"",
" 1 file(s), 5 bytes",
"",
]);
t.run("DIR")
.expect_prints(prints)
.expect_file("MEMORY:/empty.bas", "")
.expect_file("OTHER:/foo.bas", "hello")
.check();
}
#[test]
fn test_dir_errors() {
check_stmt_err("1:1: In call to DIR: expected [path$]", "DIR 2, 3");
check_stmt_err("1:1: In call to DIR: 1:5: DIR requires a string as the path", "DIR 2");
}
#[test]
fn test_mount_list() {
let mut t = Tester::default();
let other = InMemoryDrive::default();
t.get_storage().borrow_mut().attach("o", "origin://", Box::from(other)).unwrap();
let mut prints = vec![
"",
" Name Target",
" MEMORY memory://",
" O origin://",
"",
" 2 drive(s)",
"",
];
t.run("MOUNT").expect_prints(prints.clone()).check();
t.get_storage().borrow_mut().cd("o:").unwrap();
t.get_storage().borrow_mut().unmount("memory").unwrap();
prints.extend([
"",
" Name Target",
" O origin://",
"",
" 1 drive(s)",
"",
]);
t.run("MOUNT").expect_prints(prints.clone()).check();
}
#[test]
fn test_mount_mount() {
let mut t = Tester::default();
t.run(r#"MOUNT "memory://" AS "abc""#).check();
let mut exp_info = BTreeMap::default();
exp_info.insert("MEMORY", "memory://");
exp_info.insert("ABC", "memory://");
assert_eq!(exp_info, t.get_storage().borrow().mounted());
}
#[test]
fn test_mount_errors() {
check_stmt_err("1:1: In call to MOUNT: expected [target$ AS drive_name$]", "MOUNT 1");
check_stmt_err("1:1: In call to MOUNT: expected [target$ AS drive_name$]", "MOUNT 1, 2, 3");
check_stmt_err(
"1:1: In call to MOUNT: 1:14: Drive name must be a string",
r#"MOUNT "a" AS 1"#,
);
check_stmt_err(
"1:1: In call to MOUNT: 1:7: Mount target must be a string",
r#"MOUNT 1 AS "a""#,
);
check_stmt_err(
"1:1: In call to MOUNT: Invalid drive name 'a:'",
r#"MOUNT "memory://" AS "a:""#,
);
check_stmt_err(
"1:1: In call to MOUNT: Mount URI must be of the form scheme://path",
r#"MOUNT "foo//bar" AS "a""#,
);
check_stmt_err(
"1:1: In call to MOUNT: Unknown mount scheme 'foo'",
r#"MOUNT "foo://bar" AS "a""#,
);
}
#[test]
fn test_pwd_without_system_path() {
let mut t = Tester::default();
t.run("PWD")
.expect_prints([
"",
" Working directory: MEMORY:/",
" No system location available",
"",
])
.check();
}
#[test]
fn test_pwd_with_system_path() {
let dir = tempfile::tempdir().unwrap();
let dir = dir.path().canonicalize().unwrap();
let mut t = Tester::default();
{
let storage = t.get_storage();
let storage = &mut *storage.borrow_mut();
storage.register_scheme("file", Box::from(DirectoryDriveFactory::default()));
storage.mount("other", &format!("file://{}", dir.display())).unwrap();
storage.cd("other:/").unwrap();
}
t.run("PWD")
.expect_prints([
"",
" Working directory: OTHER:/",
&format!(" System location: {}", dir.join("").display()),
"",
])
.check();
}
#[test]
fn test_unmount_ok() {
let mut t = Tester::default();
t.get_storage().borrow_mut().mount("other", "memory://").unwrap();
t.get_storage().borrow_mut().cd("other:").unwrap();
t.run("UNMOUNT \"memory\"").check();
let mut exp_info = BTreeMap::default();
exp_info.insert("OTHER", "memory://");
assert_eq!(exp_info, t.get_storage().borrow().mounted());
}
#[test]
fn test_unmount_errors() {
check_stmt_err("1:1: In call to UNMOUNT: expected drive_name$", "UNMOUNT");
check_stmt_err("1:1: In call to UNMOUNT: expected drive_name$", "UNMOUNT 2, 3");
check_stmt_err("1:1: In call to UNMOUNT: 1:9: Drive name must be a string", "UNMOUNT 1");
check_stmt_err("1:1: In call to UNMOUNT: Invalid drive name 'a:'", "UNMOUNT \"a:\"");
check_stmt_err("1:1: In call to UNMOUNT: Drive 'a' is not mounted", "UNMOUNT \"a\"");
}
}