Skip to content

Commit

Permalink
Merge pull request #7 from frederikstroem/release-v0.2.0
Browse files Browse the repository at this point in the history
v0.2.0
  • Loading branch information
frederikstroem committed Jan 1, 2024
2 parents f02b632 + b60f9a7 commit e374a59
Show file tree
Hide file tree
Showing 6 changed files with 106 additions and 24 deletions.
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
```
- Add video/gif demo to README.md
## [v0.2.0] - 2024-01-01
### Added
- New CLI option `--ancestry <ANCESTRY>` to display the file's ancestry in the output path by including the specified number of parent directories relative to the current working directory, or 0 to omit the ancestry.
### Changed
- Updated the help message and usage instructions in the `README.md` to reflect the new `--ancestry` option.
### Removed
- Simplified the verification logic in `Config::new` by removing the redundant `verify_cli` function since clap already handles the conflict between `--stdout` and `--copy`.
### Fixed
- Conflict checks between `--stdout` and `--copy` flags in the CLI arguments.
## [v0.1.7] - 2023-12-28
### Fixed
Expand Down
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "psource"
version = "0.1.7"
version = "0.2.0"
authors = ["Frederik Holm Strøm <crates.io@frederikstroem.com>"]
description = "CLI tool to pretty print source code to stdout or directly to the clipboard."
edition = "2021"
Expand Down
21 changes: 11 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,16 +66,17 @@ Get help:
psource --help
CLI tool to pretty print source code to stdout or directly to the clipboard. Skips binary files.
Usage: psource [OPTIONS] [INPUT]...
Usage: psource [OPTIONS] <INPUT>...
Arguments:
[INPUT]... Input files and directories
<INPUT>... Input files and directories
Options:
-s, --stdout Print the source code to stdout
-c, --copy Copy the source code to the clipboard
-h, --help Print help
-V, --version Print version
-s, --stdout Print the source code to stdout
-c, --copy Copy the source code to the clipboard
-a, --ancestry <ANCESTRY> Display the file's ancestry in the output path by including the specified number of parent directories relative to the current working directory, or 0 to omit the ancestry [default: 1]
-h, --help Print help
-V, --version Print version
```

### Example: Add a to_uppercase utils function to a Rust project
Expand Down Expand Up @@ -107,15 +108,15 @@ psource -c src

