Skip to content

Commit 548f3f3

Browse files
committed
Add DirEntry.{is_dir}
1 parent 858a6d0 commit 548f3f3

File tree

2 files changed

+21
-5
lines changed

2 files changed

+21
-5
lines changed

tests/snippets/stdlib_os.py

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ def __exit__(self, exc_type, exc_val, exc_tb):
5757

5858
FILE_NAME = "test1"
5959
FILE_NAME2 = "test2"
60+
FOLDER = "dir1"
6061
CONTENT = b"testing"
6162
CONTENT2 = b"rustpython"
6263
CONTENT3 = b"BOYA"
@@ -75,15 +76,21 @@ def __exit__(self, exc_type, exc_val, exc_tb):
7576
assert os.read(fd, len(CONTENT3)) == CONTENT3
7677
os.close(fd)
7778

78-
7979
fname2 = tmpdir + os.sep + FILE_NAME2
8080
with open(fname2, "wb"):
8181
pass
82-
files = set()
82+
folder = tmpdir + os.sep + FOLDER
83+
os.mkdir(folder)
84+
85+
names = set()
8386
paths = set()
87+
dirs = set()
8488
for dir_entry in os.scandir(tmpdir):
85-
files.add(dir_entry.name)
89+
names.add(dir_entry.name)
8690
paths.add(dir_entry.path)
91+
if dir_entry.is_dir():
92+
dirs.add(dir_entry.name)
8793

88-
assert files == set([FILE_NAME, FILE_NAME2])
89-
assert paths == set([fname, fname2])
94+
assert names == set([FILE_NAME, FILE_NAME2, FOLDER])
95+
assert paths == set([fname, fname2, folder])
96+
assert dirs == set([FOLDER])

vm/src/stdlib/os.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,14 @@ impl DirEntryRef {
214214
fn path(self, _vm: &VirtualMachine) -> String {
215215
self.entry.path().to_str().unwrap().to_string()
216216
}
217+
218+
fn is_dir(self, vm: &VirtualMachine) -> PyResult<bool> {
219+
Ok(self
220+
.entry
221+
.file_type()
222+
.map_err(|s| vm.new_os_error(s.to_string()))?
223+
.is_dir())
224+
}
217225
}
218226

219227
#[derive(Debug)]
@@ -275,6 +283,7 @@ pub fn make_module(vm: &VirtualMachine) -> PyObjectRef {
275283
let dir_entry = py_class!(ctx, "DirEntry", ctx.object(), {
276284
"name" => ctx.new_property(DirEntryRef::name),
277285
"path" => ctx.new_property(DirEntryRef::path),
286+
"is_dir" => ctx.new_rustfunc(DirEntryRef::is_dir),
278287
});
279288

280289
py_module!(vm, "_os", {

0 commit comments

Comments
 (0)