Skip to content

Commit 70deaf4

Browse files
author
masai1
committed
显示输出换用trait形式,方便生成不同的生成格式
1 parent 5750201 commit 70deaf4

File tree

5 files changed

+83
-71
lines changed

5 files changed

+83
-71
lines changed

Cargo.lock

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "ydcv"
3-
version = "0.2.0"
3+
version = "0.3.0"
44
authors = ["passchaos"]
55

66
[dependencies]

src/formatter.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
use ansi_term::Colour;
2+
3+
pub trait YDCVFormatter {
4+
fn head_color(&self) -> Colour {
5+
Colour::RGB(26, 159, 160)
6+
}
7+
8+
fn phonetic_color(&self) -> Colour {
9+
Colour::RGB(220, 186, 40)
10+
}
11+
12+
fn reference_color(&self) -> Colour {
13+
Colour::RGB(138, 88, 164)
14+
}
15+
16+
fn translation_description(&self) -> String;
17+
}

src/main.rs

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ extern crate slog_term;
1818
// extern crate slog_scope;
1919
extern crate slog_envlogger;
2020

21+
mod formatter;
2122
mod trans_type;
2223

2324
use std::io::{self, Read};
@@ -34,6 +35,8 @@ use std::str;
3435
use rocksdb::DB;
3536
use rocksdb::WriteBatch;
3637

38+
use formatter::YDCVFormatter;
39+
3740
const REQUEST_BASE: &'static str = "http://fanyi.youdao.com/openapi.do?keyfrom=ydcv-rust&key=379421805&type=data&doctype=json&version=1.1&q=";
3841

