浏览代码

Merge command line arguments and `Config`

Johannes Hofmann 7 年前
父节点
当前提交
201e63197c
共有 2 个文件被更改,包括 60 次插入12 次删除
  1. 56
    1
      src/config.rs
  2. 4
    11
      src/main.rs

+ 56
- 1
src/config.rs 查看文件

1
+use clap;
1
 use std::fs::File;
2
 use std::fs::File;
2
 use std::io::{Read, Write};
3
 use std::io::{Read, Write};
3
 use std::path::{Path, PathBuf};
4
 use std::path::{Path, PathBuf};
13
     tile_cache_dir: PathBuf,
14
     tile_cache_dir: PathBuf,
14
     sources: Vec<(String, TileSource)>,
15
     sources: Vec<(String, TileSource)>,
15
     fps: f64,
16
     fps: f64,
17
+    use_network: bool,
18
+    async: bool,
16
 }
19
 }
17
 
20
 
18
 impl Config {
21
 impl Config {
19
-    pub fn load() -> Result<Config, String> {
22
+    pub fn from_arg_matches<'a>(matches: &clap::ArgMatches<'a>) -> Result<Config, String> {
23
+        let mut config = if let Some(config_path) = matches.value_of_os("config") {
24
+            Config::from_toml_file(config_path)?
25
+        } else {
26
+            Config::find_or_create()?
27
+        };
28
+
29
+        config.merge_arg_matches(matches);
30
+
31
+        Ok(config)
32
+    }
33
+
34
+    fn merge_arg_matches<'a>(&mut self, matches: &clap::ArgMatches<'a>) {
35
+        if let Some(Ok(fps)) = matches.value_of("fps").map(|s| s.parse()) {
36
+            self.fps = fps;
37
+        }
38
+
39
+        if matches.is_present("offline") {
40
+            self.use_network = false;
41
+        }
42
+
43
+        if matches.is_present("sync") {
44
+            self.async = false;
45
+        }
46
+    }
47
+
48
+    pub fn find_or_create() -> Result<Config, String> {
20
         if let Ok(xdg_dirs) = xdg::BaseDirectories::with_prefix("deltamap") {
49
         if let Ok(xdg_dirs) = xdg::BaseDirectories::with_prefix("deltamap") {
21
             if let Some(config_path) = xdg_dirs.find_config_file("config.toml") {
50
             if let Some(config_path) = xdg_dirs.find_config_file("config.toml") {
22
                 info!("load config from path {:?}", config_path);
51
                 info!("load config from path {:?}", config_path);
76
                     }
105
                     }
77
                 };
106
                 };
78
 
107
 
108
+                let use_network = {
109
+                    match table.get("use_network") {
110
+                        Some(&Value::Boolean(x)) => x,
111
+                        Some(_) => return Err("use_network has to be a boolean.".to_string()),
112
+                        None => true,
113
+                    }
114
+                };
115
+
116
+                let async = {
117
+                    match table.get("async") {
118
+                        Some(&Value::Boolean(x)) => x,
119
+                        Some(_) => return Err("async has to be a boolean.".to_string()),
120
+                        None => true,
121
+                    }
122
+                };
123
+
79
                 let sources_table = table.get("tile_sources")
124
                 let sources_table = table.get("tile_sources")
80
                     .ok_or_else(|| "missing \"tile_sources\" table".to_string())?
125
                     .ok_or_else(|| "missing \"tile_sources\" table".to_string())?
81
                     .as_table()
126
                     .as_table()
149
                         tile_cache_dir: tile_cache_dir,
194
                         tile_cache_dir: tile_cache_dir,
150
                         sources: sources_vec,
195
                         sources: sources_vec,
151
                         fps: fps,
196
                         fps: fps,
197
+                        use_network: use_network,
198
+                        async: async,
152
                     }
199
                     }
153
                 )
200
                 )
154
             },
201
             },
173
     pub fn fps(&self) -> f64 {
220
     pub fn fps(&self) -> f64 {
174
         self.fps
221
         self.fps
175
     }
222
     }
223
+
224
+    pub fn use_network(&self) -> bool {
225
+        self.use_network
226
+    }
227
+
228
+    pub fn async(&self) -> bool {
229
+        self.async
230
+    }
176
 }
231
 }
177
 
232
 
178
 #[cfg(test)]
233
 #[cfg(test)]

+ 4
- 11
src/main.rs 查看文件

177
 fn main() {
177
 fn main() {
178
     env_logger::init();
178
     env_logger::init();
179
 
179
 
180
-    let matches = args::parse();
181
-
182
-    let config = if let Some(config_path) = matches.value_of_os("config") {
183
-            config::Config::from_toml_file(config_path).unwrap()
184
-        } else {
185
-            config::Config::load().unwrap()
186
-        };
180
+    let config = config::Config::from_arg_matches(&args::parse()).unwrap();
187
 
181
 
188
     let mut sources = TileSources::new(config.tile_sources()).unwrap();
182
     let mut sources = TileSources::new(config.tile_sources()).unwrap();
189
 
183
 
205
             &cx,
199
             &cx,
206
             window.get_inner_size().unwrap(),
200
             window.get_inner_size().unwrap(),
207
             move || { proxy.wakeup().unwrap(); },
201
             move || { proxy.wakeup().unwrap(); },
208
-            !matches.is_present("offline"),
209
-            !matches.is_present("sync"),
202
+            config.use_network(),
203
+            config.async(),
210
         )
204
         )
211
     };
205
     };
212
 
206
 
215
         mouse_pressed: false,
209
         mouse_pressed: false,
216
     };
210
     };
217
 
211
 
218
-    let fps: f64 = matches.value_of("fps").map(|s| s.parse().unwrap()).unwrap_or_else(|| config.fps());
219
-    let duration_per_frame = Duration::from_millis((1000.0 / fps - 0.5).max(0.0).floor() as u64);
212
+    let duration_per_frame = Duration::from_millis((1000.0 / config.fps() - 0.5).max(0.0).floor() as u64);
220
     info!("milliseconds per frame: {}", dur_to_sec(duration_per_frame) * 1000.0);
213
     info!("milliseconds per frame: {}", dur_to_sec(duration_per_frame) * 1000.0);
221
 
214
 
222
     // estimated draw duration
215
     // estimated draw duration