intercept/
parameters.rs

1/*  Copyright (C) 2012-2018 by László Nagy
2    This file is part of Bear.
3
4    Bear is a tool to generate compilation database for clang tooling.
5
6    Bear is free software: you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation, either version 3 of the License, or
9    (at your option) any later version.
10
11    Bear is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20use std::env;
21use std::io;
22use std::ffi::OsString;
23use serde_json;
24
25use Result;
26use Error;
27
28
29#[derive(Serialize, Deserialize)]
30pub struct Parameters {
31    cc: OsString,
32    cxx: OsString,
33    target: OsString,
34}
35
36impl Parameters {
37    pub fn new(cc: &str, cxx: &str, target: &str) -> Parameters {
38        Parameters {
39            cc: OsString::from(cc),
40            cxx: OsString::from(cxx),
41            target: OsString::from(target)
42        }
43    }
44
45    pub fn get_cc(&self) -> &OsString {
46        &self.cc
47    }
48
49    pub fn get_cxx(&self) -> &OsString {
50        &self.cxx
51    }
52
53    pub fn get_target(&self) -> &OsString {
54        &self.target
55    }
56
57    /// Serialize the parameters into a string.
58    pub fn write(&self) -> Result<OsString> {
59        let result = serde_json::to_string(self)?;
60        Ok(OsString::from(result))
61    }
62
63    /// Deserialize the parameters from a string.
64    pub fn read(source: &OsString) -> Result<Parameters> {
65        match source.to_str() {
66            Some(string) => {
67                let result = serde_json::from_str(string)?;
68                Ok(result)
69            }
70            None => Err(Error::Io(io::Error::from(io::ErrorKind::InvalidInput)))
71        }
72    }
73}
74
75
76const ENV_KEY: &'static str = "__BEAR";
77
78/// Create a key-value pair from parameters to store that in environment.
79pub fn to_env(parameters: &Parameters) -> Result<(OsString, OsString)> {
80    let key: OsString = OsString::from(ENV_KEY);
81    parameters.write().map(|value| (key, value))
82}
83
84/// Read parameters from environment variables.
85pub fn from_env() -> Result<Parameters> {
86    let value = env::var(ENV_KEY)?;
87    Parameters::read(&OsString::from(&value))
88}