3942
fn get_remote_json_translation(query: &str, cache_db: &DB, update_cache: bool, logger: &slog::Logger) -> Result<String, YDCVError> {
@@ -48,7 +51,7 @@ fn get_remote_json_translation(query: &str, cache_db: &DB, update_cache: bool, l
4851
let mut res = try!(client.get(&request_url).header(Connection::close()).send());
4952

5053
let mut body = String::new();
51-
try!(res.read_to_string(&mut body));
54+
res.read_to_string(&mut body)?;
5255

5356
slog_debug!(logger, "json content: {}", body);
5457

@@ -58,14 +61,14 @@ fn get_remote_json_translation(query: &str, cache_db: &DB, update_cache: bool, l
5861
slog_debug!(logger, "更新本地缓存");
5962
let mut batch = WriteBatch::default();
6063
batch.delete(query.as_bytes());
61-
batch.put(query.as_bytes(), format!("{}", trans_result).as_bytes());
64+
batch.put(query.as_bytes(), trans_result.translation_description().as_bytes());
6265
cache_db.write(batch);
6366
} else {
6467
slog_debug!(logger, "写入本地缓存");
65-
try!(cache_db.put(query.as_bytes(), format!("{}", trans_result).as_bytes()));
68+
cache_db.put(query.as_bytes(), trans_result.translation_description().as_bytes())?;
6669
}
6770

68-
Ok(format!("{}", trans_result))
71+
Ok(trans_result.translation_description())
6972
}
7073

7174
fn main() {
@@ -74,7 +77,7 @@ fn main() {
7477
let root_log = slog::Logger::root(drain, o!("version" => "0.2"));
7578

7679
let matches = App::new("YDCV")
77-
.version("0.2")
80+
.version("0.3.0")
7881
.author("Greedwolf DSS <greedwolf.dss@gmail.com>")
7982
.about("Consolve version of Youdao")
8083
.arg(Arg::with_name("update").short("u").long("update").help("Update local cached word"))
@@ -95,7 +98,7 @@ fn main() {
9598
}) {
9699
Some(path) => path,
97100
None => {
98-
println!("没有缓存路径");
101+
slog_error!(root_log, "没有缓存路径");
99102
return;
100103
},
101104
};
@@ -104,7 +107,7 @@ fn main() {
104107
let db = match DB::open_default(cache_path.as_str()) {
105108
Ok(db) => db,
106109
Err(err) => {
107-
println!("无法创建RocksDB的存储目录 error: {}", err);
110+
slog_error!(root_log, "无法创建RocksDB的存储目录 error: {}", err);
108111
return;
109112
}
110113
};

src/trans_type.rs

Lines changed: 54 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,11 @@ use std::fmt::{self, Formatter, Display};
33
use ansi_term::Colour::{self, RGB};
44
use ansi_term::Style;
55

6+
use formatter::YDCVFormatter;
7+
68
#[derive(Debug, Deserialize)]
79
struct Basic {
810
explains: Vec<String>,
9-
phonetic: Option<String>,
1011
#[serde(rename="uk-phonetic")]
1112
uk_phonetic: Option<String>,
1213
#[serde(rename="us-phonetic")]
@@ -28,74 +29,65 @@ pub struct Translation {
2829
web: Option<Vec<Reference>>,
2930
}
3031

31-
const HEADER_COLOR: Colour = RGB(26, 159, 160);
32-
const PHONETIC_COLOR: Colour = RGB(220, 186, 40);
33-
const REFERENCE_COLOR: Colour = RGB(138, 88, 164);
34-
35-
impl Display for Reference {
36-
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
37-
let mut content = String::new();
38-
let sub_str_count = self.contents.len();
39-
40-
for (index, str) in self.contents.iter().enumerate() {
41-
content.push_str(str);
42-
43-
if index < sub_str_count - 1 {
44-
content.push_str("; ")
32+
impl YDCVFormatter for Translation {
33+
fn translation_description(&self) -> String {
34+
let yellow_star = Colour::Yellow.paint("*");
35+
let mut header_str = String::new();
36+
if let Some(ref translations) = self.translation {
37+
header_str.push_str(&format!(" {}\n\t{} ", Colour::Purple.paint("Translation:"), yellow_star));
38+
for (idx, value) in translations.iter().enumerate() {
39+
header_str.push_str(&value);
40+
if idx == translations.len() - 1 {
41+
header_str.push_str("\n");
42+
} else {
43+
header_str.push_str("; ");
44+
}
4545
}
4646
}
4747

48-
write!(f, "\n\t* {}\n\t {}", self.key, REFERENCE_COLOR.paint(content))
49-
}
50-
}
51-
52-
impl Display for Basic {
53-
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
54-
let mut tmp_str = String::new();
55-
56-
if let Some(ref phone) = self.phonetic {
57-
tmp_str = format!("\t[{}]\n", PHONETIC_COLOR.paint(phone.clone()));
58-
}
48+
let mut phonetic_str = String::new();
49+
if let Some(ref phonetic_basic) = self.basic {
50+
phonetic_str.push_str(&format!(" {}\n", Colour::Purple.paint("Word Explanation")));
51+
if let Some(ref uk_phonetic) = phonetic_basic.uk_phonetic {
52+
phonetic_str.push_str(&format!("\tUK: [{}]", Style::new().underline().paint(uk_phonetic.as_str())));
53+
if let Some(ref us_phonetic) = phonetic_basic.us_phonetic {
54+
phonetic_str.push_str(&format!(" US: [{}]\n", Style::new().underline().paint(us_phonetic.as_str())));
55+
};
56+
} else {
57+
if let Some(ref us_phonetic) = phonetic_basic.us_phonetic {
58+
phonetic_str.push_str(&format!("\tUS: [{}]\n", Style::new().underline().paint(us_phonetic.as_str())));
59+
}
60+
}
5961

60-
if let (Some(uk), Some(us)) = (self.uk_phonetic.clone(), self.us_phonetic.clone()) {
61-
tmp_str = format!("\tUK: [{}] US: [{}]\n", PHONETIC_COLOR.paint(uk), PHONETIC_COLOR.paint(us));
62+
for explain in &phonetic_basic.explains {
63+
phonetic_str.push_str(&format!("\t{} {}\n", yellow_star, explain));
64+
}
6265
}
6366

64-
write!(f, "{}\n {}:{}",
65-
tmp_str, HEADER_COLOR.paint("Word Explanation"), self.explains
66-
.iter()
67-
.fold(String::new(), |mut acc, ref x| {
68-
acc.push_str(format!("\n\t* {}", x).as_str());
69-
acc
70-
}))
71-
}
72-
}
73-
74-
impl Display for Translation {
75-
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
76-
let tmp_trans = match self.translation {
77-
Some(ref trans) => format!("\n {}\n\t* {}", HEADER_COLOR.paint("Translation:"), trans.first().expect("")),
78-
None => String::new(),
79-
};
80-
81-
let tmp_basic = match self.basic {
82-
Some(ref bsc) => format!("\n{}\n", bsc),
83-
None => String::new(),
84-
};
85-
86-
let tmp_web = match self.web {
87-
Some(ref vecs) => {
88-
let content = vecs.iter()
89-
.fold(String::new(), |mut acc, ref x| {
90-
acc.push_str(format!("{}", x).as_str());
91-
acc
92-
});
93-
format!("\n {}:{}", HEADER_COLOR.paint("Web Reference"), content)
67+
let mut reference_str = String::new();
68+
if let Some(ref web_ref) = self.web {
69+
reference_str.push_str(&format!(" {}\n", Colour::Purple.paint("Web Reference:")));
70+
for web in web_ref {
71+
reference_str.push_str(&format!("\t{} {}\n\t ", yellow_star, web.key));
72+
for (idx, value) in web.contents.iter().enumerate() {
73+
reference_str.push_str(&value);
74+
if idx != web.contents.len() - 1 {
75+
reference_str.push_str("; ");
76+
} else {
77+
reference_str.push_str("\n");
78+
}
79+
}
9480
}
95-
None => String::new(),
96-
};
81+
}
9782

98-
write!(f, "{}:{}{}{}",
99-
Style::new().underline().paint(self.query.clone()), tmp_trans, tmp_basic, tmp_web)
83+
if !header_str.is_empty() {
84+
header_str.push_str("\n");
85+
}
86+
header_str.push_str(&phonetic_str);
87+
if !reference_str.is_empty() {
88+
header_str.push_str("\n");
89+
}
90+
header_str.push_str(&reference_str);
91+
header_str
10092
}
10193
}

0 commit comments

Comments
 (0)