Skip to content

Commit

Permalink
Auto-fix Clippy pedantic warnings (#423)
Browse files Browse the repository at this point in the history
Via:

    cargo clippy --fix -- -Wclippy::pedantic

After:

    cargo clippy -- -Wclippy::pedantic 2>&1| grep "warning:" | wc -l
    285

Now:

    cargo clippy -- -Wclippy::pedantic 2>&1| grep "warning:" | wc -l
    112

Co-authored-by: Andrew Cantino <cantino@users.noreply.github.com>
  • Loading branch information
nicokosi and cantino authored Jul 4, 2024
1 parent 940e820 commit f06c5be
Show file tree
Hide file tree
Showing 22 changed files with 178 additions and 220 deletions.
10 changes: 6 additions & 4 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ pub struct Cli {
#[arg(short, long)]
pub debug: bool,

/// Session ID to record or search under (defaults to $MCFLY_SESSION_ID)
/// Session ID to record or search under (defaults to $`MCFLY_SESSION_ID`)
#[arg(long = "session_id")]
pub session_id: Option<String>,

/// Shell history file to read from when adding or searching (defaults to $MCFLY_HISTORY)
/// Shell history file to read from when adding or searching (defaults to $`MCFLY_HISTORY`)
#[arg(long = "mcfly_history")]
pub mcfly_history: Option<PathBuf>,

Expand All @@ -36,14 +36,14 @@ pub enum SubCommand {
/// Add commands to the history
#[command(alias = "a")]
Add {
/// The command that was run (default last line of $MCFLY_HISTORY file)
/// The command that was run (default last line of $`MCFLY_HISTORY` file)
command: Vec<String>,

/// Exit code of command
#[arg(value_name = "EXIT_CODE", short, long)]
exit: Option<i32>,

/// Also append command to the given file (e.q., .bash_history)
/// Also append command to the given file (e.q., .`bash_history`)
#[arg(value_name = "HISTFILE", short, long)]
append_to_histfile: Option<String>,

Expand Down Expand Up @@ -223,13 +223,15 @@ pub enum DumpFormat {
}

impl Cli {
#[must_use]
pub fn is_init(&self) -> bool {
matches!(self.command, SubCommand::Init { .. })
}
}

impl SortOrder {
#[inline]
#[must_use]
pub fn to_str(&self) -> &'static str {
match self {
Self::Asc => "ASC",
Expand Down
10 changes: 5 additions & 5 deletions src/command_input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub enum Move {
}

#[derive(Debug)]
/// CommandInput data structure
/// `CommandInput` data structure
pub struct CommandInput {
/// The command itself
pub command: String,
Expand Down Expand Up @@ -82,7 +82,7 @@ impl CommandInput {

pub fn delete(&mut self, cmd: Move) {
let mut new_command = String::with_capacity(self.command.len());
let command_copy = self.command.to_owned();
let command_copy = self.command.clone();
let vec = command_copy.grapheme_indices(true);

match cmd {
Expand Down Expand Up @@ -229,7 +229,7 @@ impl CommandInput {

let mut word_index: usize = 0;
let mut found_word: bool = false;
let command_copy = self.command.to_owned();
let command_copy = self.command.clone();
let vec = command_copy
.grapheme_indices(true)
.enumerate()
Expand Down Expand Up @@ -264,7 +264,7 @@ impl CommandInput {
/// Return the index of the grapheme cluster that represents the start of the next word after
/// the cursor.
fn next_word_boundary(&self) -> usize {
let command_copy = self.command.to_owned();
let command_copy = self.command.clone();

let grapheme_indices = command_copy.grapheme_indices(true);

Expand Down Expand Up @@ -309,7 +309,7 @@ mod tests {
#[test]
fn display_works() {
let input = CommandInput::from("foo bar baz");
assert_eq!(format!("{}", input), "foo bar baz");
assert_eq!(format!("{input}"), "foo bar baz");
}

#[test]
Expand Down
7 changes: 4 additions & 3 deletions src/fake_typer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@ extern "C" {
pub fn use_tiocsti(string: &str) {
for byte in string.as_bytes() {
let a: *const u8 = byte;
if unsafe { ioctl(0, libc::TIOCSTI.try_into().unwrap(), a) } < 0 {
panic!("Error encountered when calling ioctl");
}
assert!(
unsafe { ioctl(0, libc::TIOCSTI.try_into().unwrap(), a) } >= 0,
"Error encountered when calling ioctl"
);
}
}

Expand Down
1 change: 1 addition & 0 deletions src/fixed_length_grapheme_string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ impl Write for FixedLengthGraphemeString {
}

impl FixedLengthGraphemeString {
#[must_use]
pub fn empty(max_grapheme_length: u16) -> FixedLengthGraphemeString {
FixedLengthGraphemeString {
string: String::new(),
Expand Down
2 changes: 1 addition & 1 deletion src/history/db_extensions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,5 +37,5 @@ pub fn add_db_functions(db: &Connection) {
Ok(network.output(&features))
},
)
.unwrap_or_else(|err| panic!("McFly error: Successful create_scalar_function ({})", err));
.unwrap_or_else(|err| panic!("McFly error: Successful create_scalar_function ({err})"));
}
137 changes: 61 additions & 76 deletions src/history/history.rs

Large diffs are not rendered by default.

43 changes: 13 additions & 30 deletions src/history/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,45 +19,35 @@ pub fn migrate(connection: &Connection) {
[],
|row| row.get(0),
)
.unwrap_or_else(|err| panic!("McFly error: Query to work ({})", err))
.unwrap_or_else(|err| panic!("McFly error: Query to work ({err})"))
.unwrap_or(0);

if current_version > CURRENT_SCHEMA_VERSION {
panic!(
"McFly error: Database schema version ({}) is newer than the max version supported by this binary ({}). You should update mcfly.",
current_version,
CURRENT_SCHEMA_VERSION,
assert!(current_version <= CURRENT_SCHEMA_VERSION, "McFly error: Database schema version ({current_version}) is newer than the max version supported by this binary ({CURRENT_SCHEMA_VERSION}). You should update mcfly.",
);
}

if current_version < CURRENT_SCHEMA_VERSION {
print!(
"McFly: Upgrading McFly DB to version {}, please wait...",
CURRENT_SCHEMA_VERSION
);
print!("McFly: Upgrading McFly DB to version {CURRENT_SCHEMA_VERSION}, please wait...");
io::stdout()
.flush()
.unwrap_or_else(|err| panic!("McFly error: STDOUT flush should work ({})", err));
.unwrap_or_else(|err| panic!("McFly error: STDOUT flush should work ({err})"));
}

if current_version < 1 {
connection
.execute_batch(
"ALTER TABLE commands ADD COLUMN cmd_tpl TEXT; UPDATE commands SET cmd_tpl = '';",
)
.unwrap_or_else(|err| {
panic!("McFly error: Unable to add cmd_tpl to commands ({})", err)
});
.unwrap_or_else(|err| panic!("McFly error: Unable to add cmd_tpl to commands ({err})"));

let mut statement = connection
.prepare("UPDATE commands SET cmd_tpl = :cmd_tpl WHERE id = :id")
.unwrap_or_else(|err| panic!("McFly error: Unable to prepare update ({})", err));
.unwrap_or_else(|err| panic!("McFly error: Unable to prepare update ({err})"));

for (id, cmd) in cmd_strings(connection) {
let simplified_command = SimplifiedCommand::new(cmd.as_str(), true);
statement
.execute(named_params! { ":cmd_tpl": &simplified_command.result, ":id": &id })
.unwrap_or_else(|err| panic!("McFly error: Insert to work ({})", err));
.unwrap_or_else(|err| panic!("McFly error: Insert to work ({err})"));
}
}

Expand All @@ -69,10 +59,7 @@ pub fn migrate(connection: &Connection) {
CREATE INDEX command_session_id ON commands (session_id);",
)
.unwrap_or_else(|err| {
panic!(
"McFly error: Unable to add session_id to commands ({})",
err
)
panic!("McFly error: Unable to add session_id to commands ({err})")
});
}

Expand All @@ -90,7 +77,7 @@ pub fn migrate(connection: &Connection) {
ALTER TABLE commands ADD COLUMN selected INTEGER; \
UPDATE commands SET selected = 0;",
)
.unwrap_or_else(|err| panic!("McFly error: Unable to add selected_commands ({})", err));
.unwrap_or_else(|err| panic!("McFly error: Unable to add selected_commands ({err})"));
}

if current_version < CURRENT_SCHEMA_VERSION {
Expand All @@ -110,29 +97,25 @@ fn make_schema_versions_table(connection: &Connection) {
CREATE UNIQUE INDEX IF NOT EXISTS schema_versions_index ON schema_versions (version);",
)
.unwrap_or_else(|err| {
panic!(
"McFly error: Unable to create schema_versions db table ({})",
err
)
panic!("McFly error: Unable to create schema_versions db table ({err})")
});
}

fn write_current_schema_version(connection: &Connection) {
let insert = format!(
"INSERT INTO schema_versions (version, when_run) VALUES ({}, strftime('%s','now'))",
CURRENT_SCHEMA_VERSION
"INSERT INTO schema_versions (version, when_run) VALUES ({CURRENT_SCHEMA_VERSION}, strftime('%s','now'))"
);
connection
.execute_batch(&insert)
.unwrap_or_else(|err| panic!("McFly error: Unable to update schema_versions ({})", err));
.unwrap_or_else(|err| panic!("McFly error: Unable to update schema_versions ({err})"));
}

fn cmd_strings(connection: &Connection) -> Vec<(i64, String)> {
let query = "SELECT id, cmd FROM commands ORDER BY id DESC";
let mut statement = connection.prepare(query).unwrap();
let command_iter = statement
.query_map([], |row| Ok((row.get_unwrap(0), row.get_unwrap(1))))
.unwrap_or_else(|err| panic!("McFly error: Query Map to work ({})", err));
.unwrap_or_else(|err| panic!("McFly error: Query Map to work ({err})"));

let mut vec = Vec::new();
for command in command_iter.flatten() {
Expand Down
10 changes: 3 additions & 7 deletions src/history_cleaner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,11 @@ pub fn clean(settings: &Settings, history: &History, command: &str) {
.or_else(|_| env::var("MCFLY_HISTFILE"))
.unwrap_or_else(|err| {
panic!(
"McFly error: Please ensure that HISTFILE/MCFLY_HISTFILE is set ({})",
err
"McFly error: Please ensure that HISTFILE/MCFLY_HISTFILE is set ({err})"
)
}),
);
shell_history::delete_lines(&histfile, settings.history_format, command)
shell_history::delete_lines(&histfile, settings.history_format, command);
}
// Fish integration does not use a MCFLY_HISTORY file because we can get the last command
// during a fish_postexec function.
Expand All @@ -40,10 +39,7 @@ fn clean_temporary_files(mcfly_history: &Path, history_format: HistoryFormat, co
let path = mcfly_history;
if let Some(directory) = path.parent() {
let expanded_path = fs::canonicalize(directory).unwrap_or_else(|err| {
panic!(
"McFly error: The contents of $MCFLY_HISTORY appear invalid ({})",
err
)
panic!("McFly error: The contents of $MCFLY_HISTORY appear invalid ({err})")
});
let paths = fs::read_dir(expanded_path).unwrap();

Expand Down
8 changes: 4 additions & 4 deletions src/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,19 @@ impl Init {
}
pub fn init_bash() {
let script = include_str!("../mcfly.bash");
print!("{}", script);
print!("{script}");
}
pub fn init_zsh() {
let script = include_str!("../mcfly.zsh");
print!("{}", script);
print!("{script}");
}
pub fn init_fish() {
let script = include_str!("../mcfly.fish");
print!("{}", script);
print!("{script}");
}
pub fn init_pwsh() {
let script = include_str!("../mcfly.ps1")
.replace("::MCFLY::", env::current_exe().unwrap().to_str().unwrap());
print!("{}", script);
print!("{script}");
}
}
Loading

0 comments on commit f06c5be

Please sign in to comment.