Skip to content

Create the side-by-side option (-y) feature for the diff command (Incomplete) #117

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

use crate::params::{parse_params, Format};
use crate::utils::report_failure_to_read_input_file;
use crate::{context_diff, ed_diff, normal_diff, unified_diff};
use crate::{context_diff, ed_diff, normal_diff, unified_diff, side_diff};
use std::env::ArgsOs;
use std::ffi::OsString;
use std::fs;
Expand Down Expand Up @@ -79,6 +79,7 @@
eprintln!("{error}");
exit(2);
}),
Format::SideBySide => side_diff::diff(&from_content, &to_content)

Check warning on line 82 in src/diff.rs

View check run for this annotation

Codecov / codecov/patch

src/diff.rs#L82

Added line #L82 was not covered by tests
};
if params.brief && !result.is_empty() {
println!(
Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@ pub mod normal_diff;
pub mod params;
pub mod unified_diff;
pub mod utils;
pub mod side_diff;

// Re-export the public functions/types you need
pub use context_diff::diff as context_diff;
pub use ed_diff::diff as ed_diff;
pub use normal_diff::diff as normal_diff;
pub use unified_diff::diff as unified_diff;
pub use side_diff::diff as side_by_syde_diff;
1 change: 1 addition & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ mod macros;
mod normal_diff;
mod params;
mod unified_diff;
mod side_diff;
mod utils;

/// # Panics
Expand Down
8 changes: 8 additions & 0 deletions src/params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
Unified,
Context,
Ed,
SideBySide
}

#[derive(Clone, Debug, Eq, PartialEq)]
Expand Down Expand Up @@ -101,6 +102,13 @@
format = Some(Format::Ed);
continue;
}
if param == "-y" || param == "--side-by-side" {
if format.is_some() && format != Some(Format::SideBySide) {
return Err("Conflicting output style option".to_string());
}
format = Some(Format::SideBySide);
continue;

Check warning on line 110 in src/params.rs

View check run for this annotation

Codecov / codecov/patch

src/params.rs#L107-L110

Added lines #L107 - L110 were not covered by tests
}
if tabsize_re.is_match(param.to_string_lossy().as_ref()) {
// Because param matches the regular expression,
// it is safe to assume it is valid UTF-8.
Expand Down
81 changes: 81 additions & 0 deletions src/side_diff.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
use crate::utils::limited_string;
use diff::Result;
use std::{
io::{stdout, StdoutLock, Write},
vec,
};

fn push_output(
output: &mut StdoutLock,
left_ln: &[u8],
right_ln: &[u8],
symbol: &[u8],
tab_size: usize,
) -> std::io::Result<()> {
// The reason why this function exists, is that we cannot
// assume a enconding for our left or right line, and the
// writeln!() macro obligattes us to do it.

// side-by-side diff usually prints the output like:
// {left_line}{tab}{space_char}{symbol(|, < or >)}{space_char}{right_line}{EOL}

// recalculate how many spaces are nescessary, cause we need to take into
// consideration the lenght of the word before print it.
let tab_size = (tab_size as isize - left_ln.len() as isize).max(0);
let ident = vec![b' '; tab_size as usize];
output.write_all(left_ln)?; // {left_line}
output.write_all(&ident)?; // {tab}
output.write_all(b" ")?; // {space_char}
output.write_all(symbol)?; // {symbol}
output.write_all(b" ")?; // {space_char}
output.write_all(right_ln)?; // {right_line}

Check warning on line 31 in src/side_diff.rs

View check run for this annotation

Codecov / codecov/patch

src/side_diff.rs#L8-L31

Added lines #L8 - L31 were not covered by tests

writeln!(output)?; // {EOL}

Check warning on line 33 in src/side_diff.rs

View check run for this annotation

Codecov / codecov/patch

src/side_diff.rs#L33

Added line #L33 was not covered by tests

Ok(())
}

Check warning on line 36 in src/side_diff.rs

View check run for this annotation

Codecov / codecov/patch

src/side_diff.rs#L35-L36

Added lines #L35 - L36 were not covered by tests

pub fn diff(from_file: &[u8], to_file: &[u8]) -> Vec<u8> {
// ^ The left file ^ The right file

let mut output = stdout().lock();
let left_lines: Vec<&[u8]> = from_file.split(|&c| c == b'\n').collect();
let right_lines: Vec<&[u8]> = to_file.split(|&c| c == b'\n').collect();
let tab_size = 61; // for some reason the tab spaces are 61 not 60
for result in diff::slice(&left_lines, &right_lines) {
match result {
Result::Left(left_ln) => {
push_output(
&mut output,
limited_string(left_ln, tab_size),
&[],
b"<",
tab_size,
)
.unwrap();
}
Result::Right(right_ln) => {
push_output(
&mut output,
&[],
limited_string(right_ln, tab_size),
b">",
tab_size,
)
.unwrap();
}
Result::Both(left_ln, right_ln) => {
push_output(
&mut output,
limited_string(left_ln, tab_size),
limited_string(right_ln, tab_size),
b" ",
tab_size,
)
.unwrap();
}

Check warning on line 76 in src/side_diff.rs

View check run for this annotation

Codecov / codecov/patch

src/side_diff.rs#L38-L76

Added lines #L38 - L76 were not covered by tests
}
}

vec![]
}

Check warning on line 81 in src/side_diff.rs

View check run for this annotation

Codecov / codecov/patch

src/side_diff.rs#L80-L81

Added lines #L80 - L81 were not covered by tests
72 changes: 70 additions & 2 deletions src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@
// For the full copyright and license information, please view the LICENSE-*
// files that was distributed with this source code.

use std::{ffi::OsString, io::Write};

use regex::Regex;
use std::{ffi::OsString, io::Write};
use unicode_width::UnicodeWidthStr;

/// Replace tabs by spaces in the input line.
Expand Down Expand Up @@ -99,6 +98,15 @@ pub fn report_failure_to_read_input_file(
);
}

