diff --git a/examples/dir.roc b/examples/dir.roc index 6f8d292b..3a371ae2 100644 --- a/examples/dir.roc +++ b/examples/dir.roc @@ -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 diff --git a/src/src/lib.rs b/src/src/lib.rs index a859336a..1d568cb4 100644 --- a/src/src/lib.rs +++ b/src/src/lib.rs @@ -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, + roc_path: &RocList, ) -> RocResult>, 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::>>(); - - // 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")]