worm_hole 3.0.2

CLI tool to easily jump between directories
// Copyright (C) 2025 Rignchen
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

pub mod alias;
pub mod cli;
pub mod commands;
pub mod db;
pub mod error;
pub mod path;

use cli::{Args, Command};
use db::Database;
use error::{get_exit_code, WHResult};

fn main() -> std::process::ExitCode {
	get_exit_code(run())
}

fn run() -> WHResult<()> {
	let args = Args::parse_args();
	let database = Database::new(args.db_path.as_str())?;

	match args.cmd {
		Command::AddAlias(add) => {
			add.run(&database)?;
		}
		Command::RemoveAlias(remove) => {
			remove.run(&database)?;
		}
		Command::ListAliases(list) => {
			list.run(&database)?;
		}
		Command::SearchAliases(search) => {
			search.run(&database)?;
		}
		Command::Query(query) => {
			query.run(&database)?;
		}
		Command::EditAlias(edit) => {
			edit.run(&database)?;
		}
		Command::RenameAlias(rename) => {
			rename.run(&database)?;
		}
		Command::Init(init) => {
			init.run(&database, args.db_path.as_str())?;
		}
	}

	Ok(())
}

#[cfg(test)]
mod tests {
	use std::process::Command;

	#[test]
	fn exit_code_db_issue() {
		let output = Command::new("cargo")
			.args(&["run", "--", "--db-path=/some/path/which/does/not/exist.db", "ls"])
			.output()
			.expect("failed to execute process");
		eprintln!("stderr: {}", String::from_utf8_lossy(&output.stderr).to_string());
		assert_eq!(output.status.code().unwrap(), 2);
	}

	#[test]
	fn exit_code_general_error() {
		let output = Command::new("cargo")
			.args(&["run", "--", "--db-path=.db_test.db", "query", "non_existent_alias"])
			.output()
			.expect("failed to execute process");
		eprintln!("stderr: {}", String::from_utf8_lossy(&output.stderr).to_string());
		assert_eq!(output.status.code().unwrap(), 1);
	}

	#[test]
	fn exit_code_success() {
		let output = Command::new("cargo")
			.args(&["run", "--", "--db-path=.db_test.db", "init", "nu"])
			.output()
			.expect("failed to execute process");
		eprintln!("stderr: {}", String::from_utf8_lossy(&output.stderr).to_string());
		assert_eq!(output.status.code().unwrap(), 0);
	}
}