1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
// src/unix.rs
//
// Copyright (C) 2023-2024 James Petersen <m@jamespetersen.ca>
// Licensed under Apache 2.0 OR MIT. See LICENSE-APACHE or LICENSE-MIT
use var_os;
use PathBuf;
use Uid;
use User;
/// The error type returned by this library when errors occur.
pub type GetHomeError = Errno;
/// An identifier for a user.
;
/// Get a user's home directory path.
///
/// If some error occurs when obtaining the path, `Err` is returned. If no user
/// associated with `username` could be found, `Ok(None)` is returned. Otherwise,
/// the path to the user's home directory is returned.
///
/// This function uses the [`User::from_name`](nix::unistd::User::from_name)
/// method provided by the nix crate. That method uses the
/// [`getpwnam_r(3)`](https://man7.org/linux/man-pages/man3/getpwnam.3.html)
/// library function to get the home directory from the `/etc/passwd` file.
///
/// # Example
/// ```no_run
/// use homedir::unix::home;
/// use std::path::PathBuf;
///
/// # fn main() -> Result<(), homedir::unix::GetHomeError> {
/// // This assumes there is a user named `root` which has
/// // `/root` as a home directory.
/// assert_eq!(
/// Some(PathBuf::from("/root".to_owned())),
/// home("root")?
/// );
/// assert!(home("nonexistentuser")?.is_none());
/// # Ok(())
/// # }
/// ```
/// Get this process' user's home directory path.
///
/// This function will first check the `$HOME` environment variable. If this variable
/// does not exist, then the `/etc/passwd` file is checked.
///
/// The behaviour of this function is different from that of version 0.1.0.
/// Previously, this function would check the `/etc/passwd` file first, and,
/// should that fail, it would only check the `$HOME` environemnt variable if
/// the `check_env` feature was set. Now, it will check the `$HOME` environment
/// variable first, falling back on the `/etc/passwd` file should that fail.
/// To replicate the original behaviour of the function, do `UserIdentifier::my_id()?.to_home()?`.
/// Note that this can still return `None`, should the `/etc/passwd` file be missing an
/// entry for the user id of the program.
///
/// # Example
/// ```no_run
/// # fn main() -> Result<(), homedir::unix::GetHomeError> {
/// use homedir::unix::my_home;
///
/// // This assumes that the HOME environment variable is set to "/home/jpetersen".
/// assert_eq!(
/// std::path::Path::new("/home/jpetersen"),
/// my_home()?.unwrap().as_path()
/// );
/// # Ok(())
/// # }
/// ```