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

Prevent Rewatch from running twice on the same project #73

Merged
merged 8 commits into from
Jan 2, 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
31 changes: 31 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ regex = "1.7.1"
futures = "0.3.25"
futures-timer = "3.0.2"
clap = { version = "4.3.17", features = ["derive"] }
sysinfo = "0.29.10"


[profile.release]
Expand Down
2 changes: 1 addition & 1 deletion src/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ pub fn build(filter: &Option<regex::Regex>, path: &str, no_timing: bool) -> Resu
if !packages::validate_packages_dependencies(&packages) {
return Err(());
}

let timing_source_files = Instant::now();

print!(
Expand Down
29 changes: 15 additions & 14 deletions src/build/packages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -746,23 +746,23 @@ pub fn validate_packages_dependencies(packages: &AHashMap<String, Package>) -> b
]
.iter()
.for_each(|(dependency_type, dependencies)| {
if let Some(unallowed_dependency_name) = get_unallowed_dependents(packages, package_name, dependencies) {
let empty_unallowed_deps = UnallowedDependency{
bs_deps: vec![],
pinned_deps: vec![],
bs_dev_deps: vec![],
if let Some(unallowed_dependency_name) =
get_unallowed_dependents(packages, package_name, dependencies)
{
let empty_unallowed_deps = UnallowedDependency {
bs_deps: vec![],
pinned_deps: vec![],
bs_dev_deps: vec![],
};

let unallowed_dependency = detected_unallowed_dependencies.entry(String::from(package_name));
let value = unallowed_dependency
.or_insert_with(||empty_unallowed_deps);
let value = unallowed_dependency.or_insert_with(|| empty_unallowed_deps);
match dependency_type {
&"bs-dependencies" => value.bs_deps.push(String::from(unallowed_dependency_name)),
&"pinned-dependencies" => value.pinned_deps.push(String::from(unallowed_dependency_name)),
&"bs-dev-dependencies" => value.bs_dev_deps.push(String::from(unallowed_dependency_name)),
_ => (),
}

}
});
}
Expand All @@ -772,7 +772,7 @@ pub fn validate_packages_dependencies(packages: &AHashMap<String, Package>) -> b
console::style("Error").red(),
console::style(package_name).bold()
);

