reups_lib/cogs.rs
1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
4 * Copyright Nate Lust 2018*/
5
6/*!
7The `cogs` module contains miscellaneous components used to interact with
8reups.
9
10These functions are defined here, to make them available in one central
11location within the `reups_lib` library. The main library re-exports this
12module, so end users of `reups_lib` should see all functions exposed there.
13*/
14
15use dirs;
16use std::env;
17use std::path::PathBuf;
18
19/** Macro used to print an error message to the console and terminate execution
20 *
21 * This may be replaced in the future with the use of a logging system.
22 */
23macro_rules! exit_with_message {
24 ($message:expr) => {
25 use std::process::exit;
26 eprintln!("{}", $message);
27 exit(1);
28 };
29}
30
31/// Returns the eups system path as determined from the EUPS_PATH environment variable.
32///
33/// If EUPS_PATH contains more than one database path, they should be seperated by a pipe
34/// character. This function will return the first database path, as it should be the most
35/// recently added to the environment.
36pub fn get_eups_path_from_env() -> PathBuf {
37 let env_var = env::var("EUPS_PATH").unwrap_or_else(|e| {
38 exit_with_message!(format!("Problem loading eups path: {}", e));
39 });
40 let eups_path_vec: Vec<&str> = env_var.split(":").collect();
41 // only return the first member of the vec, which should be the most
42 // recently added eups path
43 let eups_path_option = eups_path_vec.first();
44 let mut eups_path = match eups_path_option {
45 Some(eups_path) => PathBuf::from(eups_path),
46 None => {
47 exit_with_message!("Problem loading eups path from env var");
48 }
49 };
50 eups_path.push("ups_db");
51 if eups_path.is_dir() {
52 eups_path
53 } else {
54 exit_with_message!("Eups path defined in env var does not appear to be a directory");
55 }
56}
57
58/// Returns the path to a user database, defined in users home directory, if one is present.
59pub fn get_user_path_from_home() -> Option<PathBuf> {
60 let user_home = dirs::home_dir();
61 let mut user_path = user_home?;
62 user_path.push(".eups/ups_db");
63 if user_path.is_dir() {
64 Some(user_path)
65 } else {
66 None
67 }
68}