1 #![cfg(any(unix, target_os = "redox"))]
2 
3 use std::fmt;
4 use std::convert;
5 use std::error;
6 use std::io;
7 use std::env;
8 use std::fs;
9 use std::path::{Path, PathBuf};
10 use std::ffi::OsString;
11 
12 use std::os::unix::fs::PermissionsExt;
13 
14 use BaseDirectoriesErrorKind::*;
15 use BaseDirectoriesError as Error;
16 
17 /// BaseDirectories allows to look up paths to configuration, data,
18 /// cache and runtime files in well-known locations according to
19 /// the [X Desktop Group Base Directory specification][xdg-basedir].
20 /// [xdg-basedir]: http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
21 ///
22 /// The Base Directory specification defines four kinds of files:
23 ///
24 ///   * **Configuration files** store the application's settings and
25 ///     are often modified during runtime;
26 ///   * **Data files** store supplementary data, such as graphic assets,
27 ///     precomputed tables, documentation, or architecture-independent
28 ///     source code;
29 ///   * **Cache files** store non-essential, transient data that provides
30 ///     a runtime speedup;
31 ///   * **Runtime files** include filesystem objects such are sockets or
32 ///     named pipes that are used for communication internal to the application.
33 ///     Runtime files must not be accessible to anyone except current user.
34 ///
35 /// # Examples
36 ///
37 /// To configure paths for application `myapp`:
38 ///
39 /// ```
40 /// extern crate xdg;
41 /// let xdg_dirs = xdg::BaseDirectories::with_prefix("myapp").unwrap();
42 /// ```
43 ///
44 /// To store configuration:
45 ///
46 /// ```
47 /// let config_path = xdg_dirs.place_config_file("config.ini")
48 ///                           .expect("cannot create configuration directory");
49 /// let mut config_file = try!(File::create(config_path));
50 /// try!(write!(&mut config_file, "configured = 1"));
51 /// ```
52 ///
53 /// The `config.ini` file will appear in the proper location for desktop
54 /// configuration files, most likely `~/.config/myapp/config.ini`.
55 /// The leading directories will be automatically created.
56 ///
57 /// To retrieve supplementary data:
58 ///
59 /// ```
60 /// let logo_path = xdg_dirs.find_data_file("logo.png")
61 ///                         .expect("application data not present");
62 /// let mut logo_file = try!(File::open(logo_path));
63 /// let mut logo = Vec::new();
64 /// try!(logo_file.read_to_end(&mut logo));
65 /// ```
66 ///
67 /// The `logo.png` will be searched in the proper locations for
68 /// supplementary data files, most likely `~/.local/share/myapp/logo.png`,
69 /// then `/usr/local/share/myapp/logo.png` and `/usr/share/myapp/logo.png`.
70 #[derive(Debug, Clone)]
71 pub struct BaseDirectories {
72     shared_prefix: PathBuf,
73     user_prefix: PathBuf,
74     data_home: PathBuf,
75     config_home: PathBuf,
76     cache_home: PathBuf,
77     data_dirs: Vec<PathBuf>,
78     config_dirs: Vec<PathBuf>,
79     runtime_dir: Option<PathBuf>,
80 }
81 
82 pub struct BaseDirectoriesError {
83     kind: BaseDirectoriesErrorKind,
84 }
85 
86 impl BaseDirectoriesError {
new(kind: BaseDirectoriesErrorKind) -> BaseDirectoriesError87     fn new(kind: BaseDirectoriesErrorKind) -> BaseDirectoriesError {
88         BaseDirectoriesError {
89             kind: kind,
90         }
91     }
92 }
93 
94 impl fmt::Debug for BaseDirectoriesError {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result95     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
96         self.kind.fmt(f)
97     }
98 }
99 
100 impl error::Error for BaseDirectoriesError {
description(&self) -> &str101     fn description(&self) -> &str {
102         match self.kind {
103             HomeMissing => "$HOME must be set",
104             XdgRuntimeDirInaccessible(_, _) =>
105                 "$XDG_RUNTIME_DIR must be accessible by the current user",
106             XdgRuntimeDirInsecure(_, _) =>
107                 "$XDG_RUNTIME_DIR must be secure: have permissions 0700",
108             XdgRuntimeDirMissing =>
109                 "$XDG_RUNTIME_DIR is not set",
110         }
111     }
cause(&self) -> Option<&error::Error>112     fn cause(&self) -> Option<&error::Error> {
113         match self.kind {
114             XdgRuntimeDirInaccessible(_, ref e) => Some(e),
115             _ => None,
116         }
117     }
118 }
119 
120 impl fmt::Display for BaseDirectoriesError {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result121     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
122         match self.kind {
123             HomeMissing => write!(f, "{}", error::Error::description(self)),
124             XdgRuntimeDirInaccessible(ref dir, ref error) => {
125                 write!(f, "$XDG_RUNTIME_DIR (`{}`) must be accessible \
126                            by the current user (error: {})", dir.display(), error)
127             },
128             XdgRuntimeDirInsecure(ref dir, permissions) => {
129                 write!(f, "$XDG_RUNTIME_DIR (`{}`) must be secure: must have \
130                            permissions 0o700, got {}", dir.display(), permissions)
131             },
132             XdgRuntimeDirMissing => {
133                 write!(f, "$XDG_RUNTIME_DIR must be set")
134             },
135         }
136     }
137 }
138 
139 impl convert::From<BaseDirectoriesError> for io::Error {
from(error: BaseDirectoriesError) -> io::Error140     fn from(error: BaseDirectoriesError) -> io::Error {
141         match error.kind {
142             HomeMissing | XdgRuntimeDirMissing =>
143                 io::Error::new(io::ErrorKind::NotFound, error),
144             _ => io::Error::new(io::ErrorKind::Other, error)
145         }
146     }
147 
148 }
149 
150 #[derive(Copy, Clone)]
151 struct Permissions(u32);
152 
153 impl fmt::Debug for Permissions {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result154     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
155         let Permissions(p) = *self;
156         write!(f, "{:#05o}", p)
157     }
158 }
159 
160 impl fmt::Display for Permissions {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result161     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
162         fmt::Debug::fmt(self, f)
163     }
164 }
165 
166 #[derive(Debug)]
167 enum BaseDirectoriesErrorKind {
168     HomeMissing,
169     XdgRuntimeDirInaccessible(PathBuf, io::Error),
170     XdgRuntimeDirInsecure(PathBuf, Permissions),
171     XdgRuntimeDirMissing,
172 }
173 
174 impl BaseDirectories {
175     /// Reads the process environment, determines the XDG base directories,
176     /// and returns a value that can be used for lookup.
177     /// The following environment variables are examined:
178     ///
179     ///   * `HOME`; if not set: use the same fallback as `std::env::home_dir()`;
180     ///     if still not available: return an error.
181     ///   * `XDG_DATA_HOME`; if not set: assumed to be `$HOME/.local/share`.
182     ///   * `XDG_CONFIG_HOME`; if not set: assumed to be `$HOME/.config`.
183     ///   * `XDG_CACHE_HOME`; if not set: assumed to be `$HOME/.cache`.
184     ///   * `XDG_DATA_DIRS`; if not set: assumed to be `/usr/local/share:/usr/share`.
185     ///   * `XDG_CONFIG_DIRS`; if not set: assumed to be `/etc/xdg`.
186     ///   * `XDG_RUNTIME_DIR`; if not accessible or permissions are not `0700`:
187     ///     record as inaccessible (can be queried with
188     ///     [has_runtime_directory](method.has_runtime_directory)).
189     ///
190     /// As per specification, if an environment variable contains a relative path,
191     /// the behavior is the same as if it was not set.
new() -> Result<BaseDirectories, BaseDirectoriesError>192     pub fn new() -> Result<BaseDirectories, BaseDirectoriesError> {
193         BaseDirectories::with_env("", "", &|name| env::var_os(name))
194     }
195 
196     /// Same as [`new()`](#method.new), but `prefix` is implicitly prepended to
197     /// every path that is looked up.
with_prefix<P>(prefix: P) -> Result<BaseDirectories, BaseDirectoriesError> where P: AsRef<Path>198     pub fn with_prefix<P>(prefix: P) -> Result<BaseDirectories, BaseDirectoriesError>
199             where P: AsRef<Path> {
200         BaseDirectories::with_env(prefix, "", &|name| env::var_os(name))
201     }
202 
203     /// Same as [`with_prefix()`](#method.with_prefix),
204     /// with `profile` also implicitly prepended to every path that is looked up,
205     /// but only for user-specific directories.
206     ///
207     /// This allows each user to have mutliple "profiles" with different user-specific data.
208     ///
209     /// For example:
210     ///
211     /// ```rust
212     /// let dirs = BaseDirectories::with_profile("program-name", "profile-name")
213     ///                            .unwrap();
214     /// dirs.find_data_file("bar.jpg");
215     /// dirs.find_config_file("foo.conf");
216     /// ```
217     ///
218     /// will find `/usr/share/program-name/bar.jpg` (without `profile-name`)
219     /// and `~/.config/program-name/profile-name/foo.conf`.
with_profile<P1, P2>(prefix: P1, profile: P2) -> Result<BaseDirectories, BaseDirectoriesError> where P1: AsRef<Path>, P2: AsRef<Path>220     pub fn with_profile<P1, P2>(prefix: P1, profile: P2)
221             -> Result<BaseDirectories, BaseDirectoriesError>
222             where P1: AsRef<Path>, P2: AsRef<Path> {
223         BaseDirectories::with_env(prefix, profile, &|name| env::var_os(name))
224     }
225 
with_env<P1, P2, T: ?Sized>(prefix: P1, profile: P2, env_var: &T) -> Result<BaseDirectories, BaseDirectoriesError> where P1: AsRef<Path>, P2: AsRef<Path>, T: Fn(&str) -> Option<OsString>226     fn with_env<P1, P2, T: ?Sized>(prefix: P1, profile: P2, env_var: &T)
227             -> Result<BaseDirectories, BaseDirectoriesError>
228             where P1: AsRef<Path>, P2: AsRef<Path>, T: Fn(&str) -> Option<OsString> {
229         BaseDirectories::with_env_impl(prefix.as_ref(), profile.as_ref(), env_var)
230     }
231 
with_env_impl<T: ?Sized>(prefix: &Path, profile: &Path, env_var: &T) -> Result<BaseDirectories, BaseDirectoriesError> where T: Fn(&str) -> Option<OsString>232     fn with_env_impl<T: ?Sized>(prefix: &Path, profile: &Path, env_var: &T)
233             -> Result<BaseDirectories, BaseDirectoriesError>
234             where T: Fn(&str) -> Option<OsString> {
235         fn abspath(path: OsString) -> Option<PathBuf> {
236             let path = PathBuf::from(path);
237             if path.is_absolute() {
238                 Some(path)
239             } else {
240                 None
241             }
242         }
243 
244         fn abspaths(paths: OsString) -> Option<Vec<PathBuf>> {
245             let paths = env::split_paths(&paths)
246                             .map(PathBuf::from)
247                             .filter(|ref path| path.is_absolute())
248                             .collect::<Vec<_>>();
249             if paths.is_empty() {
250                 None
251             } else {
252                 Some(paths)
253             }
254         }
255 
256         let home = try!(std::env::home_dir().ok_or(Error::new(HomeMissing)));
257 
258         let data_home   = env_var("XDG_DATA_HOME")
259                               .and_then(abspath)
260                               .unwrap_or(home.join(".local/share"));
261         let config_home = env_var("XDG_CONFIG_HOME")
262                               .and_then(abspath)
263                               .unwrap_or(home.join(".config"));
264         let cache_home  = env_var("XDG_CACHE_HOME")
265                               .and_then(abspath)
266                               .unwrap_or(home.join(".cache"));
267         let data_dirs   = env_var("XDG_DATA_DIRS")
268                               .and_then(abspaths)
269                               .unwrap_or(vec![PathBuf::from("/usr/local/share"),
270                                               PathBuf::from("/usr/share")]);
271         let config_dirs = env_var("XDG_CONFIG_DIRS")
272                               .and_then(abspaths)
273                               .unwrap_or(vec![PathBuf::from("/etc/xdg")]);
274         let runtime_dir = env_var("XDG_RUNTIME_DIR")
275                               .and_then(abspath); // optional
276 
277         let prefix = PathBuf::from(prefix);
278         Ok(BaseDirectories {
279             user_prefix: prefix.join(profile),
280             shared_prefix: prefix,
281             data_home: data_home,
282             config_home: config_home,
283             cache_home: cache_home,
284             data_dirs: data_dirs,
285             config_dirs: config_dirs,
286             runtime_dir: runtime_dir,
287         })
288     }
289 
get_runtime_directory(&self) -> Result<&PathBuf, BaseDirectoriesError>290     fn get_runtime_directory(&self) -> Result<&PathBuf, BaseDirectoriesError> {
291         if let Some(ref runtime_dir) = self.runtime_dir {
292             // If XDG_RUNTIME_DIR is in the environment but not secure,
293             // do not allow recovery.
294             try!(fs::read_dir(runtime_dir).map_err(|e| {
295                 Error::new(XdgRuntimeDirInaccessible(runtime_dir.clone(), e))
296             }));
297             let permissions = try!(fs::metadata(runtime_dir).map_err(|e| {
298                 Error::new(XdgRuntimeDirInaccessible(runtime_dir.clone(), e))
299             })).permissions().mode() as u32;
300             if permissions & 0o077 != 0 {
301                 Err(Error::new(XdgRuntimeDirInsecure(runtime_dir.clone(),
302                                                      Permissions(permissions))))
303             } else {
304                 Ok(&runtime_dir)
305             }
306         } else {
307             Err(Error::new(XdgRuntimeDirMissing))
308         }
309     }
310 
311     /// Returns `true` if `XDG_RUNTIME_DIR` is available, `false` otherwise.
has_runtime_directory(&self) -> bool312     pub fn has_runtime_directory(&self) -> bool {
313         match self.get_runtime_directory() {
314             Ok(_) => true,
315             _ => false
316         }
317     }
318 
319     /// Given a relative path `path`, returns an absolute path in
320     /// `XDG_CONFIG_HOME` where a configuration file may be stored.
321     /// Leading directories in the returned path are pre-created;
322     /// if that is not possible, an error is returned.
place_config_file<P>(&self, path: P) -> io::Result<PathBuf> where P: AsRef<Path>323     pub fn place_config_file<P>(&self, path: P) -> io::Result<PathBuf>
324             where P: AsRef<Path> {
325         write_file(&self.config_home, self.user_prefix.join(path))
326     }
327 
328     /// Like [`place_config_file()`](#method.place_config_file), but for
329     /// a data file in `XDG_DATA_HOME`.
place_data_file<P>(&self, path: P) -> io::Result<PathBuf> where P: AsRef<Path>330     pub fn place_data_file<P>(&self, path: P) -> io::Result<PathBuf>
331             where P: AsRef<Path> {
332         write_file(&self.data_home, self.user_prefix.join(path))
333     }
334 
335     /// Like [`place_config_file()`](#method.place_config_file), but for
336     /// a cache file in `XDG_CACHE_HOME`.
place_cache_file<P>(&self, path: P) -> io::Result<PathBuf> where P: AsRef<Path>337     pub fn place_cache_file<P>(&self, path: P) -> io::Result<PathBuf>
338             where P: AsRef<Path> {
339         write_file(&self.cache_home, self.user_prefix.join(path))
340     }
341 
342     /// Like [`place_config_file()`](#method.place_config_file), but for
343     /// a runtime file in `XDG_RUNTIME_DIR`.
344     /// If `XDG_RUNTIME_DIR` is not available, returns an error.
place_runtime_file<P>(&self, path: P) -> io::Result<PathBuf> where P: AsRef<Path>345     pub fn place_runtime_file<P>(&self, path: P) -> io::Result<PathBuf>
346             where P: AsRef<Path> {
347         write_file(try!(self.get_runtime_directory()), self.user_prefix.join(path))
348     }
349 
350     /// Given a relative path `path`, returns an absolute path to an existing
351     /// configuration file, or `None`. Searches `XDG_CONFIG_HOME` and then
352     /// `XDG_CONFIG_DIRS`.
find_config_file<P>(&self, path: P) -> Option<PathBuf> where P: AsRef<Path>353     pub fn find_config_file<P>(&self, path: P) -> Option<PathBuf>
354             where P: AsRef<Path> {
355         read_file(&self.config_home, &self.config_dirs,
356                   &self.user_prefix, &self.shared_prefix, path.as_ref())
357     }
358 
359     /// Given a relative path `path`, returns an iterator yielding absolute
360     /// paths to existing configuration files, in `XDG_CONFIG_DIRS` and
361     /// `XDG_CONFIG_HOME`. Paths are produced in order from lowest priority
362     /// to highest.
find_config_files<P>(&self, path: P) -> FileFindIterator where P: AsRef<Path>363     pub fn find_config_files<P>(&self, path: P) -> FileFindIterator
364             where P: AsRef<Path> {
365         FileFindIterator::new(&self.config_home, &self.config_dirs,
366                     &self.user_prefix, &self.shared_prefix, path.as_ref())
367     }
368 
369     /// Given a relative path `path`, returns an absolute path to an existing
370     /// data file, or `None`. Searches `XDG_DATA_HOME` and then
371     /// `XDG_DATA_DIRS`.
find_data_file<P>(&self, path: P) -> Option<PathBuf> where P: AsRef<Path>372     pub fn find_data_file<P>(&self, path: P) -> Option<PathBuf>
373             where P: AsRef<Path> {
374         read_file(&self.data_home, &self.data_dirs,
375                   &self.user_prefix, &self.shared_prefix, path.as_ref())
376     }
377 
378     /// Given a relative path `path`, returns an iterator yielding absolute
379     /// paths to existing data files, in `XDG_DATA_DIRS` and
380     /// `XDG_DATA_HOME`. Paths are produced in order from lowest priority
381     /// to highest.
find_data_files<P>(&self, path: P) -> FileFindIterator where P: AsRef<Path>382     pub fn find_data_files<P>(&self, path: P) -> FileFindIterator
383             where P: AsRef<Path> {
384         FileFindIterator::new(&self.data_home, &self.data_dirs,
385                     &self.user_prefix, &self.shared_prefix, path.as_ref())
386     }
387 
388     /// Given a relative path `path`, returns an absolute path to an existing
389     /// cache file, or `None`. Searches `XDG_CACHE_HOME`.
find_cache_file<P>(&self, path: P) -> Option<PathBuf> where P: AsRef<Path>390     pub fn find_cache_file<P>(&self, path: P) -> Option<PathBuf>
391             where P: AsRef<Path> {
392         read_file(&self.cache_home, &Vec::new(),
393                   &self.user_prefix, &self.shared_prefix, path.as_ref())
394     }
395 
396     /// Given a relative path `path`, returns an absolute path to an existing
397     /// runtime file, or `None`. Searches `XDG_RUNTIME_DIR`.
398     /// If `XDG_RUNTIME_DIR` is not available, returns `None`.
find_runtime_file<P>(&self, path: P) -> Option<PathBuf> where P: AsRef<Path>399     pub fn find_runtime_file<P>(&self, path: P) -> Option<PathBuf>
400             where P: AsRef<Path> {
401         if let Ok(runtime_dir) = self.get_runtime_directory() {
402             read_file(runtime_dir, &Vec::new(),
403                       &self.user_prefix, &self.shared_prefix, path.as_ref())
404         } else {
405             None
406         }
407     }
408 
409     /// Given a relative path `path`, returns an absolute path to a configuration
410     /// directory in `XDG_CONFIG_HOME`. The directory and all directories
411     /// leading to it are created if they did not exist;
412     /// if that is not possible, an error is returned.
create_config_directory<P>(&self, path: P) -> io::Result<PathBuf> where P: AsRef<Path>413     pub fn create_config_directory<P>(&self, path: P) -> io::Result<PathBuf>
414             where P: AsRef<Path> {
415         create_directory(&self.config_home,
416                          self.user_prefix.join(path))
417     }
418 
419     /// Like [`create_config_directory()`](#method.create_config_directory),
420     /// but for a data directory in `XDG_DATA_HOME`.
create_data_directory<P>(&self, path: P) -> io::Result<PathBuf> where P: AsRef<Path>421     pub fn create_data_directory<P>(&self, path: P) -> io::Result<PathBuf>
422             where P: AsRef<Path> {
423         create_directory(&self.data_home,
424                          self.user_prefix.join(path))
425     }
426 
427     /// Like [`create_config_directory()`](#method.create_config_directory),
428     /// but for a cache directory in `XDG_CACHE_HOME`.
create_cache_directory<P>(&self, path: P) -> io::Result<PathBuf> where P: AsRef<Path>429     pub fn create_cache_directory<P>(&self, path: P) -> io::Result<PathBuf>
430             where P: AsRef<Path> {
431         create_directory(&self.cache_home,
432                          self.user_prefix.join(path))
433     }
434 
435     /// Like [`create_config_directory()`](#method.create_config_directory),
436     /// but for a runtime directory in `XDG_RUNTIME_DIR`.
437     /// If `XDG_RUNTIME_DIR` is not available, returns an error.
create_runtime_directory<P>(&self, path: P) -> io::Result<PathBuf> where P: AsRef<Path>438     pub fn create_runtime_directory<P>(&self, path: P) -> io::Result<PathBuf>
439             where P: AsRef<Path> {
440         create_directory(try!(self.get_runtime_directory()),
441                          self.user_prefix.join(path))
442     }
443 
444     /// Given a relative path `path`, list absolute paths to all files
445     /// in directories with path `path` in `XDG_CONFIG_HOME` and
446     /// `XDG_CONFIG_DIRS`.
list_config_files<P>(&self, path: P) -> Vec<PathBuf> where P: AsRef<Path>447     pub fn list_config_files<P>(&self, path: P) -> Vec<PathBuf>
448             where P: AsRef<Path> {
449         list_files(&self.config_home, &self.config_dirs,
450                    &self.user_prefix, &self.shared_prefix, path.as_ref())
451     }
452 
453     /// Like [`list_config_files`](#method.list_config_files), but
454     /// only the first occurence of every distinct filename is returned.
list_config_files_once<P>(&self, path: P) -> Vec<PathBuf> where P: AsRef<Path>455     pub fn list_config_files_once<P>(&self, path: P) -> Vec<PathBuf>
456             where P: AsRef<Path> {
457         list_files_once(&self.config_home, &self.config_dirs,
458                         &self.user_prefix, &self.shared_prefix, path.as_ref())
459     }
460 
461     /// Given a relative path `path`, lists absolute paths to all files
462     /// in directories with path `path` in `XDG_DATA_HOME` and
463     /// `XDG_DATA_DIRS`.
list_data_files<P>(&self, path: P) -> Vec<PathBuf> where P: AsRef<Path>464     pub fn list_data_files<P>(&self, path: P) -> Vec<PathBuf>
465             where P: AsRef<Path> {
466         list_files(&self.data_home, &self.data_dirs,
467                    &self.user_prefix, &self.shared_prefix, path.as_ref())
468     }
469 
470     /// Like [`list_data_files`](#method.list_data_files), but
471     /// only the first occurence of every distinct filename is returned.
list_data_files_once<P>(&self, path: P) -> Vec<PathBuf> where P: AsRef<Path>472     pub fn list_data_files_once<P>(&self, path: P) -> Vec<PathBuf>
473             where P: AsRef<Path> {
474         list_files_once(&self.data_home, &self.data_dirs,
475                         &self.user_prefix, &self.shared_prefix, path.as_ref())
476     }
477 
478     /// Given a relative path `path`, lists absolute paths to all files
479     /// in directories with path `path` in `XDG_CACHE_HOME`.
list_cache_files<P>(&self, path: P) -> Vec<PathBuf> where P: AsRef<Path>480     pub fn list_cache_files<P>(&self, path: P) -> Vec<PathBuf>
481             where P: AsRef<Path> {
482         list_files(&self.cache_home, &Vec::new(),
483                    &self.user_prefix, &self.shared_prefix, path.as_ref())
484     }
485 
486     /// Given a relative path `path`, lists absolute paths to all files
487     /// in directories with path `path` in `XDG_RUNTIME_DIR`.
488     /// If `XDG_RUNTIME_DIR` is not available, returns an empty `Vec`.
list_runtime_files<P>(&self, path: P) -> Vec<PathBuf> where P: AsRef<Path>489     pub fn list_runtime_files<P>(&self, path: P) -> Vec<PathBuf>
490             where P: AsRef<Path> {
491         if let Ok(runtime_dir) = self.get_runtime_directory() {
492             list_files(runtime_dir, &Vec::new(),
493                        &self.user_prefix, &self.shared_prefix, path.as_ref())
494         } else {
495             Vec::new()
496         }
497     }
498 
499     /// Returns the user-specific data directory (set by `XDG_DATA_HOME`).
get_data_home(&self) -> PathBuf500     pub fn get_data_home(&self) -> PathBuf {
501         self.data_home.join(&self.user_prefix)
502     }
503 
504     /// Returns the user-specific configuration directory (set by
505     /// `XDG_CONFIG_HOME`).
get_config_home(&self) -> PathBuf506     pub fn get_config_home(&self) -> PathBuf {
507         self.config_home.join(&self.user_prefix)
508     }
509 
510     /// Returns the user-specific directory for non-essential (cached) data
511     /// (set by `XDG_CACHE_HOME`).
get_cache_home(&self) -> PathBuf512     pub fn get_cache_home(&self) -> PathBuf {
513         self.cache_home.join(&self.user_prefix)
514     }
515 
516     /// Returns a preference ordered (preferred to less preferred) list of
517     /// supplementary data directories, ordered by preference (set by
518     /// `XDG_DATA_DIRS`).
get_data_dirs(&self) -> Vec<PathBuf>519     pub fn get_data_dirs(&self) -> Vec<PathBuf> {
520         self.data_dirs.iter().map(|p| p.join(&self.shared_prefix)).collect()
521     }
522 
523     /// Returns a preference ordered (preferred to less preferred) list of
524     /// supplementary configuration directories (set by `XDG_CONFIG_DIRS`).
get_config_dirs(&self) -> Vec<PathBuf>525     pub fn get_config_dirs(&self) -> Vec<PathBuf> {
526         self.config_dirs.iter().map(|p| p.join(&self.shared_prefix)).collect()
527     }
528 }
529 
write_file<P>(home: &PathBuf, path: P) -> io::Result<PathBuf> where P: AsRef<Path>530 fn write_file<P>(home: &PathBuf, path: P) -> io::Result<PathBuf>
531         where P: AsRef<Path> {
532     match path.as_ref().parent() {
533         Some(parent) => try!(fs::create_dir_all(home.join(parent))),
534         None => try!(fs::create_dir_all(home)),
535     }
536     Ok(PathBuf::from(home.join(path.as_ref())))
537 }
538 
create_directory<P>(home: &PathBuf, path: P) -> io::Result<PathBuf> where P: AsRef<Path>539 fn create_directory<P>(home: &PathBuf, path: P) -> io::Result<PathBuf>
540         where P: AsRef<Path> {
541     let full_path = home.join(path.as_ref());
542     try!(fs::create_dir_all(&full_path));
543     Ok(full_path)
544 }
545 
path_exists<P: ?Sized + AsRef<Path>>(path: &P) -> bool546 fn path_exists<P: ?Sized + AsRef<Path>>(path: &P) -> bool {
547     fn inner(path: &Path) -> bool {
548         fs::metadata(path).is_ok()
549     }
550     inner(path.as_ref())
551 }
552 
553 #[cfg(test)]
path_is_dir<P: ?Sized + AsRef<Path>>(path: &P) -> bool554 fn path_is_dir<P: ?Sized + AsRef<Path>>(path: &P) -> bool {
555     fn inner(path: &Path) -> bool {
556         fs::metadata(path).map(|m| m.is_dir()).unwrap_or(false)
557     }
558     inner(path.as_ref())
559 }
560 
read_file(home: &PathBuf, dirs: &Vec<PathBuf>, user_prefix: &Path, shared_prefix: &Path, path: &Path) -> Option<PathBuf>561 fn read_file(home: &PathBuf, dirs: &Vec<PathBuf>,
562              user_prefix: &Path, shared_prefix: &Path, path: &Path)
563              -> Option<PathBuf> {
564     let full_path = home.join(user_prefix).join(path);
565     if path_exists(&full_path) {
566         return Some(full_path)
567     }
568     for dir in dirs.iter() {
569         let full_path = dir.join(shared_prefix).join(path);
570         if path_exists(&full_path) {
571             return Some(full_path)
572         }
573     }
574     None
575 }
576 
577 use std::iter::Iterator;
578 pub struct FileFindIterator {
579     search_dirs: Vec<PathBuf>,
580     position: usize,
581     relpath: PathBuf,
582 }
583 
584 impl FileFindIterator {
new(home: &PathBuf, dirs: &Vec<PathBuf>, user_prefix: &Path, shared_prefix: &Path, path: &Path) -> FileFindIterator585     fn new(home: &PathBuf, dirs: &Vec<PathBuf>,
586            user_prefix: &Path, shared_prefix: &Path, path: &Path)
587            -> FileFindIterator {
588        let mut search_dirs = Vec::new();
589        for dir in dirs.iter().rev() {
590            search_dirs.push(dir.join(shared_prefix));
591        }
592        search_dirs.push(home.join(user_prefix));
593        FileFindIterator {
594            search_dirs: search_dirs,
595            position: 0,
596            relpath: path.to_path_buf(),
597        }
598    }
599 }
600 
601 impl Iterator for FileFindIterator {
602     type Item = PathBuf;
603 
next(&mut self) -> Option<Self::Item>604     fn next(&mut self) -> Option<Self::Item> {
605         loop {
606             let dir = match self.search_dirs.get(self.position) {
607                 Some(d) => d,
608                 None => return None
609             };
610             self.position += 1;
611             let candidate = dir.join(self.relpath.clone());
612             if path_exists(&candidate) {
613                 return Some(candidate)
614             }
615         }
616     }
617 }
618 
list_files(home: &Path, dirs: &[PathBuf], user_prefix: &Path, shared_prefix: &Path, path: &Path) -> Vec<PathBuf>619 fn list_files(home: &Path, dirs: &[PathBuf],
620               user_prefix: &Path, shared_prefix: &Path, path: &Path)
621               -> Vec<PathBuf> {
622     fn read_dir(dir: &Path, into: &mut Vec<PathBuf>) {
623         if let Ok(entries) = fs::read_dir(dir) {
624             into.extend(
625                 entries
626                 .filter_map(|entry| entry.ok())
627                 .map(|entry| entry.path()))
628         }
629     }
630     let mut files = Vec::new();
631     read_dir(&home.join(user_prefix).join(path), &mut files);
632     for dir in dirs {
633         read_dir(&dir.join(shared_prefix).join(path), &mut files);
634     }
635     files
636 }
637 
list_files_once(home: &Path, dirs: &[PathBuf], user_prefix: &Path, shared_prefix: &Path, path: &Path) -> Vec<PathBuf>638 fn list_files_once(home: &Path, dirs: &[PathBuf],
639                    user_prefix: &Path, shared_prefix: &Path, path: &Path)
640                    -> Vec<PathBuf> {
641     let mut seen = std::collections::HashSet::new();
642     list_files(home, dirs, user_prefix, shared_prefix, path).into_iter().filter(|path| {
643         match path.clone().file_name() {
644             None => false,
645             Some(filename) => {
646                 if seen.contains(filename) {
647                     false
648                 } else {
649                     seen.insert(filename.to_owned());
650                     true
651                 }
652             }
653         }
654     }).collect::<Vec<_>>()
655 }
656 
657 #[cfg(test)]
make_absolute<P>(path: P) -> PathBuf where P: AsRef<Path>658 fn make_absolute<P>(path: P) -> PathBuf where P: AsRef<Path> {
659     env::current_dir().unwrap().join(path.as_ref())
660 }
661 
662 #[cfg(test)]
iter_after<A, I, J>(mut iter: I, mut prefix: J) -> Option<I> where I: Iterator<Item=A> + Clone, J: Iterator<Item=A>, A: PartialEq663 fn iter_after<A, I, J>(mut iter: I, mut prefix: J) -> Option<I> where
664     I: Iterator<Item=A> + Clone, J: Iterator<Item=A>, A: PartialEq
665 {
666     loop {
667         let mut iter_next = iter.clone();
668         match (iter_next.next(), prefix.next()) {
669             (Some(x), Some(y)) => {
670                 if x != y { return None }
671             }
672             (Some(_), None) => return Some(iter),
673             (None, None) => return Some(iter),
674             (None, Some(_)) => return None,
675         }
676         iter = iter_next;
677     }
678 }
679 
680 #[cfg(test)]
make_relative<P>(path: P) -> PathBuf where P: AsRef<Path>681 fn make_relative<P>(path: P) -> PathBuf where P: AsRef<Path> {
682     iter_after(path.as_ref().components(), env::current_dir().unwrap().components())
683         .unwrap().as_path().to_owned()
684 }
685 
686 #[cfg(test)]
make_env(vars: Vec<(&'static str, String)>) -> Box<Fn(&str)->Option<OsString>>687 fn make_env(vars: Vec<(&'static str, String)>) ->
688         Box<Fn(&str)->Option<OsString>> {
689     return Box::new(move |name| {
690         for &(key, ref value) in vars.iter() {
691             if key == name { return Some(OsString::from(value)) }
692         }
693         None
694     })
695 }
696 
697 #[test]
test_files_exists()698 fn test_files_exists() {
699     assert!(path_exists("test_files"));
700     assert!(fs::metadata("test_files/runtime-bad")
701                  .unwrap().permissions().mode() & 0o077 != 0);
702 }
703 
704 #[test]
test_bad_environment()705 fn test_bad_environment() {
706     let xd = BaseDirectories::with_env("", "", &*make_env(vec![
707             ("HOME", "test_files/user".to_string()),
708             ("XDG_DATA_HOME", "test_files/user/data".to_string()),
709             ("XDG_CONFIG_HOME", "test_files/user/config".to_string()),
710             ("XDG_CACHE_HOME", "test_files/user/cache".to_string()),
711             ("XDG_DATA_DIRS", "test_files/user/data".to_string()),
712             ("XDG_CONFIG_DIRS", "test_files/user/config".to_string()),
713             ("XDG_RUNTIME_DIR", "test_files/runtime-bad".to_string())
714         ])).unwrap();
715     assert_eq!(xd.find_data_file("everywhere"), None);
716     assert_eq!(xd.find_config_file("everywhere"), None);
717     assert_eq!(xd.find_cache_file("everywhere"), None);
718 }
719 
720 #[test]
test_good_environment()721 fn test_good_environment() {
722     let cwd = env::current_dir().unwrap().to_string_lossy().into_owned();
723     let xd = BaseDirectories::with_env("", "", &*make_env(vec![
724             ("HOME", format!("{}/test_files/user", cwd)),
725             ("XDG_DATA_HOME", format!("{}/test_files/user/data", cwd)),
726             ("XDG_CONFIG_HOME", format!("{}/test_files/user/config", cwd)),
727             ("XDG_CACHE_HOME", format!("{}/test_files/user/cache", cwd)),
728             ("XDG_DATA_DIRS", format!("{}/test_files/system0/data:{}/test_files/system1/data:{}/test_files/system2/data:{}/test_files/system3/data", cwd, cwd, cwd, cwd)),
729             ("XDG_CONFIG_DIRS", format!("{}/test_files/system0/config:{}/test_files/system1/config:{}/test_files/system2/config:{}/test_files/system3/config", cwd, cwd, cwd, cwd)),
730             // ("XDG_RUNTIME_DIR", format!("{}/test_files/runtime-bad", cwd)),
731         ])).unwrap();
732     assert!(xd.find_data_file("everywhere") != None);
733     assert!(xd.find_config_file("everywhere") != None);
734     assert!(xd.find_cache_file("everywhere") != None);
735 
736     let mut config_files = xd.find_config_files("everywhere");
737     assert_eq!(config_files.next(),
738         Some(PathBuf::from(format!("{}/test_files/system2/config/everywhere", cwd))));
739     assert_eq!(config_files.next(),
740         Some(PathBuf::from(format!("{}/test_files/system1/config/everywhere", cwd))));
741     assert_eq!(config_files.next(),
742         Some(PathBuf::from(format!("{}/test_files/user/config/everywhere", cwd))));
743     assert_eq!(config_files.next(), None);
744 
745     let mut data_files = xd.find_data_files("everywhere");
746     assert_eq!(data_files.next(),
747         Some(PathBuf::from(format!("{}/test_files/system2/data/everywhere", cwd))));
748     assert_eq!(data_files.next(),
749         Some(PathBuf::from(format!("{}/test_files/system1/data/everywhere", cwd))));
750     assert_eq!(data_files.next(),
751         Some(PathBuf::from(format!("{}/test_files/user/data/everywhere", cwd))));
752     assert_eq!(data_files.next(), None);
753 }
754 
755 #[test]
test_runtime_bad()756 fn test_runtime_bad() {
757     let cwd = env::current_dir().unwrap().to_string_lossy().into_owned();
758     let xd = BaseDirectories::with_env("", "", &*make_env(vec![
759             ("HOME", format!("{}/test_files/user", cwd)),
760             ("XDG_RUNTIME_DIR", format!("{}/test_files/runtime-bad", cwd)),
761         ])).unwrap();
762     assert!(xd.has_runtime_directory() == false);
763 }
764 
765 #[test]
test_runtime_good()766 fn test_runtime_good() {
767     use std::fs::File;
768 
769     let test_runtime_dir = make_absolute(&"test_files/runtime-good");
770     let _ = fs::remove_dir_all(&test_runtime_dir);
771     fs::create_dir_all(&test_runtime_dir).unwrap();
772 
773     let mut perms = fs::metadata(&test_runtime_dir).unwrap().permissions();
774     perms.set_mode(0o700);
775     fs::set_permissions(&test_runtime_dir, perms).unwrap();
776 
777     let cwd = env::current_dir().unwrap().to_string_lossy().into_owned();
778     let xd = BaseDirectories::with_env("", "", &*make_env(vec![
779             ("HOME", format!("{}/test_files/user", cwd)),
780             ("XDG_RUNTIME_DIR", format!("{}/test_files/runtime-good", cwd)),
781         ])).unwrap();
782 
783     xd.create_runtime_directory("foo").unwrap();
784     assert!(path_is_dir("test_files/runtime-good/foo"));
785     let w = xd.place_runtime_file("bar/baz").unwrap();
786     assert!(path_is_dir("test_files/runtime-good/bar"));
787     assert!(!path_exists("test_files/runtime-good/bar/baz"));
788     File::create(&w).unwrap();
789     assert!(path_exists("test_files/runtime-good/bar/baz"));
790     assert!(xd.find_runtime_file("bar/baz") == Some(w.clone()));
791     File::open(&w).unwrap();
792     fs::remove_file(&w).unwrap();
793     let root = xd.list_runtime_files(".");
794     let mut root = root.into_iter().map(|p| make_relative(&p)).collect::<Vec<_>>();
795     root.sort();
796     assert_eq!(root,
797                vec![PathBuf::from("test_files/runtime-good/bar"),
798                     PathBuf::from("test_files/runtime-good/foo")]);
799     assert!(xd.list_runtime_files("bar").is_empty());
800     assert!(xd.find_runtime_file("foo/qux").is_none());
801     assert!(xd.find_runtime_file("qux/foo").is_none());
802     assert!(!path_exists("test_files/runtime-good/qux"));
803 }
804 
805 #[test]
test_lists()806 fn test_lists() {
807     let cwd = env::current_dir().unwrap().to_string_lossy().into_owned();
808     let xd = BaseDirectories::with_env("", "", &*make_env(vec![
809             ("HOME", format!("{}/test_files/user", cwd)),
810             ("XDG_DATA_HOME", format!("{}/test_files/user/data", cwd)),
811             ("XDG_CONFIG_HOME", format!("{}/test_files/user/config", cwd)),
812             ("XDG_CACHE_HOME", format!("{}/test_files/user/cache", cwd)),
813             ("XDG_DATA_DIRS", format!("{}/test_files/system0/data:{}/test_files/system1/data:{}/test_files/system2/data:{}/test_files/system3/data", cwd, cwd, cwd, cwd)),
814             ("XDG_CONFIG_DIRS", format!("{}/test_files/system0/config:{}/test_files/system1/config:{}/test_files/system2/config:{}/test_files/system3/config", cwd, cwd, cwd, cwd)),
815         ])).unwrap();
816 
817     let files = xd.list_config_files(".");
818     let mut files = files.into_iter().map(|p| make_relative(&p)).collect::<Vec<_>>();
819     files.sort();
820     assert_eq!(files,
821         [
822             "test_files/system1/config/both_system_config.file",
823             "test_files/system1/config/everywhere",
824             "test_files/system1/config/myapp",
825             "test_files/system1/config/system1_config.file",
826             "test_files/system2/config/both_system_config.file",
827             "test_files/system2/config/everywhere",
828             "test_files/system2/config/system2_config.file",
829             "test_files/user/config/everywhere",
830             "test_files/user/config/myapp",
831             "test_files/user/config/user_config.file",
832         ].iter().map(PathBuf::from).collect::<Vec<_>>());
833 
834     let files = xd.list_config_files_once(".");
835     let mut files = files.into_iter().map(|p| make_relative(&p)).collect::<Vec<_>>();
836     files.sort();
837     assert_eq!(files,
838         [
839             "test_files/system1/config/both_system_config.file",
840             "test_files/system1/config/system1_config.file",
841             "test_files/system2/config/system2_config.file",
842             "test_files/user/config/everywhere",
843             "test_files/user/config/myapp",
844             "test_files/user/config/user_config.file",
845         ].iter().map(PathBuf::from).collect::<Vec<_>>());
846 }
847 
848 #[test]
test_prefix()849 fn test_prefix() {
850     let cwd = env::current_dir().unwrap().to_string_lossy().into_owned();
851     let xd = BaseDirectories::with_env("myapp", "", &*make_env(vec![
852             ("HOME", format!("{}/test_files/user", cwd)),
853             ("XDG_CACHE_HOME", format!("{}/test_files/user/cache", cwd)),
854         ])).unwrap();
855     assert_eq!(xd.place_cache_file("cache.db").unwrap(),
856                PathBuf::from(&format!("{}/test_files/user/cache/myapp/cache.db", cwd)));
857 }
858 
859 #[test]
test_profile()860 fn test_profile() {
861     let cwd = env::current_dir().unwrap().to_string_lossy().into_owned();
862     let xd = BaseDirectories::with_env("myapp", "default_profile", &*make_env(vec![
863             ("HOME", format!("{}/test_files/user", cwd)),
864             ("XDG_CONFIG_HOME", format!("{}/test_files/user/config", cwd)),
865             ("XDG_CONFIG_DIRS", format!("{}/test_files/system1/config", cwd)),
866        ])).unwrap();
867     assert_eq!(xd.find_config_file("system1_config.file").unwrap(),
868                // Does *not* include default_profile
869                PathBuf::from(&format!("{}/test_files/system1/config/myapp/system1_config.file", cwd)));
870     assert_eq!(xd.find_config_file("user_config.file").unwrap(),
871                // Includes default_profile
872                PathBuf::from(&format!("{}/test_files/user/config/myapp/default_profile/user_config.file", cwd)));
873 }
874