solve a thousand clippy lint errors

This commit is contained in:
Abraham Toriz 2021-08-02 19:10:34 -05:00
parent 7d53546646
commit 5186b7c159
No known key found for this signature in database
GPG Key ID: D5B4A746DB5DD42A
18 changed files with 62 additions and 60 deletions

View File

@ -13,7 +13,7 @@ impl BackendCommand {
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.output().map_err(|e| Sqlite3CommandFailed(e))?
.output().map_err(Sqlite3CommandFailed)?
.status;
if status.success() {

View File

@ -54,14 +54,14 @@ where
Some(Sheet::Full) => db.entries_full(start, end)?,
Some(Sheet::Sheet(name)) => db.entries_by_sheet(&name, start, end)?,
None => {
let current_sheet = db.current_sheet()?.unwrap_or("default".into());
let current_sheet = db.current_sheet()?.unwrap_or_else(|| "default".into());
db.entries_by_sheet(&current_sheet, start, end)?
}
};
if let Some(re) = grep {
entries.retain(|e| re.is_match(e.note.as_ref().unwrap_or(&String::new())));
entries.retain(|e| re.is_match(&e.note.clone().unwrap_or_else(String::new)));
}
let (entries, needs_warning) = entries_or_warning(entries, db)?;

View File

@ -41,7 +41,7 @@ impl<'a> Command<'a> for InCommand {
E: Write,
{
let start = args.at.unwrap_or(now);
let sheet = db.current_sheet()?.unwrap_or("default".into());
let sheet = db.current_sheet()?.unwrap_or_else(|| "default".into());
if db.running_entry(&sheet)?.is_some() {
writeln!(out, "Timer is already running for sheet '{}'", sheet)?;
@ -51,12 +51,10 @@ impl<'a> Command<'a> for InCommand {
let note = if let Some(note) = args.note {
Some(note)
} else if !config.require_note {
None
} else {
if !config.require_note {
None
} else {
Some(editor::get_string(config.note_editor.as_ref())?)
}
Some(editor::get_string(config.note_editor.as_ref())?)
};
let (start, needs_warning) = time_or_warning(start, db)?;

View File

@ -48,10 +48,10 @@ impl<'a> Command<'a> for KillCommand {
match args {
Args::Id(id) => {
if let Some(entry) = db.entry_by_id(id)? {
write!(out, "are you sure you want to delete entry {}? ({}) [y/n] ", entry.id, entry.note.unwrap_or("".into()))?;
write!(out, "are you sure you want to delete entry {}? ({}) [y/n] ", entry.id, entry.note.unwrap_or_else(|| "".into()))?;
io::stdout().flush()?;
if read_line().to_lowercase().starts_with("y") {
if read_line().to_lowercase().starts_with('y') {
db.delete_entry_by_id(id)?;
writeln!(out, "It's dead")?;
} else {
@ -67,7 +67,7 @@ impl<'a> Command<'a> for KillCommand {
write!(out, "are you sure you want to delete {} entries on sheet \"{}\"? [y/n] ", n, sheet)?;
io::stdout().flush()?;
if read_line().to_lowercase().starts_with("y") {
if read_line().to_lowercase().starts_with('y') {
db.delete_entries_in_sheet(&sheet)?;
writeln!(out, "They're gone")?;
} else {

View File

@ -72,13 +72,15 @@ impl<'a> Command<'a> for ListCommand {
(
if current.as_ref() == Some(&key) {
"*".into()
} else if last.as_ref() == Some(&key) {
"-".into()
} else {
if last.as_ref() == Some(&key) { "-".into() } else { "".into() }
"".into()
},
key,
format_duration(
now - entries.iter().filter(|e| e.end.is_none()).next().map(|e| e.start).unwrap_or(now)
now - entries.iter().find(|e| e.end.is_none()).map(|e| e.start).unwrap_or(now)
),
format_duration(

View File

@ -71,7 +71,7 @@ impl<'a> Command<'a> for NowCommand {
},
entry.sheet,
format_duration(now - entry.start),
entry.note.unwrap_or("".into())
entry.note.unwrap_or_else(|| "".into())
]);
}

View File

@ -34,7 +34,7 @@ impl<'a> Command<'a> for OutCommand {
fn handle<D: Database, O: Write, E: Write>(args: Self::Args, db: &mut D, out: &mut O, err: &mut E, _config: &Config, now: DateTime<Utc>) -> Result<()> {
let end = args.at.unwrap_or(now);
let sheet = db.current_sheet()?.unwrap_or("default".into());
let sheet = db.current_sheet()?.unwrap_or_else(|| "default".into());
let (end, needs_warning) = time_or_warning(end, db)?;

View File

@ -38,7 +38,7 @@ where
writeln!(
out,
"Resuming \"{}\" from entry #{}",
entry.note.as_ref().unwrap_or(&"".to_owned()), entry.id
entry.note.clone().unwrap_or_else(|| "".to_owned()), entry.id
)?;
r#in::InCommand::handle(r#in::Args {
@ -58,7 +58,7 @@ impl<'a> Command<'a> for ResumeCommand {
O: Write,
E: Write,
{
let current_sheet = db.current_sheet()?.unwrap_or("default".to_owned());
let current_sheet = db.current_sheet()?.unwrap_or_else(|| "default".to_owned());
// First try to process using the given id
if let Some(entry_id) = args.id {

View File

@ -37,7 +37,7 @@ impl<'a> Command<'a> for SheetCommand {
E: Write,
{
if let Some(sheet) = args.sheet {
let current_sheet = db.current_sheet()?.unwrap_or("default".into());
let current_sheet = db.current_sheet()?.unwrap_or_else(|| "default".into());
// sheet given, switch to it
let move_to = if sheet == "-" {
@ -49,14 +49,12 @@ Hint: remember that giving - (a dash) as argument to t sheet switches to the las
return Ok(());
}
} else {
if sheet == current_sheet {
writeln!(out, "Already on sheet '{}'", sheet)?;
} else if sheet == current_sheet {
writeln!(out, "Already on sheet '{}'", sheet)?;
return Ok(());
} else {
sheet
}
return Ok(());
} else {
sheet
};
db.set_last_sheet(&current_sheet)?;

View File

@ -69,9 +69,9 @@ impl Config {
// first try from env variable TIMETRAP_CONFIG_FILE
if let Ok(value) = env::var("TIMETRAP_CONFIG_FILE") {
if value.ends_with(".toml") {
return Ok(Self::read_from_toml(value)?);
return Self::read_from_toml(value);
} else {
return Ok(Self::read_from_yaml(value)?);
return Self::read_from_yaml(value);
}
}

View File

@ -166,7 +166,7 @@ pub trait Database {
}
fn running_entries(&self) -> Result<Vec<Entry>> {
Ok(self.entry_query("select * from entries where end is null order by sheet asc", &[])?)
self.entry_query("select * from entries where end is null order by sheet asc", &[])
}
fn last_checkout_of_sheet(&self, sheet: &str) -> Result<Option<Entry>> {
@ -174,7 +174,7 @@ pub trait Database {
}
fn delete_entry_by_id(&mut self, id: u64) -> Result<()> {
Ok(self.execute("delete from entries where id=?1", &[&id])?)
self.execute("delete from entries where id=?1", &[&id])
}
fn delete_entries_in_sheet(&mut self, sheet: &str) -> Result<()> {
@ -217,7 +217,7 @@ pub trait Database {
}
fn unset_last_sheet(&mut self) -> Result<()> {
Ok(self.execute("delete from meta where key='last_sheet'", &[])?)
self.execute("delete from meta where key='last_sheet'", &[])
}
fn version(&self) -> Result<DBVersion> {

View File

@ -11,7 +11,7 @@ pub fn get_string(note_editor: Option<&String>) -> Result<String> {
} else {
return Err(EditorIsEmpty);
};
let parts: Vec<_> = note_editor.split(" ").filter(|p| p.len() > 0).collect();
let parts: Vec<_> = note_editor.split(' ').filter(|p| !p.is_empty()).collect();
let editor = if let Some(name) = parts.get(0) {
name.to_owned()
} else {

View File

@ -20,21 +20,21 @@ pub fn print_formatted<W: Write>(entries: Vec<Entry>, out: &mut W, ids: bool) ->
wtr.write_record(&[
entry.id.to_string(),
entry.start.to_rfc3339_opts(SecondsFormat::Secs, true),
entry.end.map(|t| t.to_rfc3339_opts(SecondsFormat::Secs, true)).unwrap_or("".into()),
entry.note.unwrap_or("".into()),
entry.end.map(|t| t.to_rfc3339_opts(SecondsFormat::Secs, true)).unwrap_or_else(|| "".into()),
entry.note.unwrap_or_else(|| "".into()),
entry.sheet,
])?;
} else {
wtr.write_record(&[
entry.start.to_rfc3339_opts(SecondsFormat::Secs, true),
entry.end.map(|t| t.to_rfc3339_opts(SecondsFormat::Secs, true)).unwrap_or("".into()),
entry.note.unwrap_or("".into()),
entry.end.map(|t| t.to_rfc3339_opts(SecondsFormat::Secs, true)).unwrap_or_else(|| "".into()),
entry.note.unwrap_or_else(|| "".into()),
entry.sheet,
])?;
}
}
wtr.flush().map_err(|e| IOError(e))
wtr.flush().map_err(IOError)
}
#[cfg(test)]

View File

@ -5,7 +5,7 @@ use chrono::{DateTime, Utc};
use crate::models::Entry;
use crate::error::Result;
const ICAL_TIME_FORMAT: &'static str = "%Y%m%dT%H%M%SZ";
const ICAL_TIME_FORMAT: &str = "%Y%m%dT%H%M%SZ";
pub fn print_formatted<W: Write>(entries: Vec<Entry>, out: &mut W, now: DateTime<Utc>) -> Result<()> {
writeln!(out, "BEGIN:VCALENDAR")?;
@ -19,7 +19,7 @@ pub fn print_formatted<W: Write>(entries: Vec<Entry>, out: &mut W, now: DateTime
for entry in entries.into_iter() {
let uid = format!("tiempo-{id}", id=entry.id);
let note = entry.note.unwrap_or("".into());
let note = entry.note.unwrap_or_else(|| "".into());
writeln!(out, "BEGIN:VEVENT")?;
writeln!(out, "DESCRIPTION:{note}", note=note)?;

View File

@ -79,12 +79,12 @@ pub fn print_formatted<W: Write>(entries: Vec<Entry>, out: &mut W, now: DateTime
entry.start.with_timezone(&Local).naive_local(),
t.with_timezone(&Local).naive_local()
)
}).unwrap_or("".into())
}).unwrap_or_else(|| "".into())
);
let duration = entry.end.unwrap_or(now) - entry.start;
daily = daily + duration;
let duration = format_duration(duration);
let note = entry.note.unwrap_or("".into());
let note = entry.note.unwrap_or_else(|| "".into());
let id = if ids { entry.id.to_string() } else { "".into() };

View File

@ -41,7 +41,7 @@ fn local_to_utc_vec(entries: Vec<Entry>) -> Result<Vec<Entry>> {
.map(|e| {
Ok(Entry {
start: local_to_utc(e.start)?,
end: e.end.map(|t| local_to_utc(t)).transpose()?,
end: e.end.map(local_to_utc).transpose()?,
..e
})
})
@ -71,15 +71,13 @@ pub fn time_or_warning<D: Database>(time: DateTime<Utc>, db: &D) -> Result<(Date
/// emits the appropiate warning if the old database format was detected.
pub fn warn_if_needed<E: Write>(err: &mut E, needs_warning: bool) -> Result<()> {
if needs_warning {
if std::env::var_os("TIEMPO_SUPRESS_TIMETRAP_WARNING").is_none() {
writeln!(
err,
"{} You are using the old timetrap format, it is advised that \
you update your database using t migrate",
Yellow.bold().paint("[WARNING]"),
).map_err(|e| IOError(e))?;
}
if needs_warning && std::env::var_os("TIEMPO_SUPRESS_TIMETRAP_WARNING").is_none() {
writeln!(
err,
"{} You are using the old timetrap format, it is advised that \
you update your database using t migrate",
Yellow.bold().paint("[WARNING]"),
).map_err(IOError)?;
}
Ok(())

View File

@ -63,6 +63,12 @@ impl Col {
}
}
impl Default for Col {
fn default() -> Col {
Col::new()
}
}
enum DataOrSep {
Data(Vec<String>),
Sep(char),
@ -87,7 +93,7 @@ impl Tabulate {
let mut lines: Vec<Vec<String>> = Vec::new();
for (col, ((w, d), c)) in self.widths.iter_mut().zip(data.iter()).zip(self.cols.iter()).enumerate() {
for (r1, dl) in d.split("\n").enumerate() {
for (r1, dl) in d.split('\n').enumerate() {
for (r2, l) in constrained_lines(dl, c.max_width.unwrap_or(usize::MAX)).into_iter().enumerate() {
let count = l.chars().count();

View File

@ -48,14 +48,14 @@ fn date_parts<T: Datelike>(t: T) -> (i32, u32, u32) {
pub fn parse_time(input: &str) -> Result<DateTime<Utc>> {
if let Some(caps) = HUMAN_REGEX.captures(input) {
let hours = if let Some(_) = caps.name("hour") {
let hours = if caps.name("hour").is_some() {
if let Some(m) = caps.name("hcase") {
NUMBER_VALUES[m.as_str()]
} else if let Some(m) = caps.name("hdigit") {
NUMBER_VALUES[m.as_str()]
} else if let Some(m) = caps.name("hten") {
NUMBER_VALUES[m.as_str()]
} else if let Some(_) = caps.name("hcomposed") {
} else if caps.name("hcomposed").is_some() {
NUMBER_VALUES[&caps["hcten"]] + NUMBER_VALUES[&caps["hcdigit"]]
} else if let Some(m) = caps.name("htextualnum") {
m.as_str().parse().unwrap()
@ -66,14 +66,14 @@ pub fn parse_time(input: &str) -> Result<DateTime<Utc>> {
0
};
let minutes = if let Some(_) = caps.name("minute") {
let minutes = if caps.name("minute").is_some() {
if let Some(m) = caps.name("mcase") {
NUMBER_VALUES[m.as_str()]
} else if let Some(m) = caps.name("mdigit") {
NUMBER_VALUES[m.as_str()]
} else if let Some(m) = caps.name("mten") {
NUMBER_VALUES[m.as_str()]
} else if let Some(_) = caps.name("mcomposed") {
} else if caps.name("mcomposed").is_some() {
NUMBER_VALUES[&caps["mcten"]] + NUMBER_VALUES[&caps["mcdigit"]]
} else if let Some(m) = caps.name("mtextualnum") {
m.as_str().parse().unwrap()
@ -98,8 +98,8 @@ pub fn parse_time(input: &str) -> Result<DateTime<Utc>> {
let minute: u32 = caps.name("minute").map(|t| t.as_str().parse().unwrap()).unwrap_or(0);
let second: u32 = caps.name("second").map(|t| t.as_str().parse().unwrap()).unwrap_or(0);
return if let Some(_) = caps.name("offset") {
if let Some(_) = caps.name("utc") {
return if caps.name("offset").is_some() {
if caps.name("utc").is_some() {
date_from_parts(
Utc, input, year, month, day, hour, minute, second,
)
@ -125,8 +125,8 @@ pub fn parse_time(input: &str) -> Result<DateTime<Utc>> {
let minute: u32 = caps.name("minute").map(|t| t.as_str().parse().unwrap()).unwrap_or(0);
let second: u32 = caps.name("second").map(|t| t.as_str().parse().unwrap()).unwrap_or(0);
return if let Some(_) = caps.name("offset") {
if let Some(_) = caps.name("utc") {
return if caps.name("offset").is_some() {
if caps.name("utc").is_some() {
let (year, month, day) = date_parts(Utc::now());
date_from_parts(