/// Limits a string at a certain limiter position. This can break the
/// encoding of a specific char where it has been cut.
#[must_use]
pub fn limited_string(orig: &[u8], limiter: usize) -> &[u8] {
// TODO: Verify if we broke the enconding of the char
// when we cut it.
&orig[..orig.len().min(limiter)]
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -205,4 +213,64 @@ mod tests {
assert!(m_time > current_time);
}
}

mod limited_string {
use super::*;
use std::str;

#[test]
fn empty_orig_returns_empty() {
let orig: &[u8] = b"";
let result = limited_string(&orig, 10);
assert!(result.is_empty());
}

#[test]
fn zero_limit_returns_empty() {
let orig: &[u8] = b"foo";
let result = limited_string(&orig, 0);
assert!(result.is_empty());
}

#[test]
fn limit_longer_than_orig_returns_full() {
let orig: &[u8] = b"foo";
let result = limited_string(&orig, 10);
assert_eq!(result, orig);
}

#[test]
fn ascii_limit_in_middle() {
let orig: &[u8] = b"foobar";
let result = limited_string(&orig, 3);
assert_eq!(result, b"foo");
assert!(str::from_utf8(&result).is_ok()); // All are ascii chars, we do not broke the enconding
}

#[test]
fn utf8_multibyte_cut_invalidates() {
let orig = "áéíóú".as_bytes();
let result = limited_string(&orig, 1);
// should contain only the first byte of mult-byte char
assert_eq!(result, vec![0xC3]);
assert!(str::from_utf8(&result).is_err());
}

#[test]
fn utf8_limit_at_codepoint_boundary() {
let orig = "áéí".as_bytes();
let bytes = &orig;
let result = limited_string(&orig, bytes.len());

assert_eq!(result, *bytes);
assert!(str::from_utf8(&result).is_ok());
}

#[test]
fn works_with_byte_vec_input() {
let orig_bytes = b"hello".to_vec();
let result = limited_string(&orig_bytes, 3);
assert_eq!(result, b"hel");
}
}
}
Loading