Skip to content

Commit

Permalink
moved resources around and changed default config files
Browse files Browse the repository at this point in the history
  • Loading branch information
shaneish committed Feb 11, 2023
1 parent fe7c999 commit d16a008
Show file tree
Hide file tree
Showing 4 changed files with 99 additions and 53 deletions.
54 changes: 54 additions & 0 deletions src/defaults/defaults.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
[settings]
# Use this to set the default editor for opening
# shortcuts to files.
default_editor="vi"

# Use this to set the maximum number of saved entries
# in the bunnyhop command history table.
#
# If set to 0, will continue to history indefinitely
# without removing.
max_history=300

# Use this choose how to display the results of the `ls`
# or `list` command.
#
# If set to 0, will print out the entire list of shortcuts
# at once.
#
# If set to some integer N > 0,
# it will display N shortcuts at once and wait for a keypress
# before displaying the next N shortcuts.
ls_display_block=0

[editors]
# Use this section to define alternate editors for individual
# file extensions. Set the extension on the right and the command
# to open the editor for that extension on the right.
#
# If a file is opened without a specified extension, the default
# editor will be used to open it.
#
# For example, use Jupyter Notebooks with IPython files, you can set:
#
# ipynb="jupyter-notebook"
#
# and anytime bunnyhop is used to open a shortcut to a .ipynb file,
# it will open it in Jupyter.
#
# As another example, if you want to open normal Python files in
# VSCode, you can set:
#
# py="code"
#
# If you want to open Scala files in Intellij, you can set:
#
# sc="idea"
# scala="idea"
# sbt="idea"
#
# Note that it had to be defined for all of the relevant
# Scala file extensions.
#
# I pretty much just use Neovim (the GOAT) for everything but
# notebooks. For notebooks I use: `ipynb="euporia-notebook"`
20 changes: 20 additions & 0 deletions src/defaults/help.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
"
{} {} {}
1) First argument is required.
2) Second argument is optional.

Valid first argument commands are:
1) {}: command to add a shortcut to the current directory.
If a second argument is given, that argument is the name that will
be used to refer to the shortcut for future use.
If no second argument is given, the high level name will be used.
2) {} or {}: command to list the current shortcuts and their names.
3) {} or {}: both commands to show current hop version info.
4) {}: command to create a temporary shortcut to the current directory
that can be jumped back to using the {} {} command.
5) {} or {}: command to remove the shortcut specified by {}.
6) {}: Any other first arguments given will be checked to see if it
represents a valid directory/file to hop to. This input can be a named
shortcut, a file/directory in the current directory, or a file/directory
from previous {} commands.
"
64 changes: 18 additions & 46 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use press_btn_continue;
use serde_derive::Deserialize;
use sqlite;
use std::{
include_str,
collections::HashMap,
env::current_exe,
env::{current_dir, var},
Expand Down Expand Up @@ -44,14 +45,14 @@ impl Env {
Ok(loc) => PathBuf::from(&loc),
Err(_) => {
home_dir.push(".config");
home_dir.push("hop");
home_dir.push("bunnyhop");
home_dir
}
};
let mut hop_config_file = PathBuf::from(&config_dir);
match var("HOP_CONFIG_FILE_NAME") {
Ok(name) => hop_config_file.push(name),
Err(_) => hop_config_file.push("hop.toml"),
Err(_) => hop_config_file.push("bunnyhop.toml"),
};
let mut database_dir = match var("HOP_DATABASE_DIRECTORY") {
Ok(loc) => PathBuf::from(&loc),
Expand All @@ -70,7 +71,7 @@ impl Env {
};
match var("HOP_DATABASE_FILE_NAME") {
Ok(name) => database_dir.push(name),
Err(_) => database_dir.push("hop.sqlite"),
Err(_) => database_dir.push("bunnyhop.db"),
};

Env {
Expand All @@ -79,8 +80,7 @@ impl Env {
}
}
}
// Suppressing assignment warnings as functionality that uses `config` will be added in the future.
#[allow(dead_code)]

pub struct Hopper {
pub config: Config,
pub env: Env,
Expand All @@ -99,8 +99,9 @@ impl Hopper {
.expect("[error] Unable to create config directory.");
let mut new_conf =
fs::File::create(&env.config_file).expect("[error] Unable to create config file.");
static DEFAULT_CONFIGS: &str = include_str!("defaults/defaults.toml");
new_conf
.write_all(b"[settings]\ndefault_editor=\"nvim\"\nmax_history=0\nls_display_block=0")
.write_all(DEFAULT_CONFIGS.as_bytes())
.expect("[error] Unable to generate default config file.");
};
let toml_str: String = fs::read_to_string(env.config_file.clone()).unwrap();
Expand Down Expand Up @@ -128,7 +129,7 @@ impl Hopper {
})
}

