Skip to content

Commit 15fe32c

Browse files
added some type of logging for now
1 parent 6c807ed commit 15fe32c

File tree

6 files changed

+224
-36
lines changed

6 files changed

+224
-36
lines changed

.gitignore

+3
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,6 @@
22

33
# vscode settings
44
.vscode
5+
6+
# Temporary files
7+
tmp*

Cargo.lock

+119
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

+6-2
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,12 @@ edition = "2021"
55

66
[dependencies]
77
clap = { version = "4.5.23", features = ["derive"] }
8-
lscolors = {version = "0.20.0", features = ["crossterm"]}
8+
lscolors = { version = "0.20.0", features = ["crossterm"] }
99
nu-ansi-term = "0.50.1"
10-
chrono = "0.4.39"
10+
chrono = { version = "0.4.39", features = ["serde"] }
1111
uutils_term_grid = "0.6.0"
1212
terminal_size = "0.4.1"
13+
serde = { version = "1.0.217", features = ["derive"] }
14+
slog = "2.7.0"
15+
serde_json = "1.0.134"
16+
slog-json = "2.6.1"

src/main.rs

+1-8
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
mod trm;
2+
pub mod utils;
23

34
use clap::Parser;
45
use std::path::PathBuf;
@@ -17,14 +18,6 @@ fn main() {
1718
files.push(PathBuf::from(file));
1819
}
1920

20-
match setup_logging() {
21-
Ok(_) => {}
22-
Err(e) => {
23-
eprintln!("Could not setup logging: {}", e);
24-
std::process::exit(1);
25-
}
26-
}
27-
2821
let dir_path = match setup_directory(&args) {
2922
Ok(path) => path,
3023
Err(e) => {

src/trm.rs

+15-26
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use chrono::{DateTime, Local};
1+
use crate::utils::{append_to_logs, FileInfo, OpType};
22
use clap::Parser;
33
use lscolors::LsColors;
44
use std::fs;
@@ -9,7 +9,7 @@ use std::{
99
use term_grid::{Grid, GridOptions};
1010

1111
pub static DEFAULT_DIR: &str = "/var/tmp/trm_files";
12-
pub static LOG_DIR: &str = "/var/log/trm";
12+
pub static LOG_FILE: &str = "/var/tmp/trm.log";
1313

1414
#[derive(Parser, Debug, Default)]
1515
#[command(version, about = "trm - Temporary rm, a utility to reversibly remove your files", long_about=None)]
@@ -41,14 +41,6 @@ pub struct Args {
4141
pub dir: String,
4242
}
4343

44-
struct _FileInfo {
45-
/// The original path from where the path was copied
46-
path: String,
47-
48-
/// The datetime when it was moved
49-
moved_time: DateTime<Local>,
50-
}
51-
5244
macro_rules! get_file_name {
5345
($path:expr) => {
5446
$path.file_name().unwrap().to_str().unwrap().to_string()
@@ -93,22 +85,6 @@ pub fn display_files(files: &Vec<PathBuf>, only_filename: bool) {
9385
println!("{grid}");
9486
}
9587

96-
pub fn setup_logging() -> Result<bool, Error> {
97-
if let Err(e) = std::fs::create_dir_all(LOG_DIR) {
98-
eprintln!("Failed to create logging directory {}: {}", LOG_DIR, e);
99-
return Err(e);
100-
}
101-
102-
let log_path = PathBuf::from(LOG_DIR);
103-
let history_path = log_path.join("history");
104-
105-
if !history_path.try_exists().unwrap() {
106-
std::fs::File::create(history_path).unwrap();
107-
}
108-
109-
Ok(true)
110-
}
111-
11288
pub fn setup_directory(args: &Args) -> Result<PathBuf, Error> {
11389
let dir: String;
11490
let mut var_dir: String = String::new();
@@ -220,6 +196,12 @@ pub fn move_files(args: &Args, dir_path: &PathBuf, files: &Vec<PathBuf>) {
220196
if args.verbose {
221197
println!("Successfully moved {} to trash", full_path.display());
222198
}
199+
append_to_logs(&FileInfo {
200+
src: full_path.display().to_string(),
201+
dst: new_location.display().to_string(),
202+
operation: OpType::TRASH,
203+
moved_time: chrono::offset::Local::now(),
204+
});
223205
}
224206
Err(e) => {
225207
eprintln!(
@@ -311,6 +293,13 @@ pub fn recover_files(args: &Args, dir_path: &PathBuf, files: &mut Vec<PathBuf>,
311293
full_path.display()
312294
);
313295
}
296+
297+
append_to_logs(&FileInfo {
298+
src: file.display().to_string(),
299+
dst: full_path.display().to_string(),
300+
operation: OpType::RESTORE,
301+
moved_time: chrono::offset::Local::now(),
302+
});
314303
}
315304
Err(e) => {
316305
eprintln!(

src/utils.rs

+80
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
use crate::LOG_FILE;
2+
3+
use chrono::{DateTime, Local};
4+
use serde::{Deserialize, Serialize};
5+
use slog::{info, o, Drain, Logger};
6+
use std::{
7+
fs::{File, OpenOptions},
8+
io,
9+
io::{BufRead, BufReader},
10+
sync::Mutex,
11+
};
12+
13+
#[derive(Serialize, Deserialize, Debug)]
14+
pub enum OpType {
15+
TRASH,
16+
RESTORE,
17+
}
18+
19+
impl OpType {
20+
#[allow(dead_code)]
21+
fn as_str(&self) -> &str {
22+
match self {
23+
OpType::TRASH => "Trash",
24+
OpType::RESTORE => "Restore",
25+
}
26+
}
27+
}
28+
29+
#[derive(Serialize, Deserialize, Debug)]
30+
pub struct FileInfo {
31+
/// The original path from where the path was moved
32+
pub src: String,
33+
34+
/// The path where the file ended up in
35+
pub dst: String,
36+
37+
/// Type of operation
38+
pub operation: OpType,
39+
40+
/// The datetime when it was moved
41+
pub moved_time: DateTime<Local>,
42+
}
43+
44+
fn init_logger() -> Logger {
45+
let file = OpenOptions::new()
46+
.create(true)
47+
.write(true)
48+
.append(true)
49+
.open(LOG_FILE)
50+
.unwrap();
51+
52+
let drain = slog_json::Json::new(file).build().fuse();
53+
54+
Logger::root(Mutex::new(drain).fuse(), o!())
55+
}
56+
57+
pub fn append_to_logs(info: &FileInfo) {
58+
let logger = init_logger();
59+
info!(logger, "File Operation";
60+
"SRC" => &info.src,
61+
"DST" => &info.dst,
62+
"OPERATION" => &info.operation.as_str(),
63+
"MOVED_TIME" => &info.moved_time.to_string()
64+
);
65+
}
66+
67+
pub fn read_logs() -> io::Result<Vec<FileInfo>> {
68+
let file = File::open(LOG_FILE).unwrap();
69+
let reader = BufReader::new(file);
70+
let mut logs: Vec<FileInfo> = vec![];
71+
72+
for line in reader.lines() {
73+
let line = line.unwrap();
74+
if let Ok(log) = serde_json::from_str::<FileInfo>(&line) {
75+
logs.push(log);
76+
}
77+
}
78+
79+
Ok(logs)
80+
}

0 commit comments

Comments
 (0)