Skip to main content

pgdo/
util.rs

1use std::env;
2use std::ffi::OsString;
3use std::path::Path;
4
5type PrependedPath = Result<OsString, env::JoinPathsError>;
6
7/// Prepend the given `dir` to the given `path`.
8///
9/// If `dir` is already in `path` it is moved to first place. Note that this
10/// does *not* update `PATH` in the environment.
11pub(crate) fn prepend_to_path(dir: &Path, path: Option<OsString>) -> PrependedPath {
12    Ok(match path {
13        None => env::join_paths([dir])?,
14        Some(path) => {
15            let mut paths = vec![dir.to_path_buf()];
16            paths.extend(env::split_paths(&path).filter(|path| path != dir));
17            env::join_paths(paths)?
18        }
19    })
20}
21
22#[derive(thiserror::Error, Debug)]
23pub enum CurrentUserError {
24    #[error("user name in {0:?} environment variable cannot be decoded: {1:?}")]
25    NotUnicode(&'static str, std::ffi::OsString),
26    #[error("system error")]
27    System(#[from] nix::Error),
28    #[error("user unknown")]
29    Unknown,
30}
31
32/// Determine the current user name to use.
33///
34/// Checks the `PGUSER` then `USER` environment variables first, which allows
35/// the invoking user to override the current user name. If those are not set,
36/// it obtains the user name from the OS.
37pub fn current_user() -> Result<String, CurrentUserError> {
38    use nix::unistd::{getuid, User};
39    use std::env::{var, VarError::*};
40    match var("PGUSER") {
41        Ok(user) if !user.trim().is_empty() => Ok(user),
42        Err(NotUnicode(value)) => Err(CurrentUserError::NotUnicode("PGUSER", value)),
43        Ok(_) | Err(NotPresent) => match var("USER") {
44            Ok(user) if !user.trim().is_empty() => Ok(user),
45            Err(NotUnicode(value)) => Err(CurrentUserError::NotUnicode("USER", value)),
46            Ok(_) | Err(NotPresent) => User::from_uid(getuid())?
47                .map(|user| user.name)
48                .ok_or(CurrentUserError::Unknown),
49        },
50    }
51}
52
53#[cfg(test)]
54mod tests {
55    use std::env;
56
57    type TestResult = Result<(), Box<dyn std::error::Error>>;
58
59    #[test]
60    fn test_prepend_to_path_prepends_given_dir_to_path() -> TestResult {
61        let path = env::join_paths([tempfile::tempdir()?.path(), tempfile::tempdir()?.path()])?;
62        let tempdir = tempfile::tempdir()?;
63        let expected = {
64            let mut tmp = vec![tempdir.path().to_path_buf()];
65            tmp.extend(env::split_paths(&path));
66            env::join_paths(tmp)?
67        };
68        let observed = { super::prepend_to_path(tempdir.path(), Some(path))? };
69        assert_eq!(expected, observed);
70        Ok(())
71    }
72
73    #[test]
74    fn test_prepend_to_path_moves_dir_to_front_of_path() -> TestResult {
75        let tempdir = tempfile::tempdir()?;
76        let path = env::join_paths([
77            tempfile::tempdir()?.path(),
78            tempfile::tempdir()?.path(),
79            tempdir.path(),
80        ])?;
81        let expected = {
82            let mut tmp = vec![tempdir.path().to_path_buf()];
83            tmp.extend(env::split_paths(&path).take(2));
84            env::join_paths(tmp)?
85        };
86        let observed = { super::prepend_to_path(tempdir.path(), Some(path))? };
87        assert_eq!(expected, observed);
88        Ok(())
89    }
90
91    #[test]
92    fn test_prepend_to_path_returns_given_dir_if_path_is_empty() -> TestResult {
93        let tempdir = tempfile::tempdir()?;
94        let expected = tempdir.path();
95        let observed = super::prepend_to_path(tempdir.path(), None)?;
96        assert_eq!(expected, observed);
97        Ok(())
98    }
99}