@@ -4,23 +4,32 @@ use std::fs::File;
4
4
use std:: io:: { BufRead , BufReader } ;
5
5
use std:: path:: { Path , PathBuf } ;
6
6
7
- /// try to load a password from the various pgpass file locations
7
+ /// Try to load a password from the various pgpass file locations.
8
+ ///
9
+ /// Loading is attempted in the following order:
10
+ /// 1. Path given via the `PGPASSFILE` environment variable.
11
+ /// 2. Paths given via custom_paths.
12
+ /// 3. Default path (`~/.pgpass` on Linux and `%APPDATA%/postgres/pgpass.conf`
13
+ /// on Windows)
8
14
pub fn load_password (
9
15
host : & str ,
10
16
port : u16 ,
11
17
username : & str ,
12
18
database : Option < & str > ,
19
+ custom_paths : & [ impl AsRef < Path > ] ,
13
20
) -> Option < String > {
14
- let custom_file = var_os ( "PGPASSFILE" ) ;
15
- if let Some ( file) = custom_file {
16
- if let Some ( password) =
17
- load_password_from_file ( & PathBuf :: from ( file) , host, port, username, database)
18
- {
19
- return Some ( password) ;
20
- }
21
- }
22
-
23
- load_password_from_file ( & default_path ( ) ?, host, port, username, database)
21
+ let env_path = var_os ( "PGPASSFILE" ) . map ( PathBuf :: from) ;
22
+ let default_path = default_path ( ) ;
23
+
24
+ let path_iter = env_path
25
+ . as_deref ( )
26
+ . into_iter ( )
27
+ . chain ( custom_paths. iter ( ) . map ( AsRef :: as_ref) )
28
+ . chain ( default_path. as_deref ( ) ) ;
29
+
30
+ path_iter
31
+ . filter_map ( |path| load_password_from_file ( path, host, port, username, database) )
32
+ . next ( )
24
33
}
25
34
26
35
#[ cfg( not( target_os = "windows" ) ) ]
0 commit comments