Skip to content

diff: implement -s #362

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
42 changes: 25 additions & 17 deletions text/diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,16 @@

mod diff_util;

use std::{fs, io, path::PathBuf};

use clap::Parser;
use diff_util::{
common::{FormatOptions, OutputFormat},
diff_exit_status::DiffExitStatus,
dir_diff::DirDiff,
file_diff::FileDiff,
functions::check_existance,
functions::check_existence,
};
use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory};
use std::{fs, io, path::PathBuf};

/// diff - compare two files
#[derive(Parser, Clone)]
Expand Down Expand Up @@ -54,6 +53,10 @@ struct Args {
#[arg(short, long)]
recurse: bool,

/// Print a message even when there are no differences between files
#[arg(short = 's', long = "report-identical-files")]
report_identical_files: bool,

/// Output 3 lines of unified context
#[arg(short)]
unified3: bool,
Expand Down Expand Up @@ -103,17 +106,16 @@ impl From<&Args> for OutputFormat {
}

fn check_difference(args: Args) -> io::Result<DiffExitStatus> {
let path1 = PathBuf::from(&args.file1);
let path2 = PathBuf::from(&args.file2);
let path1 = PathBuf::from(args.file1.as_str());
let path2 = PathBuf::from(args.file2.as_str());

let path1_exists = check_existance(&path1)?;
let path2_exists = check_existance(&path2)?;
let path1_path = path1.as_path();
let path2_path = path2.as_path();

if !path1_exists || !path2_exists {
return Ok(DiffExitStatus::Trouble);
}
let path1_exists = check_existence(path1_path);
let path2_exists = check_existence(path2_path);

if path1 == path2 {
if !path1_exists || !path2_exists {
return Ok(DiffExitStatus::Trouble);
}

Expand All @@ -124,18 +126,24 @@ fn check_difference(args: Args) -> io::Result<DiffExitStatus> {
output_format,
args.label,
args.label2,
args.report_identical_files,
);

let format_options = format_options.unwrap();

let path1_is_file = fs::metadata(&path1)?.is_file();
let path2_is_file = fs::metadata(&path2)?.is_file();
let path1_is_file = fs::metadata(path1_path)?.is_file();
let path2_is_file = fs::metadata(path2_path)?.is_file();

if path1_is_file && path2_is_file {
FileDiff::file_diff(path1, path2, &format_options, None)
FileDiff::file_diff(path1_path, path2_path, &format_options, None)
} else if !path1_is_file && !path2_is_file {
DirDiff::dir_diff(path1, path2, &format_options, args.recurse)
DirDiff::dir_diff(path1_path, path2_path, &format_options, args.recurse)
} else {
FileDiff::file_dir_diff(path1, path2, &format_options)
Ok(FileDiff::file_dir_diff(
path1_path,
path2_path,
&format_options,
)?)
}
}

Expand All @@ -151,7 +159,7 @@ fn main() -> DiffExitStatus {
match result {
Ok(diff_exit_status) => diff_exit_status,
Err(error) => {
eprintln!("diff: {}", error);
eprintln!("diff: {error}");

DiffExitStatus::Trouble
}
Expand Down
3 changes: 3 additions & 0 deletions text/diff_util/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ pub struct FormatOptions {
pub output_format: OutputFormat,
label1: Option<String>,
label2: Option<String>,
pub report_identical_files: bool,
}

impl FormatOptions {
Expand All @@ -11,6 +12,7 @@ impl FormatOptions {
output_format: OutputFormat,
label1: Option<String>,
label2: Option<String>,
report_identical_files: bool,
) -> Result<Self, &'static str> {
if label1.is_none() && label2.is_some() {
return Err("label1 can not be NONE when label2 is available");
Expand All @@ -21,6 +23,7 @@ impl FormatOptions {
output_format,
label1,
label2,
report_identical_files,
})
}

Expand Down
22 changes: 10 additions & 12 deletions text/diff_util/dir_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,19 @@ use std::{
ffi::OsString,
fs::{self, DirEntry},
io,
path::PathBuf,
path::{Display, Path},
};

use super::constants::*;

pub struct DirData {
path: PathBuf,
pub struct DirData<'a> {
path: &'a Path,
files: HashMap<OsString, DirEntry>,
}

impl DirData {
pub fn load(path: PathBuf) -> io::Result<Self> {
impl<'a> DirData<'a> {
pub fn load(path: &'a Path) -> io::Result<Self> {
let mut files: HashMap<OsString, DirEntry> = Default::default();

let entries = fs::read_dir(&path)?;
let entries = fs::read_dir(path)?;

for entry in entries {
let entry = entry?;
Expand All @@ -31,11 +29,11 @@ impl DirData {
&self.files
}

pub fn path(&self) -> &PathBuf {
&self.path
pub fn path(&'a self) -> &'a Path {
self.path
}

pub fn path_str(&self) -> &str {
self.path.to_str().unwrap_or(COULD_NOT_UNWRAP_FILENAME)
pub fn path_str(&self) -> Display {
self.path.display()
}
}
54 changes: 16 additions & 38 deletions text/diff_util/dir_diff.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{collections::HashSet, ffi::OsString, io, path::PathBuf};
use std::{collections::HashSet, ffi::OsString, io, path::Path};

use crate::diff_util::{
constants::COULD_NOT_UNWRAP_FILENAME, diff_exit_status::DiffExitStatus, file_diff::FileDiff,
Expand All @@ -7,16 +7,16 @@ use crate::diff_util::{
use super::{common::FormatOptions, dir_data::DirData};

pub struct DirDiff<'a> {
dir1: &'a mut DirData,
dir2: &'a mut DirData,
dir1: &'a mut DirData<'a>,
dir2: &'a mut DirData<'a>,
format_options: &'a FormatOptions,
recursive: bool,
}

impl<'a> DirDiff<'a> {
fn new(
dir1: &'a mut DirData,
dir2: &'a mut DirData,
dir1: &'a mut DirData<'a>,
dir2: &'a mut DirData<'a>,
format_options: &'a FormatOptions,
recursive: bool,
) -> Self {
Expand All @@ -29,8 +29,8 @@ impl<'a> DirDiff<'a> {
}

pub fn dir_diff(
path1: PathBuf,
path2: PathBuf,
path1: &Path,
path2: &Path,
format_options: &FormatOptions,
recursive: bool,
) -> io::Result<DiffExitStatus> {
Expand All @@ -48,15 +48,7 @@ impl<'a> DirDiff<'a> {
let is_file = dir_data
.files()
.get_key_value(file_name)
.unwrap_or_else(|| {
panic!(
"Could not find file in {}",
dir_data
.path()
.to_str()
.unwrap_or(COULD_NOT_UNWRAP_FILENAME)
)
})
.unwrap_or_else(|| panic!("Could not find file in {}", dir_data.path().display()))
.1
.file_type()?
.is_file();
Expand Down Expand Up @@ -141,8 +133,8 @@ impl<'a> DirDiff<'a> {
}

let inner_exit_status = FileDiff::file_diff(
path1,
path2,
path1.as_path(),
path2.as_path(),
self.format_options,
Some(show_if_different),
)?;
Expand All @@ -153,37 +145,23 @@ impl<'a> DirDiff<'a> {
} else if !in_dir1_is_file && !in_dir2_is_file {
if self.recursive {
Self::dir_diff(
self.dir1.path().join(file_name),
self.dir2.path().join(file_name),
self.dir1.path().join(file_name).as_path(),
self.dir2.path().join(file_name).as_path(),
self.format_options,
self.recursive,
)?;
} else {
println!(
"Common subdirectories: \"{}\" and \"{}\"",
self.dir1
.path()
.join(file_name)
.to_str()
.unwrap_or(COULD_NOT_UNWRAP_FILENAME),
self.dir2
.path()
.join(file_name)
.to_str()
.unwrap_or(COULD_NOT_UNWRAP_FILENAME)
self.dir1.path().join(file_name).display(),
self.dir2.path().join(file_name).display()
);
}
} else {
let (file, dir) = if in_dir1_is_file && !in_dir2_is_file {
(
path1.to_str().unwrap_or(COULD_NOT_UNWRAP_FILENAME),
path2.to_str().unwrap_or(COULD_NOT_UNWRAP_FILENAME),
)
(path1.display(), path2.display())
} else {
(
path2.to_str().unwrap_or(COULD_NOT_UNWRAP_FILENAME),
path1.to_str().unwrap_or(COULD_NOT_UNWRAP_FILENAME),
)
(path2.display(), path1.display())
};

println!(
Expand Down
19 changes: 13 additions & 6 deletions text/diff_util/file_data.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
use std::{fs::File, io, mem::take, path::PathBuf, str::from_utf8, time::SystemTime};
use std::{
fs::File,
io,
mem::take,
path::{Display, Path},
str::from_utf8,
time::SystemTime,
};

use super::constants::COULD_NOT_UNWRAP_FILENAME;

#[derive(Debug)]
pub struct FileData<'a> {
path: PathBuf,
path: &'a Path,
lines: Vec<&'a str>,
modified: SystemTime,
ends_with_newline: bool,
Expand All @@ -16,11 +23,11 @@ impl<'a> FileData<'a> {
}

pub fn get_file(
path: PathBuf,
path: &'a Path,
lines: Vec<&'a str>,
ends_with_newline: bool,
) -> io::Result<Self> {
let file = File::open(&path)?;
let file = File::open(path)?;
let modified = file.metadata()?.modified()?;

Ok(Self {
Expand Down Expand Up @@ -53,8 +60,8 @@ impl<'a> FileData<'a> {
COULD_NOT_UNWRAP_FILENAME
}

pub fn path(&self) -> &str {
self.path.to_str().unwrap_or(COULD_NOT_UNWRAP_FILENAME)
pub fn path(&self) -> Display {
self.path.display()
}
}

Expand Down
Loading