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

FEAT: Add rule: dirty untar #172

Merged
merged 9 commits into from
May 24, 2024
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
591 changes: 569 additions & 22 deletions Cargo.lock

Large diffs are not rendered by default.

8 changes: 7 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ console = "0.15.7"
dirs = "5.0.1"
regex = "1.10.2"
is_executable = "1.0.1"
zip = { version = "1.1.3", optional = true }
tar = { version = "0.4.40", optional = true }

[features]
zip = ["dep:zip"]
tar = ["dep:tar"]

[profile.release]
lto = true # Enable link-time optimization
Expand All @@ -28,7 +34,7 @@ codegen-units = 1 # Reduce number of codegen units to increase optimizations

[dev-dependencies]
mockall = "0.12.0"
tempfile = "3.8.1"
tempfile = "3.10.1"
rstest = "0.18.2"

[target.aarch64-apple-darwin]
Expand Down
6 changes: 3 additions & 3 deletions src/cli/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@ use crate::shell::Shell;
#[derive(Debug)]
pub struct CorrectedCommand {
pub script: String,
pub side_effect: Option<fn(CrabCommand, &String)>,
pub side_effect: Option<fn(CrabCommand, Option<&str>)>,
pub priority: u16,
}

impl CorrectedCommand {
pub fn new(
script: String,
side_effect: Option<fn(CrabCommand, &String)>,
side_effect: Option<fn(CrabCommand, Option<&str>)>,
priority: u16,
) -> Self {
Self {
Expand All @@ -28,7 +28,7 @@ impl CorrectedCommand {
}
pub fn run(&self, old_command: CrabCommand) {
if let Some(side_effect) = self.side_effect {
(side_effect)(old_command, &self.script);
(side_effect)(old_command, Some(&self.script));
}
println!("{}", self.get_script());
}
Expand Down
2 changes: 1 addition & 1 deletion src/rules/brew_link.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ pub fn match_rule(command: &mut CrabCommand, system_shell: Option<&dyn Shell>) -

pub fn get_new_command(command: &mut CrabCommand, system_shell: Option<&dyn Shell>) -> Vec<String> {
let mut command_parts = command.script_parts.clone();
command_parts[1] = "link".to_owned();
"link".clone_into(&mut command_parts[1]);
command_parts.insert(2, "--overwrite".to_owned());
command_parts.insert(3, "--dry-run".to_owned());
vec![command_parts.join(" ")]
Expand Down
2 changes: 1 addition & 1 deletion src/rules/brew_uninstall.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ pub fn match_rule(command: &mut CrabCommand, system_shell: Option<&dyn Shell>) -

pub fn get_new_command(command: &mut CrabCommand, system_shell: Option<&dyn Shell>) -> Vec<String> {
let mut command_parts = command.script_parts.clone();
command_parts[1] = "uninstall".to_owned();
"uninstall".clone_into(&mut command_parts[1]);
command_parts.insert(2, "--force".to_owned());
vec![command_parts.join(" ")]
}
Expand Down
266 changes: 266 additions & 0 deletions src/rules/dirty_untar.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,266 @@
use super::{utils::match_rule_with_is_app, Rule};
use crate::{cli::command::CrabCommand, shell::Shell};
use shlex::Quoter;
use std::fs;
use tar::Archive;

const TAR_EXTENSIONS: [&str; 15] = [
".tar",
".tar.Z",
".tar.bz2",
".tar.gz",
".tar.lz",
".tar.lzma",
".tar.xz",
".taz",
".tb2",
".tbz",
".tbz2",
".tgz",
".tlz",
".txz",
".tz",
];

fn is_tar_extract(cmd: &str) -> bool {
if cmd.contains("--extract") {
return true;
}
let cmd_split: Vec<&str> = cmd.split_whitespace().collect();
cmd_split.len() > 1 && cmd_split[1].contains('x')
}

fn tar_file(cmd: &[String]) -> Option<(String, String)> {
for c in cmd {
for ext in &TAR_EXTENSIONS {
if c.ends_with(ext) {
return Some((c.clone(), c[..c.len() - ext.len()].to_string()));
}
}
}
None
}

fn auxiliary_match_rule(command: &CrabCommand) -> bool {
!command.script.contains("-C")
&& is_tar_extract(&command.script)
&& tar_file(&command.script_parts).is_some()
}

pub fn match_rule(command: &mut CrabCommand, system_shell: Option<&dyn Shell>) -> bool {
match_rule_with_is_app(auxiliary_match_rule, command, vec!["tar"], None)
}

pub fn get_new_command(command: &mut CrabCommand, system_shell: Option<&dyn Shell>) -> Vec<String> {
let shlex_quoter = Quoter::new();
return match tar_file(&command.script_parts) {
Some((_, filepath_no_ext)) => {
let dir = shlex_quoter.quote(&filepath_no_ext).unwrap();
vec![system_shell.unwrap().and(vec![
&format!("mkdir -p {}", dir),
&format!("{cmd} -C {dir}", dir = dir, cmd = command.script),
])]
}
nonw => return vec![],
};
}

pub fn side_effect(old_cmd: CrabCommand, command: Option<&str>) {
if let Some((filepath, _)) = tar_file(&old_cmd.script_parts) {
let mut archive = Archive::new(std::fs::File::open(filepath).unwrap());

for file in archive.entries().unwrap() {
let file = file.unwrap();
let path = file.path().unwrap().to_path_buf();

if !path
.canonicalize()
.unwrap()
.starts_with(std::env::current_dir().unwrap())
{
// it's unsafe to overwrite files outside of the current directory
continue;
}

if path.is_file() {
fs::remove_file(path).unwrap_or(());
}
}
}
}

pub fn get_rule() -> Rule {
Rule::new(
"tar".to_owned(),
None,
None,
None,
match_rule,
get_new_command,
Some(side_effect),
)
}

#[cfg(test)]
mod tests {
use super::{get_new_command, match_rule, side_effect, TAR_EXTENSIONS};
use crate::cli::command::CrabCommand;
use crate::shell::Bash;
use std::env;
use std::fs;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use tar::Archive;
use tar::Builder;
use tempfile::TempDir;

pub fn tar_error(filename: &str, tmp_dir: &TempDir) {
let filename = format!("./{}", filename);
let path = tmp_dir.path().join(&filename);

let _ = env::set_current_dir(tmp_dir.path());
reset(&path);

let entries = fs::read_dir(".").unwrap();
let mut files = entries
.map(|res| res.map(|e| e.path()))
.collect::<Result<Vec<_>, std::io::Error>>()
.unwrap();
let mut expected_files = vec![
Path::new(&filename),
Path::new("./a"),
Path::new("./b"),
Path::new("./c"),
Path::new("./d"),
];
expected_files.sort();
files.sort();
assert_eq!(files, expected_files);

let entries = fs::read_dir("./d").unwrap();
let mut files = entries
.map(|res| res.map(|e| e.path()))
.collect::<Result<Vec<_>, std::io::Error>>()
.unwrap();
files.sort();
assert_eq!(files, vec![Path::new("./d/e")]);
}

fn reset(path: &Path) {
fs::create_dir("d").unwrap();
let files = vec!["a", "b", "c", "d/e"];

let tar_gz = File::create(path).unwrap();
let mut tar = Builder::new(tar_gz);

for file in files {
let file_path = PathBuf::from(file);

let mut f = File::create(&file_path).unwrap();
f.write_all(b"*").unwrap();
tar.append_path(&file_path).unwrap();
fs::remove_file(&file_path).unwrap();
}

let tar_gz = File::open(path).unwrap();
let mut tar = Archive::new(tar_gz);
tar.unpack(".").unwrap();
}

fn get_filename() -> Vec<(
Box<dyn Fn(&str) -> String>,
Box<dyn Fn(&str) -> String>,
Box<dyn Fn(&str) -> String>,
)> {
vec![
(
Box::new(|s: &str| format!("foo{}", s)),
Box::new(|s: &str| format!("foo{}", s)),
Box::new(|s: &str| format!("foo{}", s)),
),
(
Box::new(|s: &str| format!(r#""foo bar{}""#, s)),
Box::new(|s: &str| format!("foo bar{}", s)),
Box::new(|s: &str| format!("'foo bar{}'", s)),
),
]
}

fn get_script() -> Vec<(
Box<dyn Fn(&str) -> String>,
Box<dyn Fn(&str, &str) -> String>,
)> {
vec![
(
Box::new(|s: &str| format!("tar xvf {}", s)),
Box::new(|dir: &str, filename: &str| {
format!(
"mkdir -p {dir} && tar xvf {filename} -C {dir}",
dir = dir,
filename = filename
)
}),
),
(
Box::new(|s: &str| format!("tar -xvf {}", s)),
Box::new(|dir: &str, filename: &str| {
format!(
"mkdir -p {dir} && tar -xvf {filename} -C {dir}",
dir = dir,
filename = filename
)
}),
),
(
Box::new(|s: &str| format!("tar --extract -f {}", s)),
Box::new(|dir: &str, filename: &str| {
format!(
"mkdir -p {dir} && tar --extract -f {filename} -C {dir}",
dir = dir,
filename = filename
)
}),
),
]
}

#[test]
// The unit tests were split into test_match, test_side_effect and test_get_new_command.
// However, there was an issue with tempfile raising errors when the tests were running in
// parallel. Hence, we moved them to the same function.
fn test_dirty_unrar() {
for (filename, unquoted, quoted) in get_filename() {
for (script, fixed) in get_script() {
for ext in TAR_EXTENSIONS {
let tmp_dir = TempDir::new().unwrap();
tar_error(&unquoted(ext), &tmp_dir);
let mut command =
CrabCommand::new(script(&filename(ext)), Some("".to_owned()), None);
assert!(match_rule(&mut command, None));

side_effect(command, None);
let entries = fs::read_dir(".").unwrap();
let mut files = entries
.map(|res| res.map(|e| e.path()))
.collect::<Result<Vec<_>, std::io::Error>>()
.unwrap();
let unquoted = format!("./{}", unquoted(ext));
let mut expected_files = vec![Path::new(&unquoted), Path::new("./d")];
files.sort();
expected_files.sort();
assert_eq!(files, expected_files);

let system_shell = Bash {};
let mut command =
CrabCommand::new(script(&filename(ext)), Some("".to_owned()), None);
assert_eq!(
get_new_command(&mut command, Some(&system_shell)),
vec![fixed(&quoted(""), &filename(ext))]
);
}
}
}
}
}
2 changes: 0 additions & 2 deletions src/rules/ln_no_hard_link.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ pub fn get_rule() -> Rule {
mod tests {
use super::{get_new_command, match_rule};
use crate::cli::command::CrabCommand;
use crate::shell::Bash;

use rstest::rstest;

Expand Down Expand Up @@ -79,7 +78,6 @@ mod tests {
#[case] stdout: &str,
#[case] expected: Vec<&str>,
) {
let system_shell = Bash {};
let mut command = CrabCommand::new(command.to_owned(), Some(stdout.to_owned()), None);
assert_eq!(get_new_command(&mut command, None), expected);
}
Expand Down
8 changes: 6 additions & 2 deletions src/rules/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ mod conda_mistype;
mod cp_create_destination;
mod cp_omitting_directory;
mod cpp11;
#[cfg(feature = "tar")]
mod dirty_untar;
mod django_south_ghost;
mod django_south_merge;
mod docker_image_being_used_by_container;
Expand Down Expand Up @@ -156,6 +158,8 @@ pub fn get_rules() -> Vec<Rule> {
cp_create_destination::get_rule(),
cp_omitting_directory::get_rule(),
cpp11::get_rule(),
#[cfg(feature = "tar")]
dirty_untar::get_rule(),
django_south_ghost::get_rule(),
django_south_merge::get_rule(),
docker_image_being_used_by_container::get_rule(),
Expand Down Expand Up @@ -255,7 +259,7 @@ pub struct Rule {
requires_output: bool,
pub match_rule: fn(&mut CrabCommand, Option<&dyn Shell>) -> bool,
get_new_command: fn(&mut CrabCommand, Option<&dyn Shell>) -> Vec<String>,
side_effect: Option<fn(CrabCommand, &String)>,
side_effect: Option<fn(CrabCommand, Option<&str>)>,
}

impl fmt::Display for Rule {
Expand All @@ -272,7 +276,7 @@ impl Rule {
requires_output: Option<bool>,
match_rule: fn(&mut CrabCommand, Option<&dyn Shell>) -> bool,
get_new_command: fn(&mut CrabCommand, Option<&dyn Shell>) -> Vec<String>,
side_effect: Option<fn(CrabCommand, &String)>,
side_effect: Option<fn(CrabCommand, Option<&str>)>,
) -> Self {
Self {
name,
Expand Down
Loading
Loading