@@ -4,23 +4,32 @@ use std::fs::File;
44use std:: io:: { BufRead , BufReader } ;
55use std:: path:: { Path , PathBuf } ;
66
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)
814pub fn load_password (
915 host : & str ,
1016 port : u16 ,
1117 username : & str ,
1218 database : Option < & str > ,
19+ custom_paths : & [ impl AsRef < Path > ] ,
1320) -> 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 ( )
2433}
2534
2635#[ cfg( not( target_os = "windows" ) ) ]
0 commit comments