Skip to content

Commit

Permalink
🎨 - Move lockfile into /lib
Browse files Browse the repository at this point in the history
  • Loading branch information
rolandpeelen committed Jan 2, 2024
1 parent 29ba3aa commit 9e9bafd
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 10 deletions.
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
24 changes: 18 additions & 6 deletions src/lock.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::fs;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::process;
use sysinfo::{PidExt, System, SystemExt};

Expand Down Expand Up @@ -41,20 +42,31 @@ fn exists(to_check_pid: u32) -> bool {
.any(|(pid, _process)| pid.as_u32() == to_check_pid)
}

fn create(pid: u32) -> Lock {
File::create(LOCKFILE)
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() -> Lock {
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(LOCKFILE) {
Err(e) if (e.kind() == std::io::ErrorKind::NotFound) => create(pid),
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(pid),
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)),
},
Expand Down
4 changes: 1 addition & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,7 @@ fn main() {
.filter
.map(|filter| Regex::new(filter.as_ref()).expect("Could not parse regex"));

let lock = lock::get();

match (lock, command) {
match (lock::get(&folder), command) {
(lock::Lock::Error(ref e), _) => {
eprintln!("Error while trying to get lock: {}", e.to_string());
std::process::exit(1)
Expand Down

0 comments on commit 9e9bafd

Please sign in to comment.