Skip to content

Commit

Permalink
added ability to open config on default editor or specified editor
Browse files Browse the repository at this point in the history
  • Loading branch information
codeitlikemiley committed Dec 9, 2024
1 parent 4d71797 commit bdf70b9
Show file tree
Hide file tree
Showing 13 changed files with 267 additions and 122 deletions.
270 changes: 177 additions & 93 deletions Cargo.lock

Large diffs are not rendered by default.

22 changes: 9 additions & 13 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "snip-cli"
version = "0.1.1"
version = "0.1.2"
edition = "2021"
authors = ["Uriah G. <[email protected]>"]
description = "A CLI tool (snip-cli) for managing Neovim and VSCode snippets"
Expand All @@ -14,24 +14,20 @@ categories = ["command-line-utilities"]
name = "snip"
path = "src/main.rs"

# Used when Bunding for OSX
[[bin]]
name = "snip-cli"
path = "src/main.rs"


# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
anyhow = "1.0.75"
clap = { version = "4.4.11", features = ["cargo", "derive", "string"] }
serde = { version = "1.0.193", features = ["derive"] }
serde_json = "1.0.108"
tokio = { version = "1.35.0", features = ["full"] }
tempfile = { version = "3.8.1", features = [] }
anyhow = "1.0.94"
clap = { version = "4.5.23", features = ["cargo", "derive", "string"] }
serde = { version = "1.0.215", features = ["derive"] }
serde_json = "1.0.133"
tokio = { version = "1.42.0", features = ["full"] }
tempfile = { version = "3.14.0", features = [] }
prettytable = "0.10.0"
dirs-next = "2.0.0"
dotenv = { version = "0.15.0", features = ["clap"] }
opener = "0.7.2"