This command will place the following content onto your clipboard:
```plaintext
⚫ simple_rust_program/src/main.rs
/simple_rust_program/src/main.rs
mod lib;
fn main() {
let message = lib::greet("Rustacean");
println!("{}", message);
}
⚫ simple_rust_program/src/lib.rs
/simple_rust_program/src/lib.rs
pub fn greet(name: &str) -> String {
format!("Hello, {}!", name)
}
Expand All @@ -128,15 +129,15 @@ Please add a to_uppercase function to a new utils.rs file. Modify the greet func
Source code:
⚫ simple_rust_program/src/main.rs
/simple_rust_program/src/main.rs
mod lib;
fn main() {
let message = lib::greet("Rustacean");
println!("{}", message);
}
⚫ simple_rust_program/src/lib.rs
/simple_rust_program/src/lib.rs
pub fn greet(name: &str) -> String {
format!("Hello, {}!", name)
}
Expand Down
8 changes: 6 additions & 2 deletions src/cli/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,17 @@ use clap::Parser;
#[command(about = "CLI tool to pretty print source code to stdout or directly to the clipboard. Skips binary files.", long_about = None)]
pub struct Cli {
/// Print the source code to stdout
#[arg(short, long)]
#[arg(short, long, conflicts_with = "copy")]
pub stdout: bool,

/// Copy the source code to the clipboard
#[arg(short, long)]
#[arg(short, long, conflicts_with = "stdout")]
pub copy: bool,

/// Display the file's ancestry in the output path by including the specified number of parent directories relative to the current working directory, or 0 to omit the ancestry
#[arg(short, long, default_value = "1")]
pub ancestry: usize,

// /// Exclude files matching the given regex
// #[arg(short, long)]
// pub exclude: Option<String>,
Expand Down
10 changes: 0 additions & 10 deletions src/config/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@ pub struct Config {

impl Config {
pub fn new(cli: &Cli) -> anyhow::Result<Self> {
Self::verify_cli(&cli)?;

let config_file = Self::get_config_file()?;

let output_target = if cli.stdout {
Expand All @@ -32,14 +30,6 @@ impl Config {
)
}

fn verify_cli(cli: &Cli) -> anyhow::Result<()> {
if cli.stdout && cli.copy {
return Err(anyhow::anyhow!("Cannot use both --stdout and --copy at the same time."));
}

Ok(())
}

fn get_config_file() -> anyhow::Result<config::Config> {
let config_dir = match dirs::config_dir() {
Some(config_dir) => config_dir,
Expand Down
75 changes: 74 additions & 1 deletion src/printer/printer.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
use std::env;
use std::fs;
use std::path::{PathBuf, Path};
use std::ffi::OsStr;
use std::time::Duration;
use arboard::Clipboard;

Expand All @@ -22,13 +25,83 @@ impl<'a> Printer<'a> {
)
}

fn get_ancestry_path(&self, path: &Path, ancestry: usize) -> String {
// Get current working directory. This is the directory from which the program was executed.
let cwd: PathBuf = env::current_dir().expect("Failed to get current working directory");

// Collect ancestors into a vector.
let mut ancestors_full_path = cwd.ancestors().collect::<Vec<&Path>>();
// // Print
// for (i, ancestor) in ancestors_full_path.iter().enumerate() {
// println!("{}: {}", i, ancestor.to_string_lossy());
// }
// // 0: /home/tux/projects/psource
// // 1: /home/tux/projects
// // 2: /home/tux
// // 3: /home
// // 4: /

// Remove last element (root).
ancestors_full_path.pop();
// // Print
// for (i, ancestor) in ancestors_full_path.iter().enumerate() {
// println!("{}: {}", i, ancestor.to_string_lossy());
// }
// // 0: /home/tux/projects/psource
// // 1: /home/tux/projects
// // 2: /home/tux
// // 3: /home

// Trim ancestors down to directory names only.
let ancestors = ancestors_full_path
.iter()
.map(|ancestor| ancestor.file_name().unwrap())
.collect::<Vec<&OsStr>>();
// // Print
// for (i, ancestor) in ancestors.iter().enumerate() {
// println!("{}: {}", i, ancestor.to_string_lossy());
// }
// // 0: psource
// // 1: projects
// // 2: tux
// // 3: home

// Create an iterator over the ancestors.
let mut ancestors = ancestors.into_iter();

// Create a string to hold the ancestry path.
let mut ancestry_path = String::new();

// Prepend <ANCESTRY> ancestors to the path, if they exist.
for _ in 0..ancestry {
match ancestors.next() {
Some(ancestor) => {
ancestry_path.insert_str(0, &format!("{}/", ancestor.to_string_lossy()));
},
None => {
break;
},
}
}

// Prepend a trailing slash to the path.
ancestry_path.insert_str(0, "/");

// Append the path to the file
ancestry_path.push_str(&format!("{}", path.to_string_lossy()));

// Return the ancestry path
ancestry_path
}

fn get_output(&self) -> anyhow::Result<String> {
let paths = self.file_walker.walk(&self.cli.input)?;

let mut output = String::new();
for path in paths {
let content = fs::read_to_string(&path)?;
output.push_str(&format!("⚫ {}\n{}\n", path.display(), content));
let ancestry_path = self.get_ancestry_path(&path, self.cli.ancestry);
output.push_str(&format!("⚫ {}\n{}\n", ancestry_path, content));
}

Ok(output)
Expand Down

0 comments on commit e374a59

Please sign in to comment.