Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Smart print #124

Merged
merged 7 commits into from
Feb 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## Unreleased
### Added
* `-s` for `--stdout` in `copy` and `search` commands (Issue [122](https://github.com/out-of-cheese-error/the-way/issues/122))
* Option to import a `the-way`-style gist with `the-way import -w <gist-url>` (Issue [98](https://github.com/out-of-cheese-error/the-way/issues/98))
* Field `copy_cmd` in configuration file which allows user to change the default copy command.
In case of empty field value (empty string) the default command is used.
Expand All @@ -15,6 +16,7 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
command is not supported by default.

### Changed
* Don't use ANSI color codes when terminal is not in tty mode (Issue [123](https://github.com/out-of-cheese-error/the-way/issues/123))
* Apply the Clippy's recommendations for the snippet.rs file.

## [0.15.0] - 2022-01-07
Expand Down
32 changes: 32 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ skim = "0.9.4"
# Terminal syntax highlighting
syntect = { version = "4.6.0", default-features = false, features = ["default-fancy"] }
hex = "0.4.3"
grep-cli = "0.1.6"
termcolor = "1.1.2"

# Sync to Gist/GitLab
ureq = { version = "2.4.0", features = ["json"] }
Expand Down
4 changes: 2 additions & 2 deletions src/the_way/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ pub enum TheWayCLI {
#[structopt(flatten)]
filters: Filters,
/// Print to stdout instead of copying (with Enter)
#[structopt(long)]
#[structopt(long, short)]
stdout: bool,
/// Use exact search instead of fuzzy
#[structopt(long, short)]
Expand Down Expand Up @@ -121,7 +121,7 @@ pub enum TheWayCLI {
/// Index of snippet to copy
index: usize,
/// Print to stdout instead of copying
#[structopt(long)]
#[structopt(long, short)]
stdout: bool,
},
/// View snippet
Expand Down
38 changes: 19 additions & 19 deletions src/the_way/gist.rs
Original file line number Diff line number Diff line change
Expand Up @@ -246,11 +246,14 @@ impl TheWay {
};
// Upload index file to Gist
let result = client.update_gist(&result.id, &update_payload)?;
spinner.finish_with_message(self.highlight_string(&format!(
"Created gist at {} with {} snippets",
result.html_url,
result.files.len()
)));
spinner.finish_with_message(utils::highlight_string(
&format!(
"Created gist at {} with {} snippets",
result.html_url,
result.files.len()
),
self.highlighter.main_style,
));

// Return created Gist ID
Ok(result.id)
Expand All @@ -261,7 +264,7 @@ impl TheWay {
// Retrieve local snippets
let mut snippets = self.list_snippets()?;
if snippets.is_empty() {
println!("{}", self.highlight_string("No snippets to sync."));
self.color_print("No snippets to sync.\n")?;
return Ok(());
}
// Make client
Expand All @@ -280,7 +283,10 @@ impl TheWay {
// Retrieve gist and gist snippets
let gist = client.get_gist(self.config.gist_id.as_ref().unwrap());
if gist.is_err() {
spinner.finish_with_message(self.highlight_string("Gist not found."));
spinner.finish_with_message(utils::highlight_string(
"Gist not found.",
self.highlighter.main_style,
));
self.config.gist_id =
Some(self.make_gist(self.config.github_access_token.as_ref().unwrap())?);
return Ok(());
Expand Down Expand Up @@ -356,19 +362,13 @@ impl TheWay {

// Print results
for (action, count) in action_counts {
println!(
"{}",
self.highlight_string(&if action == SyncAction::UpToDate {
format!("{} snippet(s) are up to date", count)
} else {
format!("{:?} {} snippet(s)", action, count)
})
);
self.color_print(&if action == SyncAction::UpToDate {
format!("{} snippet(s) are up to date\n", count)
} else {
format!("{:?} {} snippet(s)\n", action, count)
})?;
}
println!(
"{}",
self.highlight_string(&format!("\nGist: {}", gist.html_url))
);
self.color_print(&format!("\nGist: {}\n", gist.html_url))?;
Ok(())
}

Expand Down
103 changes: 36 additions & 67 deletions src/the_way/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,10 +107,7 @@ impl TheWay {
let snippet =
Snippet::from_user(self.get_current_snippet_index()? + 1, &self.languages, None)?;
let index = self.add_snippet(&snippet)?;
println!(
"{}",
self.highlight_string(&format!("Snippet #{} added", index))
);
self.color_print(&format!("Snippet #{} added\n", index))?;
self.increment_snippet_index()?;
Ok(())
}
Expand All @@ -120,10 +117,7 @@ impl TheWay {
let snippet =
Snippet::cmd_from_user(self.get_current_snippet_index()? + 1, code.as_deref())?;
let index = self.add_snippet(&snippet)?;
println!(
"{}",
self.highlight_string(&format!("Snippet #{} added", index))
);
self.color_print(&format!("Snippet #{} added\n", index))?;
self.increment_snippet_index()?;
Ok(())
}
Expand All @@ -132,15 +126,12 @@ impl TheWay {
fn delete(&mut self, index: usize, force: bool) -> color_eyre::Result<()> {
if force
|| Confirm::with_theme(&ColorfulTheme::default())
.with_prompt(&format!("Delete snippet #{}?", index))
.with_prompt(&format!("Delete snippet #{}?\n", index))
.default(false)
.interact()?
{
self.delete_snippet(index)?;
println!(
"{}",
self.highlight_string(&format!("Snippet #{} deleted", index))
);
self.color_print(&format!("Snippet #{} deleted\n", index))?;
Ok(())
} else {
let error: color_eyre::Result<()> = Err(LostTheWay::DoingNothing.into());
Expand All @@ -154,28 +145,22 @@ impl TheWay {
let new_snippet = Snippet::from_user(index, &self.languages, Some(&old_snippet))?;
self.delete_snippet(index)?;
self.add_snippet(&new_snippet)?;
println!(
"{}",
self.highlight_string(&format!("Snippet #{} changed", index))
);
self.color_print(&format!("Snippet #{} changed\n", index))?;
Ok(())
}

/// Pretty prints a snippet to terminal
fn view(&self, index: usize) -> color_eyre::Result<()> {
let snippet = self.get_snippet(index)?;
print!(
"{}",
utils::highlight_strings(
&snippet.pretty_print(
&self.highlighter,
self.languages
.get(&snippet.language)
.unwrap_or(&Language::default()),
),
false
)
);
utils::smart_print(
&snippet.pretty_print(
&self.highlighter,
self.languages
.get(&snippet.language)
.unwrap_or(&Language::default()),
),
false,
)?;
Ok(())
}

Expand All @@ -185,8 +170,7 @@ impl TheWay {
let code = snippet.fill_snippet(self.highlighter.selection_style)?;
if to_stdout {
// See https://github.com/rust-lang/rust/issues/46016
let mut stdout = std::io::stdout();
if let Err(e) = writeln!(stdout, "{}", code) {
if let Err(e) = writeln!(std::io::stdout(), "{}", code) {
if e.kind() != ErrorKind::BrokenPipe {
eprintln!("{}", e);
process::exit(1);
Expand All @@ -196,7 +180,10 @@ impl TheWay {
utils::copy_to_clipboard(&self.config.copy_cmd, &code)?;
eprintln!(
"{}",
self.highlight_string(&format!("Snippet #{} copied to clipboard", index))
utils::highlight_string(
&format!("Snippet #{} copied to clipboard\n", index),
self.highlighter.main_style
)
);
}
Ok(())
Expand Down Expand Up @@ -234,11 +221,7 @@ impl TheWay {
.into());
}
}

println!(
"{}",
self.highlight_string(&format!("Imported {} snippets", num))
);
self.color_print(&format!("Imported {} snippets\n", num))?;
Ok(())
}

Expand Down Expand Up @@ -272,7 +255,7 @@ impl TheWay {
}

/// Prints given snippets in full
fn show_snippets(&self, snippets: &[Snippet]) {
fn show_snippets(&self, snippets: &[Snippet]) -> color_eyre::Result<()> {
let mut colorized = Vec::new();
let default_language = Language::default();
for snippet in snippets {
Expand All @@ -285,14 +268,15 @@ impl TheWay {
),
);
}
print!("{}", utils::highlight_strings(&colorized, false));
utils::smart_print(&colorized, false)?;
Ok(())
}

/// Lists snippets (optionally filtered)
fn list(&self, filters: &Filters) -> color_eyre::Result<()> {
let mut snippets = self.filter_snippets(filters)?;
snippets.sort_by(|a, b| a.index.cmp(&b.index));
self.show_snippets(&snippets);
self.show_snippets(&snippets)?;
Ok(())
}

Expand Down Expand Up @@ -333,7 +317,7 @@ impl TheWay {
}
}
self.reset_index()?;
println!("{}", self.highlight_string("Data cleared."));
self.color_print("Data cleared.\n")?;
Ok(())
} else {
let error: color_eyre::Result<()> = Err(LostTheWay::DoingNothing.into());
Expand All @@ -349,11 +333,7 @@ impl TheWay {
.or_else(|| self.config.github_access_token.clone());
// Get token from user if not set
if self.config.github_access_token.is_none() {
println!(
"{}",
self.highlight_string("Get a GitHub access token from https://github.com/settings/tokens/new (add the \"gist\" scope)\n",
)
);
self.color_print("Get a GitHub access token from https://github.com/settings/tokens/new (add the \"gist\" scope)\n\n")?;
self.config.github_access_token = Some(
dialoguer::Password::with_theme(&ColorfulTheme::default())
.with_prompt("GitHub access token")
Expand Down Expand Up @@ -385,45 +365,34 @@ impl TheWay {
themes[theme_index].clone()
};
self.highlighter.set_theme(theme.clone())?;
println!(
"{}",
self.highlight_string(&format!("Theme changed to {}", theme))
);
self.color_print(&format!("Theme changed to {}\n", theme))?;
self.config.theme = theme;
self.config.store()?;
Ok(())
}
ThemeCommand::Add { file } => {
let theme = self.highlighter.add_theme(&file)?;
println!(
"{}",
self.highlight_string(&format!("Added theme {}", theme))
);
self.color_print(&format!("Added theme {}\n", theme))?;
Ok(())
}
ThemeCommand::Language { file } => {
let language = self.highlighter.add_syntax(&file)?;
println!(
"{}",
self.highlight_string(&format!("Added {} syntax", language))
);
self.color_print(&format!("Added {} syntax\n", language))?;
Ok(())
}
ThemeCommand::Get => {
println!(
"{}",
self.highlight_string(&format!(
"Current theme: {}",
self.highlighter.get_theme_name()
))
);
self.color_print(&format!(
"Current theme: {}\n",
self.highlighter.get_theme_name()
))?;
Ok(())
}
}
}

/// Adds some color to logging output, uses selected theme
pub(crate) fn highlight_string(&self, input: &str) -> String {
utils::highlight_string(input, self.highlighter.main_style)
pub(crate) fn color_print(&self, input: &str) -> color_eyre::Result<()> {
utils::smart_print(&[(self.highlighter.main_style, input.to_string())], false)?;
Ok(())
}
}