vec![
("bs-dependencies", unallowed_deps.bs_deps.to_owned()),
("pinned-dependencies", unallowed_deps.pinned_deps.to_owned()),
Expand All @@ -792,9 +792,10 @@ pub fn validate_packages_dependencies(packages: &AHashMap<String, Package>) -> b
let has_any_unallowed_dependent = detected_unallowed_dependencies.len() > 0;

if has_any_unallowed_dependent {
println!("\nUpdate the {} value in the {} of the unallowed dependencies to solve the issue!",
console::style("unallowed_dependents").bold().dim(),
console::style("bsconfig.json").bold().dim()
println!(
"\nUpdate the {} value in the {} of the unallowed dependencies to solve the issue!",
console::style("unallowed_dependents").bold().dim(),
console::style("bsconfig.json").bold().dim()
)
}
return !has_any_unallowed_dependent;
Expand All @@ -805,7 +806,7 @@ mod test {
use crate::bsconfig::Source;
use ahash::{AHashMap, AHashSet};

use super::{Package, Namespace};
use super::{Namespace, Package};

fn create_package(
name: String,
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@ pub mod bsconfig;
pub mod build;
pub mod cmd;
pub mod helpers;
pub mod lock;
pub mod queue;
pub mod watcher;
74 changes: 74 additions & 0 deletions src/lock.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
use std::fs;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::process;
use sysinfo::{PidExt, System, SystemExt};

/* This locking mechanism is meant to never be deleted. Instead, it stores the PID of the process
* that's running, when trying to aquire a lock, it checks wether that process is still running. If
* not, it rewrites the lockfile to have its own PID instead. */

pub static LOCKFILE: &str = "rewatch.lock";

pub enum Error {
Locked(u32),
ParsingLockfile(std::num::ParseIntError),
ReadingLockfile(std::io::Error),
WritingLockfile(std::io::Error),
}

impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let msg = match self {
Error::Locked(pid) => format!("Rewatch is already running with PID {}", pid),
Error::ParsingLockfile(e) => format!("Could not parse lockfile: \n {}", e.to_string()),
Error::ReadingLockfile(e) => format!("Could not read lockfile: \n {}", e.to_string()),
Error::WritingLockfile(e) => format!("Could not write lockfile: \n {}", e.to_string()),
};
write!(f, "{}", msg)
}
}

pub enum Lock {
Aquired(u32),
Error(Error),
}

fn exists(to_check_pid: u32) -> bool {
System::new_all()
.processes()
.into_iter()
.any(|(pid, _process)| pid.as_u32() == to_check_pid)
}

fn create(lockfile_location: &Path, pid: u32) -> Lock {
// Create /lib if not exists
match lockfile_location
.parent()
.map(|folder| fs::create_dir_all(folder))
{
Some(Err(e)) => return Lock::Error(Error::WritingLockfile(e)),
_ => (),
};

File::create(lockfile_location)
.and_then(|mut file| file.write(pid.to_string().as_bytes()).map(|_| Lock::Aquired(pid)))
.unwrap_or_else(|e| Lock::Error(Error::WritingLockfile(e)))
}

pub fn get(folder: &str) -> Lock {
let location = format!("{}/lib/{}", folder, LOCKFILE);
let path = Path::new(&location);
let pid = process::id();

match fs::read_to_string(&location) {
Err(e) if (e.kind() == std::io::ErrorKind::NotFound) => create(&path, pid),
Err(e) => Lock::Error(Error::ReadingLockfile(e)),
Ok(s) => match s.parse::<u32>() {
Ok(parsed_pid) if !exists(parsed_pid) => create(&path, pid),
Ok(parsed_pid) => Lock::Error(Error::Locked(parsed_pid)),
Err(e) => Lock::Error(Error::ParsingLockfile(e)),
},
}
}
37 changes: 22 additions & 15 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ pub mod bsconfig;
pub mod build;
pub mod cmd;
pub mod helpers;
pub mod lock;
pub mod queue;
pub mod watcher;

Expand Down Expand Up @@ -56,21 +57,27 @@ fn main() {
.filter
.map(|filter| Regex::new(filter.as_ref()).expect("Could not parse regex"));

match command {
Command::Clean => build::clean::clean(&folder),
Command::Build => {
match build::build(&filter, &folder, args.no_timing.unwrap_or(false)) {
Err(()) => std::process::exit(1),
Ok(_) => {
args.after_build.map(|command| cmd::run(command));
std::process::exit(0)
}
};
}
Command::Watch => {
let _initial_build = build::build(&filter, &folder, false);
args.after_build.clone().map(|command| cmd::run(command));
watcher::start(&filter, &folder, args.after_build);
match lock::get(&folder) {
lock::Lock::Error(ref e) => {
eprintln!("Error while trying to get lock: {}", e.to_string());
std::process::exit(1)
}
lock::Lock::Aquired(_) => match command {
Command::Clean => build::clean::clean(&folder),
Command::Build => {
match build::build(&filter, &folder, args.no_timing.unwrap_or(false)) {
Err(()) => std::process::exit(1),
Ok(_) => {
args.after_build.map(|command| cmd::run(command));
std::process::exit(0)
}
};
}
Command::Watch => {
let _initial_build = build::build(&filter, &folder, false);
args.after_build.clone().map(|command| cmd::run(command));
watcher::start(&filter, &folder, args.after_build);
}
},
}
}
54 changes: 54 additions & 0 deletions tests/lock.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
source "./utils.sh"
cd ../testrepo

bold "Test: It should lock - when watching"

sleep 1

if rewatch clean &> /dev/null;
then
success "Repo Cleaned"
else
error "Error Cleaning Repo"
exit 1
fi

exit_watcher() {
# we need to kill the parent process (rewatch)
kill $(pgrep -P $!);
}

rewatch watch &>/dev/null &
success "Watcher Started"

sleep 1

if rewatch watch 2>&1 | grep 'Error while trying to get lock:' &> /dev/null;
then
success "Lock is correctly set"
exit_watcher
else
error "Not setting lock correctly"
exit_watcher
exit 1
fi

sleep 1

touch tmp.txt
rewatch watch &> tmp.txt &
success "Watcher Started"

sleep 1

if cat tmp.txt | grep 'Error while trying to get lock:' &> /dev/null;
then
error "Lock not removed correctly"
exit_watcher
exit 1
else
success "Lock removed correctly"
exit_watcher
fi

rm tmp.txt
3 changes: 1 addition & 2 deletions tests/suite-ci.sh
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,4 @@ else
exit 1
fi

./compile.sh && ./watch.sh

./compile.sh && ./watch.sh && ./lock.sh
Loading