shell_rs/
pwd.rs

1// Copyright (c) 2021 Xu Shaohua <shaohua@biofan.org>. All rights reserved.
2// Use of this source is governed by General Public License that can be found
3// in the LICENSE file.
4
5use std::ffi::OsStr;
6use std::os::unix::ffi::OsStrExt;
7use std::path::PathBuf;
8
9use crate::error::Error;
10
11#[derive(Debug, Clone, Copy, PartialEq)]
12pub enum Mode {
13    /// Use PWD from environment, even if it contains symlinks.
14    Logical,
15
16    /// Avoid all symlinks.
17    Physical,
18}
19
20impl Default for Mode {
21    fn default() -> Self {
22        Self::Physical
23    }
24}
25
26/// Print name of current/working directory.
27pub fn pwd(mode: Mode) -> Result<PathBuf, Error> {
28    if mode == Mode::Logical {
29        // From environment.
30        if let Ok(cwd) = std::env::var("PWD") {
31            return Ok(PathBuf::from(&cwd));
32        }
33    }
34
35    // From system call.
36    let mut path_buf = [0_u8; nc::PATH_MAX as usize + 1];
37    let path_len = unsafe { nc::getcwd(path_buf.as_mut_ptr() as usize, path_buf.len())? };
38    // Remove null-terminal char.
39    let path_len = path_len as usize - 1;
40    let cwd = OsStr::from_bytes(&path_buf[0..path_len]);
41    Ok(PathBuf::from(cwd))
42}
43
44#[cfg(test)]
45mod tests {
46    use super::*;
47
48    #[test]
49    fn test_pwd() {
50        let ret = pwd(Mode::Logical);
51        assert!(ret.is_ok());
52
53        let ret = pwd(Mode::Physical);
54        assert!(ret.is_ok());
55        assert_eq!(ret.unwrap(), std::env::current_dir().unwrap());
56    }
57}