Skip to content

Commit 10ffa89

Browse files
committed
Tidy persistence.
Seems I prefer Config over Settings. Ho hum.
1 parent 7965098 commit 10ffa89

File tree

7 files changed

+87
-80
lines changed

7 files changed

+87
-80
lines changed

src/backend.rs

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,9 @@ use crossbeam_channel::{bounded, Receiver, RecvTimeoutError};
77

88
use crate::background::BackgroundHandle;
99
use crate::compression::BackgroundCompactor;
10-
use crate::filesdb::FilesDb;
1110
use crate::folder::{FileKind, FolderInfo, FolderScan};
1211
use crate::gui::{GuiRequest, GuiWrapper};
13-
use crate::settings;
12+
use crate::persistence::{config, pathdb};
1413

1514
pub struct Backend<T> {
1615
gui: GuiWrapper<T>,
@@ -78,9 +77,9 @@ impl<T> Backend<T> {
7877
}
7978

8079
fn scan_loop(&mut self, path: PathBuf) {
81-
let settings = settings::get();
80+
let excludes = config().read().unwrap().current().globset().expect("globs");
8281

83-
let scanner = FolderScan::new(path, settings.globset().expect("globs"));
82+
let scanner = FolderScan::new(path, excludes);
8483
let task = BackgroundHandle::spawn(scanner);
8584
let start = Instant::now();
8685

@@ -143,7 +142,7 @@ impl<T> Backend<T> {
143142
let (send_file, send_file_rx) = bounded::<Option<(PathBuf, u64)>>(1);
144143
let (recv_result_tx, recv_result) = bounded::<(PathBuf, io::Result<bool>)>(1);
145144

146-
let compression = Some(settings::get().compression);
145+
let compression = Some(config().read().unwrap().current().compression);
147146
let compactor = BackgroundCompactor::new(compression, send_file_rx, recv_result_tx);
148147
let task = BackgroundHandle::spawn(compactor);
149148
let start = Instant::now();
@@ -160,7 +159,8 @@ impl<T> Backend<T> {
160159
let old_size = folder.physical_size;
161160
let compressible_size = folder.summary().compressible.physical_size;
162161

163-
let mut incompressible = FilesDb::borrow();
162+
let incompressible = pathdb();
163+
let mut incompressible = incompressible.write().unwrap();
164164
let _ = incompressible.load();
165165

166166
self.gui.compacting();
@@ -303,13 +303,13 @@ impl<T> Backend<T> {
303303
let _ = incompressible.save();
304304

305305
let new_size = folder.physical_size;
306-
let s = settings::get();
306+
let decimal = config().read().unwrap().current().decimal;
307307

308308
let msg = format!(
309309
"Compacted {} in {} files, saving {} in {:.2?}",
310-
format_size(compressible_size, s.decimal),
310+
format_size(compressible_size, decimal),
311311
done,
312-
format_size(old_size - new_size, s.decimal),
312+
format_size(old_size - new_size, decimal),
313313
start.elapsed()
314314
);
315315

@@ -459,7 +459,10 @@ impl<T> Backend<T> {
459459
let msg = format!(
460460
"Expanded {} files wasting {} in {:.2?}",
461461
done,
462-
format_size(new_size - old_size, settings::get().decimal),
462+
format_size(
463+
new_size - old_size,
464+
config().read().unwrap().current().decimal
465+
),
463466
start.elapsed()
464467
);
465468

src/compact.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -373,5 +373,9 @@ fn compact_works_i_guess() {
373373
uncompress_file(&path).expect("uncompress_file");
374374
assert_eq!(None, detect_compression(&path).expect("detect_compression"));
375375
compress_file(&path, Compression::default()).expect("compress_file");
376+
assert_eq!(
377+
Some(Compression::default()),
378+
detect_compression(&path).expect("detect_compression")
379+
);
376380
}
377381
}

src/settings.rs renamed to src/config.rs

Lines changed: 19 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,13 @@
1-
use std::path::Path;
2-
use std::path::PathBuf;
3-
use std::sync::Mutex;
1+
use std::io;
2+
use std::path::{Path, PathBuf};
43

54
use globset::{Glob, GlobSet, GlobSetBuilder};
6-
use lazy_static::lazy_static;
75
use serde_derive::{Deserialize, Serialize};
86

97
use crate::compact::Compression;
108

119
#[derive(Debug, Default)]
12-
pub struct Settings {
10+
pub struct ConfigFile {
1311
backing: Option<PathBuf>,
1412
config: Config,
1513
}
@@ -78,25 +76,20 @@ impl Default for Config {
7876
}
7977
}
8078

81-
impl Settings {
82-
pub fn set_backing<P: AsRef<Path>>(&mut self, p: P) {
83-
self.backing = Some(p.as_ref().to_owned());
84-
}
85-
86-
pub fn load(&mut self) {
87-
match &self.backing {
88-
Some(path) => {
89-
if let Ok(data) = std::fs::read(path) {
90-
if let Ok(c) = serde_json::from_slice::<Config>(&data) {
91-
self.set(c);
92-
}
93-
}
94-
}
95-
None => (),
79+
impl ConfigFile {
80+
pub fn new<P: AsRef<Path>>(path: P) -> Self {
81+
Self {
82+
backing: Some(path.as_ref().to_owned()),
83+
config: std::fs::read(path)
84+
.and_then(|data| {
85+
serde_json::from_slice::<Config>(&data)
86+
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
87+
})
88+
.unwrap_or_default(),
9689
}
9790
}
9891

99-
pub fn save(&mut self) -> std::io::Result<()> {
92+
pub fn save(&self) -> io::Result<()> {
10093
match &self.backing {
10194
Some(path) => {
10295
if let Some(dir) = path.parent() {
@@ -110,12 +103,12 @@ impl Settings {
110103
}
111104
}
112105

113-
pub fn set(&mut self, c: Config) {
114-
self.config = c;
106+
pub fn current(&self) -> Config {
107+
self.config.clone()
115108
}
116109

117-
pub fn get(&self) -> Config {
118-
self.config.clone()
110+
pub fn replace(&mut self, c: Config) {
111+
self.config = c;
119112
}
120113
}
121114

@@ -129,30 +122,8 @@ impl Config {
129122
}
130123
}
131124

132-
lazy_static! {
133-
static ref SETTINGS: Mutex<Settings> = Mutex::new(Settings::default());
134-
}
135-
136-
pub fn get() -> Config {
137-
SETTINGS.lock().expect("Settings").get()
138-
}
139-
140-
pub fn set(s: Config) {
141-
SETTINGS.lock().expect("Settings").set(s);
142-
}
143-
144-
pub fn load<P: AsRef<Path>>(p: P) {
145-
let mut s = SETTINGS.lock().unwrap();
146-
s.set_backing(p);
147-
s.load();
148-
}
149-
150-
pub fn save() {
151-
SETTINGS.lock().unwrap().save();
152-
}
153-
154125
#[test]
155-
fn test_settings() {
126+
fn test_config() {
156127
let s = Config::default();
157128

158129
assert!(s.globset().is_ok());

src/folder.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use winapi::um::winnt::{
1414
};
1515

1616
use crate::background::{Background, ControlToken};
17-
use crate::filesdb::FilesDb;
17+
use crate::persistence::pathdb;
1818

1919
#[derive(Debug, Clone, Serialize)]
2020
pub struct FileInfo {
@@ -173,7 +173,8 @@ impl Background for FolderScan {
173173
fn run(&self, control: &ControlToken<Self::Status>) -> Self::Output {
174174
let mut ds = FolderInfo::new(&self.path);
175175
let excludes = self.excludes.lock().expect("exclude lock");
176-
let mut incompressible = FilesDb::borrow();
176+
let incompressible = pathdb();
177+
let mut incompressible = incompressible.write().unwrap();
177178
let _ = incompressible.load();
178179

179180
let mut last_status = Instant::now();

src/gui.rs

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@ use winapi::um::knownfolders;
1414
use crate::backend::Backend;
1515
use crate::compact::system_supports_compression;
1616
use crate::folder::FolderSummary;
17-
use crate::persistence;
18-
use crate::settings::{self, Config};
17+
use crate::persistence::{self, config};
18+
use crate::config::Config;
1919

2020
// messages received from the GUI
2121
#[derive(Deserialize, Debug, Clone)]
@@ -99,7 +99,7 @@ impl<T> GuiWrapper<T> {
9999
}
100100

101101
pub fn settings(&self) {
102-
let s = settings::get();
102+
let s = config().read().unwrap().current();;
103103
self.send(&GuiResponse::Settings {
104104
decimal: s.decimal,
105105
compression: s.compression.to_string(),
@@ -214,12 +214,15 @@ pub fn spawn_gui() {
214214
excludes: s.excludes.join("\n"),
215215
},
216216
);
217-
webview
218-
.dialog()
219-
.info("Settings Saved", "Settings Updated")
220-
.ok();
221-
settings::set(s);
222-
settings::save();
217+
let c = config();
218+
let mut c = c.write().unwrap();
219+
c.replace(s);
220+
if let Err(e) = c.save() {
221+
webview
222+
.dialog()
223+
.error("Settings Error", format!("Error saving settings: {:?}", e))
224+
.ok();
225+
}
223226
}
224227
}
225228
Ok(GuiRequest::ResetSettings) => {
@@ -233,8 +236,15 @@ pub fn spawn_gui() {
233236
excludes: s.excludes.join("\n"),
234237
},
235238
);
236-
settings::set(s);
237-
settings::save();
239+
let c = config();
240+
let mut c = c.write().unwrap();
241+
c.replace(s);
242+
if let Err(e) = c.save() {
243+
webview
244+
.dialog()
245+
.error("Settings Error", format!("Error saving settings: {:?}", e))
246+
.ok();
247+
}
238248
}
239249
Ok(msg) => {
240250
from_gui.send(msg).expect("GUI message queue");
@@ -249,7 +259,7 @@ pub fn spawn_gui() {
249259
.build()
250260
.expect("WebView");
251261

252-
persistence::load();
262+
persistence::init();
253263

254264
if !system_supports_compression().unwrap_or_default() {
255265
webview

src/main.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
2+
#![allow(non_snake_case)]
23

34
mod backend;
45
mod background;
56
mod compact;
67
mod compression;
7-
mod filesdb;
88
mod folder;
99
mod gui;
1010
mod persistence;
11-
mod settings;
11+
mod config;
1212

1313
fn main() {
1414
if let Err(e) = std::panic::catch_unwind(gui::spawn_gui) {

src/persistence.rs

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,29 @@
11
use directories::ProjectDirs;
2+
use hashfilter::HashFilter;
3+
use lazy_static::lazy_static;
4+
use std::sync::{Arc, RwLock};
25

3-
use crate::filesdb::FilesDb;
4-
use crate::settings;
6+
use crate::config::ConfigFile;
57

6-
pub fn load() {
7-
let dirs = ProjectDirs::from("", "Freaky", "Compactor").expect("dirs");
8+
lazy_static! {
9+
static ref PATHDB: Arc<RwLock<HashFilter>> = Arc::new(RwLock::new(HashFilter::default()));
10+
static ref CONFIG: Arc<RwLock<ConfigFile>> = Arc::new(RwLock::new(ConfigFile::default()));
11+
}
12+
13+
pub fn init() {
14+
if let Some(dirs) = ProjectDirs::from("", "Freaky", "Compactor") {
15+
pathdb()
16+
.write()
17+
.unwrap()
18+
.set_backing(dirs.cache_dir().join("incompressible.dat"));
19+
*config().write().unwrap() = ConfigFile::new(dirs.config_dir().join("config.json"));
20+
}
21+
}
22+
23+
pub fn config() -> Arc<RwLock<ConfigFile>> {
24+
CONFIG.clone()
25+
}
826

9-
FilesDb::borrow().set_backing(dirs.cache_dir().join("incompressible.dat"));
10-
settings::load(dirs.config_dir().join("config.json"));
27+
pub fn pathdb() -> Arc<RwLock<HashFilter>> {
28+
PATHDB.clone()
1129
}

0 commit comments

Comments
 (0)