[package.metadata.bundle]
name = "snip" # The name of your application
Expand All @@ -40,7 +36,7 @@ copyright = "Copyright (c) codeitlikemiley 2023. All rights reserved."
category = "Developer Tool"
short_description = "A CLI tool for managing Neovim and VSCode snippets"
long_description = "A CLI tool for managing Neovim and VSCode snippets"
version = "0.1.1" # Version of your application
version = "0.1.2" # Version of your application
osx_url_schemes = [
"com.codeitlikemiley.snip",
] # URL schemes your application supports
Expand Down
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -230,3 +230,13 @@ snip config --help
# Config Snippet
snip config <path>
```

10. Edit Config

```sh
snip open
# or we can pass in the editor command e.g. code
snip open --editor code
```

This will open the configuration file in the default editor, or the editor specified with the `--editor` flag.
2 changes: 1 addition & 1 deletion provision.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ cargo clean
rm snip.pkg
cargo zigbuild --release
cargo bundle --release
pkgbuild --root ./target/release/bundle/osx/snip.app --install-location "/Applications/snip.app" --identifier com.codeitlikemiley.snip --version 0.1.0 --scripts ./scripts snip.pkg
pkgbuild --root ./target/release/bundle/osx/snip.app --install-location "/Applications/snip.app" --identifier com.codeitlikemiley.snip --version 0.1.2 --scripts ./scripts snip.pkg
2 changes: 1 addition & 1 deletion scripts/postinstall
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,4 @@ if [ -L "$USER_HOME/.local/bin/snip" ]; then
fi

# Create the symlink in ~/.local/bin
ln -s "/Applications/snip.app/Contents/MacOS/snip-cli" "$USER_HOME/.local/bin/snip"
ln -s "/Applications/snip.app/Contents/MacOS/snip" "$USER_HOME/.local/bin/snip"
1 change: 1 addition & 0 deletions src/actions.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
pub mod create_directory_and_file;
pub mod edit_snippet_in_file;
pub mod list_snippets;
pub mod open_file_with;
pub mod remove_snippet_from_file;
pub mod search_snippets;
pub mod show_snippet;
Expand Down
1 change: 1 addition & 0 deletions src/actions/create_directory_and_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ pub fn create_directory_and_file(file_path: &str) -> anyhow::Result<()> {
OpenOptions::new()
.write(true)
.create(true) // This will create the file if it doesn't exist
.truncate(false)
.open(file_path)
.context("Failed to create or open the file")?;

Expand Down
49 changes: 49 additions & 0 deletions src/actions/open_file_with.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
use anyhow::{Context, Result};
use opener;
use std::{fs, process::Command};

/// Opens the file specified in the configuration JSON file using the system's default text editor.
///
/// # Arguments
///
/// * `config_path` - A string slice that holds the path to the JSON configuration file.
///
/// # Returns
///
/// * `Result<()>` - Returns `Ok` if the file is successfully opened, otherwise returns an error.
pub fn open_file_with(config_path: &str, editor: Option<String>) -> Result<()> {
// Read the configuration file
let config_content = fs::read_to_string(config_path)
.with_context(|| format!("Failed to read the configuration file at: {}", config_path))?;

// Parse the JSON to extract the `path` field
let config: serde_json::Value = serde_json::from_str(&config_content)
.with_context(|| "Failed to parse the configuration file as JSON")?;

// Extract the `path` field
let file_path = config["path"].as_str().ok_or_else(|| {
anyhow::anyhow!("`path` field is missing or invalid in configuration file")
})?;

// Open the file with the default editor
// If the editor is not provided, use the default editor
if editor.is_none() {
opener::open(file_path)
.with_context(|| format!("Failed to open the file at path: {}", file_path))
.map_err(|err| anyhow::anyhow!("Failed to open the file: {}", err))?;
} else {
// Use the provided editor
let editor = editor.unwrap();
// get the path to the editor
Command::new(editor.clone())
.arg(file_path)
.spawn()
.with_context(|| {
format!(
"Failed to open the file at path: {} with program: {}",
file_path, editor
)
})?;
}
Ok(())
}
3 changes: 1 addition & 2 deletions src/helpers/get_app_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ pub fn get_app_config() -> String {
#[cfg(test)]
mod tests {
use super::*;
use std::io::{stdout, Write};

#[test]
#[ignore]
Expand All @@ -34,7 +33,7 @@ mod tests {
// Act
let actual = get_app_config();
// For debugging purpose on CI
writeln!(stdout(), "DEBUGGER ENV CONFIG PATH: {}", actual).unwrap();
println!("DEBUGGER ENV CONFIG PATH: {}", actual);
// Assert
assert_eq!(actual, expected);
}
Expand Down
8 changes: 4 additions & 4 deletions src/helpers/is_fuzzy_match.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ mod tests {

#[test]
fn test_is_fuzzy_match() {
assert_ne!(is_fuzzy_match("moon", "bd"), true);
assert_ne!(is_fuzzy_match("moon", "mp"), true);
assert_eq!(is_fuzzy_match("moon", "mn"), true);
assert_eq!(is_fuzzy_match("moon", "oon"), true);
assert!(!is_fuzzy_match("moon", "bd"));
assert!(!is_fuzzy_match("moon", "mp"));
assert!(is_fuzzy_match("moon", "mn"));
assert!(is_fuzzy_match("moon", "oon"));
}
}
14 changes: 8 additions & 6 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use clap::Parser;
use snip_cli::actions::create_directory_and_file::create_directory_and_file;
use snip_cli::actions::edit_snippet_in_file::edit_snippet_in_file;
use snip_cli::actions::list_snippets::list_snippets;
use snip_cli::actions::open_file_with::open_file_with;
use snip_cli::actions::remove_snippet_from_file::remove_snippet_from_file;
use snip_cli::actions::search_snippets::search_snippets;
use snip_cli::actions::show_snippet::show_snippet;
Expand All @@ -14,16 +15,13 @@ use snip_cli::helpers::get_app_config::get_app_config;
use snip_cli::models::cli_model::Cli;
use snip_cli::models::commands_model::Commands;
use snip_cli::models::snip_config_model::SnipConfig;
use std::io::Write;

#[tokio::main]
async fn main() -> Result<()> {
let config_path = get_app_config();

// Ensure the config directory exists
create_directory_and_file(&config_path)?;

// Load or create the configuration
let config = match SnipConfig::load(&config_path) {
Ok(cfg) => cfg,
Err(_) => {
Expand Down Expand Up @@ -59,7 +57,7 @@ async fn main() -> Result<()> {
dbg!(list_option);
let output = list_snippets(&config.path, list_option)
.context("Failed to list snippets from file")?;
writeln!(std::io::stdout(), "{}", output).unwrap();
println!("{}", output);
}
Commands::Edit {
key,
Expand All @@ -75,15 +73,15 @@ async fn main() -> Result<()> {
dbg!(&key);
let output =
show_snippet(&config.path, key).context("Failed to show snippet from file")?;
writeln!(std::io::stdout(), "{}", output).unwrap();
println!("{}", output);
}
Commands::Search { id, name } => {
dbg!(id, &name);
let output = search_snippets(&config.path, id, name)
.context("Failed to search snippet from file")?;

for result in output {
writeln!(std::io::stdout(), "{}\n", result).unwrap();
println!("{}\n", result);
}
}
Commands::UpdateKey { old_key, new_key } => {
Expand All @@ -101,6 +99,10 @@ async fn main() -> Result<()> {
println!("Configuration updated.");
}
}
Commands::Open { editor } => {
open_file_with(&config_path, editor)
.context("Failed to open the configuration file")?;
}
}

Ok(())
Expand Down
4 changes: 4 additions & 0 deletions src/models/commands_model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,8 @@ pub enum Commands {
#[arg(short, long)]
new_key: String,
},
Open {
#[arg(short, long)]
editor: Option<String>,
},
}
3 changes: 1 addition & 2 deletions src/models/snip_config_model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use crate::helpers::expand_home_dir::expand_home_dir;
use anyhow::Context;
use serde::{Deserialize, Serialize};
use std::fs;
use std::io::{stdout, Write};

#[derive(Serialize, Deserialize, Debug)]
pub struct SnipConfig {
Expand All @@ -14,7 +13,7 @@ impl SnipConfig {
let config_content = fs::read_to_string(path).context("Failed to read config file")?;
let config: SnipConfig =
serde_json::from_str(&config_content).context("Failed to parse config file")?;
writeln!(stdout(), "{}", &config.path).unwrap();
println!("{}", &config.path);
Ok(config)
}

Expand Down

0 comments on commit bdf70b9

Please sign in to comment.