Skip to content

Commit

Permalink
feat: Color output
Browse files Browse the repository at this point in the history
  • Loading branch information
schpet committed Sep 22, 2024
1 parent fb45a8a commit 0e219e9
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 40 deletions.
45 changes: 36 additions & 9 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ pub fn print_env_file(file_path: &str, env_vars: &HashMap<String, String>) -> st
}

let mut buffer = Vec::new();
print_lines(&lines, &mut buffer);
print_lines(&lines, &mut buffer, false);

fs::write(file_path, buffer)
}
Expand Down Expand Up @@ -138,11 +138,11 @@ pub fn parse_env_content(content: &str) -> HashMap<String, String> {
}
}

pub fn print_env_vars<W: Write>(file_path: &str, writer: &mut W) {
pub fn print_env_vars<W: Write>(file_path: &str, writer: &mut W, use_color: bool) {
match fs::read_to_string(file_path) {
Ok(content) => match parser::parser().parse(content) {
Ok(lines) => {
print_lines(&lines, writer);
print_lines(&lines, writer, use_color);
}
Err(e) => {
eprintln!("Error parsing .env file: {:?}", e);
Expand All @@ -154,21 +154,41 @@ pub fn print_env_vars<W: Write>(file_path: &str, writer: &mut W) {
}
}

pub fn print_lines<W: Write>(lines: &[parser::Line], writer: &mut W) {
pub fn print_lines<W: Write>(lines: &[parser::Line], writer: &mut W, use_color: bool) {
for line in lines {
match line {
parser::Line::Comment(comment) => {
writeln!(writer, "#{}", comment).unwrap();
let comment_str = if use_color {
format!("#{}", comment).bright_black().to_string()
} else {
format!("#{}", comment)
};
writeln!(writer, "{}", comment_str).unwrap();
}
parser::Line::KeyValue {
key,
value,
comment,
} => {
let key_str = if use_color {
key.blue().to_string()
} else {
key.to_string()
};
let quoted_value = quote_value(value);
let mut line = format!("{}={}", key, quoted_value);
let value_str = if use_color {
quoted_value.green().to_string()
} else {
quoted_value
};
let mut line = format!("{}={}", key_str, value_str);
if let Some(comment) = comment {
line.push_str(&format!(" #{}", comment));
let comment_str = if use_color {
format!(" #{}", comment).bright_black().to_string()
} else {
format!(" #{}", comment)
};
line.push_str(&comment_str);
}
writeln!(writer, "{}", line).unwrap();
}
Expand Down Expand Up @@ -226,6 +246,8 @@ pub fn delete_keys(file_path: &str, keys: &[String]) -> std::io::Result<()> {
)
})?;

let original_env = parse_env_content(&content);

let updated_lines: Vec<parser::Line> = lines
.into_iter()
.filter(|line| {
Expand All @@ -238,9 +260,14 @@ pub fn delete_keys(file_path: &str, keys: &[String]) -> std::io::Result<()> {
.collect();

let mut buffer = Vec::new();
print_lines(&updated_lines, &mut buffer);
print_lines(&updated_lines, &mut buffer, false);

fs::write(file_path, buffer)
fs::write(file_path, &buffer)?;

let updated_env = parse_env_content(&String::from_utf8_lossy(&buffer));
print_diff(&original_env, &updated_env, &mut std::io::stdout());

Ok(())
}

fn needs_quoting(value: &str) -> bool {
Expand Down
26 changes: 4 additions & 22 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,36 +73,24 @@ fn main() {
}
},
Some(Commands::Print { parse_tree, json }) => {
let use_color = atty::is(Stream::Stdout);
if *parse_tree {
print_parse_tree(&cli.file, &mut std::io::stdout());
} else if *json {
print_env_vars_as_json(&cli.file, &mut std::io::stdout());
} else {
print_env_vars(&cli.file, &mut std::io::stdout());
print_env_vars(&cli.file, &mut std::io::stdout(), use_color);
}
return; // Exit after printing
}
Some(Commands::Keys) => {
print_env_keys_to_writer(&cli.file, &mut std::io::stdout());
}
Some(Commands::Delete { keys }) => {
let env_vars = match read_env_vars(&cli.file) {
Ok(result) => result,
Err(e) => {
eprintln!("Error reading .env file: {}", e);
process::exit(1);
}
};

let original_env = env_vars.clone();

if let Err(e) = envset::delete_keys(&cli.file, keys) {
eprintln!("Error deleting environment variables: {}", e);
process::exit(1);
}

let updated_env = read_env_vars(&cli.file).unwrap();
print_diff(&original_env, &updated_env, &mut std::io::stdout());
}
None => {}
}
Expand All @@ -111,7 +99,6 @@ fn main() {
if !atty::is(Stream::Stdin) {
parse_stdin()
} else {
println!("Debugging: cli.vars = {:?}", cli.vars);
parse_args(&cli.vars)
}
} else {
Expand Down Expand Up @@ -150,12 +137,7 @@ fn main() {
}

if should_print {
if atty::is(Stream::Stdout) {
print_env_vars(&cli.file, &mut std::io::stdout());
} else {
// If not outputting to a terminal, use a plain writer without colors
let mut writer = std::io::stdout();
envset::print_env_vars(&cli.file, &mut writer);
}
let use_color = atty::is(Stream::Stdout);
print_env_vars(&cli.file, &mut std::io::stdout(), use_color);
}
}
18 changes: 9 additions & 9 deletions src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ use tempfile::tempdir;

use crate::{Cli, Commands};
use envset::{
parse_args, parse_stdin_with_reader, print_diff, print_env_file, print_env_keys_to_writer,
print_env_vars, read_env_vars,
parse_stdin_with_reader, print_diff, print_env_file, print_env_keys_to_writer, print_env_vars,
read_env_vars,
};

#[test]
Expand Down Expand Up @@ -252,16 +252,16 @@ fn test_last_occurence_of_duplicate_keys_updated() {
fn test_delete_env_vars() {
let dir = tempdir().unwrap();
let file_path = dir.path().join(".env");
let initial_content = "FOO=bar\nBAZ=qux\nQUUX=quux\n";
let initial_content = "# Comment\nFOO=bar\nBAZ=qux\n# Another comment\nQUUX=quux\n";
fs::write(&file_path, initial_content).unwrap();

let keys_to_delete = vec!["FOO".to_string(), "QUUX".to_string()];
envset::delete_keys(file_path.to_str().unwrap(), &keys_to_delete).unwrap();

let final_content = fs::read_to_string(&file_path).unwrap();
assert_eq!(
final_content, "BAZ=qux\n",
"Final content should only contain BAZ=qux"
final_content, "# Comment\nBAZ=qux\n# Another comment\n",
"Final content should contain BAZ=qux and preserve comments"
);

let result = read_env_vars(file_path.to_str().unwrap()).unwrap();
Expand Down Expand Up @@ -328,7 +328,7 @@ fn test_print_all_env_vars() {
writeln!(file, "FOO=bar\nBAZ=qux\nABC=123").unwrap();

let mut output = Vec::new();
print_env_vars(file_path.to_str().unwrap(), &mut output);
print_env_vars(file_path.to_str().unwrap(), &mut output, false);

let output_str = String::from_utf8(output).unwrap();

Expand Down Expand Up @@ -371,7 +371,7 @@ fn test_no_print_when_args_provided() {
// This is where we would normally set the environment variables
// For this test, we're just ensuring it doesn't print
} else {
print_env_vars(file_path.to_str().unwrap(), &mut cursor);
print_env_vars(file_path.to_str().unwrap(), &mut cursor, false);
}
}

Expand Down Expand Up @@ -424,7 +424,7 @@ fn test_print_when_no_args() {
json: false,
})
| None => {
print_env_vars(file_path.to_str().unwrap(), &mut cursor);
print_env_vars(file_path.to_str().unwrap(), &mut cursor, false);
}
Some(Commands::Print {
parse_tree: true,
Expand Down Expand Up @@ -479,7 +479,7 @@ fn test_no_print_when_vars_set_via_stdin() {
print_env_file(file_path.to_str().unwrap(), &env_vars).unwrap();
print_diff(&original_env, &env_vars, &mut stdout);
} else if cli.command.is_none() {
print_env_vars(file_path.to_str().unwrap(), &mut stdout);
print_env_vars(file_path.to_str().unwrap(), &mut stdout, false);
}
}

Expand Down

0 comments on commit 0e219e9

Please sign in to comment.