Add std::fs::{Home|Media}Dirs - #158936
Conversation
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
Reviewed the Darwin parts.
calling those correctly requires an active Objective C autorelease pool, IIUC
Not that hard though, you can push and pop it with objc_autoreleasePoolPush/objc_autoreleasePoolPop. The bigger problem is that it requires linking Foundation, which has a startup cost we'd rather avoid.
This implementation diverges from the directories crate's mapping [...]
It seems to me that for something as nuanced as these user dirs (with a lot of platform-specific details that are not readily apparent), it might make sense to implement the desires std API in directories first? And once it stabilizes more there, we could upstream it to std?
This is mostly already the case. The only API-facing changes from directories here are:
The ideal API shape inside std and in a crate often differ slightly. This approved impl experiment is to determine if a form of this API that fits std's goals exists. I'm going to split the base directory discovery and the user/media directories into different types to better represent that the existence of these sets is not strongly correlated and fix the things @madsmtm pointed out w.r.t. docs and the darwin impl, then this should be good for proper libs-api review. The use of shlex for shell-unquote for the XDG user dirs needs a resolution, but doing the work to give shlex a rustc-dep-of-std feature can wait until we know whether that's the direction we want to take. |
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
| } | ||
|
|
||
| impl<'a> Iter<'a> { | ||
| // SAFETY: `mask` must be <= `SYSDIR_DOMAIN_MASK_ALL` |
There was a problem hiding this comment.
Huh, why?
There was a problem hiding this comment.
I'm assuming, tbqh; the manpage doesn't really specify. Note that here libc incorrectly translates sysdir_search_path_domain_mask_t as an enum when it's a bitmask, so there's no potential for unsafety currently, but I'm being conservative.
There was a problem hiding this comment.
I did see that libc issue, yeah.
I'm confident that it's not an issue though, the only way I could imagine it would work differently is if they decided in the future to use the rest of the integer for flags, and one of those flags doing something unsound. But that sounds improbable given that we're using the API in exactly the intended / documented fashion.
(It sounds a lot more likely to me that they'd add a new API if they really needed some new functionality).
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
For Windows I think we should ideally be delay loading at least SHGetKnownFolderPath and probably CoTaskMemFree too. SHGetKnownFolderPath is a GUI shell function and we try to avoid those in std (e.g. library/std/src/sys/args/windows.rs#L45). For local_app_data and roaming_app_data I think we should prefer the environment variables and only fallback to using the gui shell functions if that fails. That allows both allows users to override them and for it to work without the shell. That also implies that it should be possible to get the dirs.home.* directories without caching the dirs.media.* directories.
Tbh, I'm not personally convinced that the media directories are a good fit for std, at least for Windows, and not just for the reason above. Mostly CLI tools are going to be using either the current directory or otherwise explicit directories and GUI tools are usually going to want the GUI file/directory picker so I think this is fairly niche unless the standard library grows to encompass more GUI stuff. But that's ultimately a libs-api decision.
There was a problem hiding this comment.
You got in right before I split UserDirs properly (76ddaa3), so it's now possible to load the HomeDirs without MediaDirs. I had forgotten the fact that linking into shell32.dll marks the application as graphical; that's reason enough to prefer using the %APPDATA% environment variables if they're present.
(I'm not sure how we'd do the delayed DLL load in std.)
There was a problem hiding this comment.
We do have some helper macros, although they are more geared towards compatibility shims. But as I said, I'm happy to leave that to later. It might be enough that they're separate because now they'll be optimised out if they're never used. So that just leaves the case where they're conditionally used. But I doubt many CLI apps will have much use for media directories (as output paths are typically given explicitly or else the current directory is used).
There was a problem hiding this comment.
Well, I believe I've implemented lazy loading in 23bd91d; I'd appreciate a quick review of how I did so.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
|
I consider this fully ready for review now. r? @rust-lang/libs-api |
|
|
I did a clean rebase onto upstream main (no commit edits) on prompting by rustbot (not initially realizing that it's a "once needed" reminder). Initial feedback from libs-api addressed, so putting this back for review. Continuing API review is happening on the ACP, so passing back to libs review. @rustbot ready r? rust-lang/libs |
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
| /// # SAFETY | ||
| /// | ||
| /// Some thread must have started loading the module. (`self.1 is (0 | usize::MAX)`) | ||
| unsafe fn wait_unchecked(&self) -> Option<Module> { |
There was a problem hiding this comment.
I don't think we need our own waiting mechanism here. It should be fine to call LoadLibraryEx from multiple threads since it does its own locking when loading modules. It doesn't really matter which thread wins the race, they'll all get back the module handle. Losing threads could call FreeLibraryEx to decrement the counter but I'm not even sure that's necessary seeing as we never intend to unload it.
|
@rustbot reroll |
View all comments
std::fs::UserDirsor similar libs-team#830Replacement for
std::os::unix::xdgas suggested by libs-api in #157515 (comment). Exposes media directories common between the three big OSes in addition to the cache/config/data/state directories under a separate feature gate. API summary:This implementation diverges from the
directoriescrate's mapping in that we setstate_dirin the non-unix constructors (to~/Library/Application Supporton Darwin and%APPDATA%on Windows). This mapping is derived from the idea that "state" files are application support files that are not important nor portable enough to the user to be "data" files.The XDG paths are as described in the XDG Base Directories Specification and the xdg-user-dirs tool.
$XDG_CONFIG_DIR/user-dirs.dirsis parsed directly to avoid delegating to potentially arbitrary shell execution.The Darwin paths are loaded via the
sysdir(3)API fromlibSystem.dylib(introduced in macOS 10.12 with a similar timeline for other Darwin OSes, deprecating the earlierNSSystemDirectories.hAPI). Using the File System Effectively points to preferring the Foundation framework'sNSSearchPathForDirectoriesInDomain(_:_:_:)orNSFileManager.URLForDirectoryinstead, but calling those correctly requires an active Objective C autorelease pool, IIUC. TheLibrary/Application Supportdirectory is used forconfig_home,data_home, andstate_home; the Apple documentationThe Library Directory Stores App-Specific Filesdirectly calls out placing data and configuration files inLibrary/Application Support, and state files are just less user-meaningful data files.The Windows paths are loaded via the Known Folders API (introduced in Vista).
config_homeanddata_homeare placed inAppData\Roamingas files intended to be important and portable to the user, whilecache_homeandstate_homeare placed inAppData\Localas files that aren't.I'm not fully confident about the handling of the XDG base directory paths which don't have good cross-platform analogs, as well as the exact API for the search path dealing functions, but I'm confident that the shape of the rest of the API does match the stdlib API style. Common paths are platform-independent enough of a needed concept to be exposed by std, IMHO, but platform-specific that a struct with public fields (even
#[non_exhaustive]) seems incorrect, specifically because of platform-specific paths that we may want to expose like is already done for XDG.The one API change I could see doing is moving
state_dirinto the XDGUserDirsExt. I chose not to do this for this initial implementation, though, as getting the ideal choice of fallback for both Darwin and Windows can't be achieved in an OS-agnostic way:~/Library/Caches~/AppData/Local~/Library/Application Support~/AppData/Roaming~/Library/Application Support~/AppData/Roaming~/Library/Application Support~/AppData/LocalA more drastic change would be to move all four onto the unix
UserDirsExt, addingcaches/application_supportto the DarwinUserDirsExtandroaming_app_data/local_app_datato the WindowsUserDirsExt. This would be more "correct" but seems a bit heavy-handed, as it would mean applications need to pull in OS-specific extension traits just to place their support files in something more appropriate than a~/.appnamedirectory.We could also separate the "home" directory API from the "media" directory API. I'm neutral on this with one relevant note: the app-specific cache/config/data/state files need a subdirectory named after the application, so "
ProjectDirs" would exclude the media directories; it could make sense to have a type with just those and apush_application_subdirmethod.Switching the impl to using a pal
imp::UserDirscould be reasonable, but seems at odds with the desire to have the target agnostic way to "build your own"UserDirs. AnExtraUserDirsinstead of the#[allow(dead_code)]fields would make sense, I just didn't know how to best set up that in the pal layer.Disclaimer: This was worked on as part of my employment at Canonical. I initially proposed it independently of my employment, but improving std's functionality is part of my job description, so Canonical told me I should use work time on it.
AI Disclosure: I did not use AI to generate any of the code, with a partial exception for VSCode's AI-assisted smart autocomplete helping with the repetitive parts of the code. All nontrivial code was handwritten. As an experiment, I did use some AI to assist in exploring the problem and API design spaces.
I tested locally on my Ubuntu developer machine, but am relying on CI for Darwin and Windows tests. 🤞
user_home(toNSHomeDirectoryandFOLDERID_Profilerespectively) instead ofenv::home_dir? (Shouldenv::home_dirbe changed to call those?)SHGetKnownFolderPatheagerly? If so, how? Addstd::fs::{Home|Media}Dirs#158936 (comment)set_*methods do any kind of validation, such as ensuring the path is non-empty or even absolute?set_*methods takeimpl AsRef<Path>instead ofPathBuf? (Would introduce needless copies without a separate ownership-taking option likereplace_*below.)fn replace_*(&mut self, x: Option<PathBuf>) -> Option<PathBuf>style methods to allow transferring ownership and setting paths back toNone?NSSearchPathDirectorymake sense to expose in the DarwinUserDirsExt?KNOWNFOLDERIDmake sense to expose in the WindowsUserDirsExt?cc @joshtriplett @nia-e