Skip to content

Commit 819ba2b

Browse files
committed
implemented environment based config defaults
fixed a possible bug with config file reading when no write perm is granted
1 parent 8436db0 commit 819ba2b

File tree

1 file changed

+52
-30
lines changed

1 file changed

+52
-30
lines changed

src/lib/config.rs

Lines changed: 52 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@ use toml::decode_str;
33
use std::io::Write;
44
use std::io::Read;
55

6-
use std::fs::metadata;
7-
use std::fs::File;
6+
use std::fs::{File,metadata,OpenOptions};
7+
use std::path::Path;
88

99
use std::process::exit;
1010

@@ -87,39 +87,59 @@ pub struct Extensions {
8787
pub webm: Vec<i16>,
8888
}
8989

90-
/// create PathBuf by getting the current working dir
90+
/// Init config, reading from file or creating such
91+
#[cfg(not(test))]
9192
pub fn init_config() -> Config {
9293
let mut path = l_expect(lib::get_executable_folder(), "config folder"); // PathBuf
9394
path.push(CONFIG_PATH); // set_file_name doesn't return smth -> needs to be run on mut path
9495
trace!("config path {:?}",path );
95-
let config : Config;
96+
let data: String;
9697
if metadata(&path).is_ok() { // PathExt for path..as_path().exists() is unstable
9798
info!("Config file found.");
98-
config = l_expect(read_config(&path.to_str().unwrap()),"config read");
99+
data = l_expect(read_config(&path),"unable to read config!");
99100
}else{
100101
info!("Config file not found.");
101-
l_expect(create_config(&path.to_str().unwrap()), "config creation");
102+
data = create_config();
103+
l_expect(write_config_file(&path, &data),"unable to write config");
102104

103105
exit(0);
104106
}
105-
config
107+
108+
l_expect(parse_config(data), "unable to parse config")
109+
}
110+
111+
/// Config for test builds, using environment variables
112+
#[cfg(test)]
113+
pub fn init_config() -> Config {
114+
use std::env;
115+
macro_rules! env(
116+
($s:expr) => (match env::var($s) { Ok(val) => val, Err(e) => panic!("unable to read env var {}",$s),});
117+
);
118+
119+
let data = create_config();
120+
let mut conf = l_expect(parse_config(data),"invalid default config!");
121+
conf.general.ffmpeg_bin_dir = env!("ffmpeg_dir");
122+
conf
123+
}
124+
125+
/// Parse input toml to config struct
126+
fn parse_config(input: String) -> Result<Config, ConfigError> {
127+
match decode_str(&input) {
128+
None => Err(ConfigError::ParseError),
129+
Some(dconfig) => Ok(dconfig),
130+
}
106131
}
107132

108133
/// Read config from file.
109-
pub fn read_config(file: &str) -> Result<Config,ConfigError> {
110-
let mut f = try!(File::open(file).map_err(|_| ConfigError::ReadError));
111-
let mut toml = String::new();
112-
try!(f.read_to_string(&mut toml).map_err(|_| ConfigError::ReadError));
113-
let config: Config = match decode_str(&toml) {
114-
None => return Err(ConfigError::ParseError),
115-
Some(dconfig) => dconfig,
116-
};
117-
Ok(config)
134+
pub fn read_config(file: &Path) -> Result<String,ConfigError> {
135+
let mut f = try!(OpenOptions::new().read(true).open(file).map_err(|_| ConfigError::ReadError));
136+
let mut data = String::new();
137+
try!(f.read_to_string(&mut data).map_err(|_| ConfigError::ReadError));
138+
Ok(data)
118139
}
119140

120-
/// Create, read & write a new config.
121-
pub fn create_config(path: &str) -> Result<Config,ConfigError> {
122-
//TODO: replace with import_string
141+
/// Create a new config.
142+
pub fn create_config() -> String {
123143
trace!("Creating config..");
124144
let toml = r#"[db]
125145
user = "user"
@@ -131,15 +151,15 @@ ip = "127.0.0.1"
131151
[general]
132152
133153
# temporary dir for downloads before the conversion etc
134-
temp_dir = "/downloads/temp"
154+
temp_dir = "~/downloads/temp"
135155
136156
# final destination of downloaded files / playlists
137-
download_dir = "/downloads"
157+
download_dir = "~/downloads"
138158
download_mbps = 48 # MBit/s limit
139159
mp3_quality = 3 #see https://trac.ffmpeg.org/wiki/Encode/MP3
140160
141161
# folder in which the ffmpeg binary lies
142-
ffmpeg_bin_dir = "/ffmpeg/ffmpeg-2.6.2-64bit-static/"
162+
ffmpeg_bin_dir = "~/ffmpeg/ffmpeg-2.6.2-64bit-static/"
143163
144164
# additional lib callable in case of country-locks
145165
# will be called with {[optional arguments]} -q {quality} -r {speed limit} -f {dest. file} -v {video/audio -> true/false} {url}
@@ -183,12 +203,14 @@ mp4 = [-10,-11,-12,-13,-14,299,298,137,136,135,134,133,22,18]
183203
flv = []
184204
webm = [303,302,248]
185205
"#;
186-
let mut file = try!(File::create(path).map_err(|_| ConfigError::CreateError ));
187-
let config: Config = match decode_str(&toml) {
188-
None => return Err(ConfigError::ParseError),
189-
Some(dconfig) => dconfig,
190-
};
191-
trace!("Raw new config: {:?}", config);
192-
try!(file.write_all(toml.as_bytes()).map_err(|_| ConfigError::WriteError));
193-
Ok(config)
206+
trace!("Raw new config: {:?}", toml);
207+
208+
toml.to_owned()
209+
}
210+
211+
/// Writes the recived string into the file
212+
fn write_config_file(path: &Path, data: &str) -> Result<(),ConfigError> {
213+
let mut file = try!(File::create(path).map_err(|_| ConfigError::CreateError ));
214+
try!(file.write_all(data.as_bytes()).map_err(|_| ConfigError::WriteError));
215+
Ok(())
194216
}

0 commit comments

Comments
 (0)