-
Notifications
You must be signed in to change notification settings - Fork 0
/
fastresumes.rs
81 lines (59 loc) · 2.1 KB
/
fastresumes.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
use std::borrow::Cow;
use std::{fs, io};
use std::path::Path;
use yabel::{Decoder, Item, BString, Bencode};
fn main() -> io::Result<()> {
let source = "resumes"; // directory with `*.fastresume` files
let target = "patched-resumes"; // patched files will be placed here
replace_paths(source, target, "old", "new")?;
print_save_paths(target)?;
Ok(())
}
fn replace(input: &mut Cow<[u8]>, old: &[u8], new: &[u8]) {
if let Some(pos) = input.windows(old.len()).position(|window| window == old) {
input.to_mut().splice(pos..pos + old.len(), new.iter().cloned());
}
}
fn replace_paths<P: AsRef<Path>, S: AsRef<str>>(source: P, target: P, old: S, new: S) -> io::Result<()> {
let old = old.as_ref().as_bytes();
let new = new.as_ref().as_bytes();
fs::create_dir_all(&target)?;
let qbt_save_path = "qBt-savePath".into();
for entry in fs::read_dir(source)? {
let entry = entry?;
let path = entry.path();
let v = fs::read(&path)?;
let opt = Decoder::new(&v)
.decode()
.ok()
.and_then(|v| v.into_iter().next())
.and_then(|i| i.dictionary());
if let Some(mut bd) = opt {
if let Some(Item::String(BString(b))) = bd.0.get_mut(&qbt_save_path) {
replace(b, old, new);
}
let path = target.as_ref().join(path.file_name().expect("no filename"));
std::fs::write(path, bd.encode())?;
}
}
Ok(())
}
fn print_save_paths<P: AsRef<Path>>(source: P) -> io::Result<()> {
let qbt_save_path = "qBt-savePath".into();
for entry in fs::read_dir(source)? {
let entry = entry?;
let path = entry.path();
let v = fs::read(&path).unwrap();
let opt = Decoder::new(&v)
.decode()
.ok()
.and_then(|v| v.into_iter().next())
.and_then(|i| i.dictionary());
if let Some(bd) = opt {
if let Some(Item::String(s)) = bd.0.get(&qbt_save_path) {
println!("{}: {:?}", qbt_save_path, s);
}
}
}
Ok(())
}