pub fn add_hop<T: AsRef<Path>>(&mut self, path: T, name: &str) -> anyhow::Result<()> {
fn add_hop<T: AsRef<Path>>(&mut self, path: T, name: &str) -> anyhow::Result<()> {
let query = format!(
"INSERT OR REPLACE INTO named_hops (name, location) VALUES (\"{}\", \"{}\")",
name,
Expand All @@ -139,7 +140,7 @@ impl Hopper {
Ok(())
}

pub fn remove_hop(&mut self, bunny: args::Rabbit) -> anyhow::Result<()> {
fn remove_hop(&mut self, bunny: args::Rabbit) -> anyhow::Result<()> {
let output_pair = match bunny {
args::Rabbit::RequestName(name) => {
Some((format!("name=\"{}\"", name), format!("shortcut: {}", name)))
Expand Down Expand Up @@ -182,7 +183,7 @@ impl Hopper {
}
}

pub fn use_hop(&mut self, shortcut_name: String) -> anyhow::Result<()> {
fn use_hop(&mut self, shortcut_name: String) -> anyhow::Result<()> {
let query = format!(
"SELECT location FROM named_hops WHERE name=\"{}\"",
&shortcut_name
Expand Down Expand Up @@ -221,7 +222,7 @@ impl Hopper {
}
}

pub fn just_do_it(&mut self, bunny: Rabbit) -> anyhow::Result<()> {
fn just_do_it(&mut self, bunny: Rabbit) -> anyhow::Result<()> {
match bunny {
Rabbit::File(hop_name, hop_path) => self.add_hop(hop_path, &hop_name),
Rabbit::Dir(hop_name, hop_path) => self.add_hop(hop_path, &hop_name),
Expand All @@ -230,7 +231,7 @@ impl Hopper {
}
}

pub fn log_history(&self, location: String, name: String) -> anyhow::Result<()> {
fn log_history(&self, location: String, name: String) -> anyhow::Result<()> {
if self.config.settings.max_history > 0 {
let query = format!(
"INSERT INTO history (time, name, location) VALUES ({}, \"{}\", \"{}\") ",
Expand All @@ -251,7 +252,7 @@ impl Hopper {
Ok(())
}

pub fn check_dir(&self, name: &str) -> Option<(PathBuf, String)> {
fn check_dir(&self, name: &str) -> Option<(PathBuf, String)> {
read_dir(current_dir().unwrap())
.expect("[error] Unable to search contents of current directory.")
.filter(|f| f.is_ok())
Expand All @@ -269,7 +270,7 @@ impl Hopper {
.find(|(_, path_end)| path_end == name)
}

pub fn list_hops(&self) -> anyhow::Result<()> {
fn list_hops(&self) -> anyhow::Result<()> {
let query = format!("SELECT name, location FROM named_hops");
let mut query_result = self.db.prepare(&query)?;
let mut hops: Vec<(String, String)> = Vec::new();
Expand Down Expand Up @@ -312,43 +313,14 @@ impl Hopper {
Ok(())
}

pub fn hop_names(&self) -> anyhow::Result<Vec<String>> {
let query = format!("SELECT name FROM named_hops");
let mut query_result = self.db.prepare(&query)?;
let mut hops: Vec<String> = Vec::new();
while let Ok(sqlite::State::Row) = query_result.next() {
let name = query_result.read::<String, _>("name")?;
hops.push(name);
}
Ok(hops)
}

pub fn brb<T: AsRef<Path>>(&mut self, path: T) -> anyhow::Result<()> {
fn brb<T: AsRef<Path>>(&mut self, path: T) -> anyhow::Result<()> {
self.add_hop(path.as_ref(), "back")?;
Ok(())
}

pub fn print_help() -> anyhow::Result<()> {
fn print_help() -> anyhow::Result<()> {
println!(
r#"
{} {} {}
1) First argument is required.
2) Second argument is optional.
Valid first argument commands are:
1) {}: command to add a shortcut to the current directory.
If a second argument is given, that argument is the name that will
be used to refer to the shortcut for future use.
If no second argument is given, the high level name will be used.
2) {} or {}: command to list the current shortcuts and their names.
3) {} or {}: both commands to show current hop version info.
4) {}: command to create a temporary shortcut to the current directory
that can be jumped back to using the {} {} command.
5) {} or {}: command to remove the shortcut specified by {}.
6) {}: Any other first arguments given will be checked to see if it
represents a valid directory/file to hop to. This input can be a named
shortcut, a file/directory in the current directory, or a file/directory
from previous {} commands."#,
include!("defaults/help.txt"),
"hp".bold(),
"arg1".italic().dimmed(),
"arg2".italic().dimmed(),
Expand All @@ -369,7 +341,7 @@ Valid first argument commands are:
Ok(())
}

pub fn runner(&self, cmd: String) -> anyhow::Result<()> {
fn runner(&self, cmd: String) -> anyhow::Result<()> {
let bunnyhop_exe = current_exe()
.expect("[error] Unable to extract current bunnyhop executable name.")
.into_os_string()
Expand Down
14 changes: 7 additions & 7 deletions tests/test_hopper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ fn test_initializing_resources() {
let config_dir = PathBuf::from(&temp_dir.path());
let _ = get_test_hopper(&config_dir);
let mut new_toml = config_dir.clone();
new_toml.push("hop.toml");
new_toml.push("bunnyhop.toml");
println!("{}", fs::read_to_string(&new_toml).unwrap());
assert!(new_toml.exists(), "TOML wasn't created.");
assert!(new_toml.is_file(), "TOML isn't a file.");
Expand All @@ -30,7 +30,7 @@ fn test_initializing_resources() {
assert!(new_db.exists(), "DB directory wasn't created.");
assert!(new_db.is_dir(), "DB directory isn't a directory.");

new_db.push("hop.sqlite");
new_db.push("bunnyhop.db");
assert!(new_db.exists(), "DB file wasn't created.");
assert!(new_db.is_file(), "DB file isn't a file.");
}
Expand All @@ -45,11 +45,11 @@ fn test_read_default_configs() {
println!("{:?}", hopper.config);
let default_config = bunnyhop::Config {
settings: Settings {
default_editor: "nvim".to_string(),
max_history: 0,
default_editor: "vi".to_string(),
max_history: 300,
ls_display_block: 0,
},
editors: None,
editors: Some(HashMap::new()),
};

assert_eq!(hopper.config, default_config);
Expand All @@ -62,9 +62,9 @@ fn test_read_configs_with_alt_editors() {
TempDir::new("tmp_test_alt_editors").expect("Unable to create temp directory for test.");
let config_dir = PathBuf::from(&temp_dir.path());
let mut alt_toml = config_dir.clone();
alt_toml.push("hop.toml");
alt_toml.push("bunnyhop.toml");
let mut alt_toml_file =
fs::File::create(&alt_toml).expect("Unable to create alternate hop.toml.");
fs::File::create(&alt_toml).expect("Unable to create alternate bunnyhop.toml.");
alt_toml_file.write_all(b"[settings]\ndefault_editor=\"vi\"\nmax_history=100\nls_display_block=10\n[editors]\npy=\"nano\"\nipynb=\"code\"\nrust=\"nvim\"").expect("Unable to generate alternate hop.toml.");
let hopper = get_test_hopper(&config_dir);
let expected_editors = HashMap::from_iter(
Expand Down

0 comments on commit d16a008

Please sign in to comment.