Get free disk space given path

I'm in the unfortunate situation where I need to determine the amount of free space available given a directory path. I discovered the sysinfo crate that has Disk::available_space() -- which is perfect .. but how do I get from an arbitrary &Path (pointing to a directory) to a Disk structure?

Do I need to manually perform the path.starts_with(disk.mount_point())/resolve symlinks dance, or is there some helper function that I'm not seeing that'll do all that for me?

I haven't used the crate, just looked at the docs.

I didn't see anything convenient offhand. On Linux/Unix/Apple, you can get the device number of a path from st_dev or dev. Then you need to know the device number of the corresponding mount.

For that, it looks like you can use Disks::new_with_refreshed_list and disks.list() to get all the Disks, then use mount_point to get a path that's for sure on that disk. Then e.g. make a map from device number to mounts.

Still a dance, but a better one. The starts_with approach would require checking prefixes in order from longest to shortest due to nested mounts.

There's probably a lot of annoying corners around namespaces that I haven't spent any time thinking about.

2 Likes

Me personally, I cheat. I would look at the "df" command in uutils/coreutils and see how they do it.

1 Like