Skip to content

Commit

Permalink
Merge pull request #136 from lukewilliamboswell/dirlist
Browse files Browse the repository at this point in the history
Add `Dir.list` effect
  • Loading branch information
Anton-4 committed Nov 24, 2023
2 parents d1c0370 + 9d60e91 commit dee04a8
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 20 deletions.
11 changes: 11 additions & 0 deletions examples/dir.roc
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,17 @@ main =
expect
createChildShouldSucceed == Ok {}

# List the contents of a directory
paths <-
Path.fromStr "a"
|> Dir.list
|> Task.onErr \_ -> crash "Failed to list directory"
|> Task.await

# Check the contents of the directory
expect
(List.map paths Path.display) == ["b", "child"]

# Try to create a directory without a parent
createWithoutParentShouldFail <- Task.attempt (Dir.create (Path.fromStr "d/child"))
expect
Expand Down
45 changes: 25 additions & 20 deletions src/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -516,28 +516,33 @@ pub extern "C" fn roc_fx_sleepMillis(milliseconds: u64) {

#[no_mangle]
pub extern "C" fn roc_fx_dirList(
_roc_path: &RocList<u8>,
roc_path: &RocList<u8>,
) -> RocResult<RocList<RocList<u8>>, IOError> {
// match std::fs::read_dir(path_from_roc_path(roc_path)) {
// Ok(dir_entries) => {

// let entries = dir_entries
// .filter_map(|opt_dir_entry| match opt_dir_entry {
// Ok(entry) => Some(os_str_to_roc_path(entry.path().into_os_string().as_os_str())),
// Err(_) => None
// })
// .collect::<RocList<RocList<u8>>>();

// dbg!(&entries);

// RocResult::ok(entries)

// },
// Err(err) => RocResult::err(toRocIOError(err)),
// }
let path = path_from_roc_path(roc_path);

if path.is_dir() {
let dir = match std::fs::read_dir(path) {
Ok(dir) => dir,
Err(err) => return RocResult::err(toRocIOError(err)),
};

let mut entries = Vec::new();

for entry in dir {
match entry {
Ok(entry) => {
let path = entry.path();
let str = path.as_os_str();
entries.push(os_str_to_roc_path(str));
}
Err(_) => {} // TODO should we ignore errors reading directory??
}
}

// TODO implement this function
RocResult::err(IOError::Other())
return roc_std::RocResult::ok(RocList::from_iter(entries));
} else {
return roc_std::RocResult::err(dir_glue::IOError::NotADirectory());
}
}

#[cfg(target_family = "unix")]
Expand Down

0 comments on commit dee04a8

Please sign in to comment.