Skip to content

Commit

Permalink
more helpers, utils and refactors
Browse files Browse the repository at this point in the history
  • Loading branch information
Kyagara committed Jun 21, 2023
1 parent c6690b8 commit 92c75f7
Show file tree
Hide file tree
Showing 14 changed files with 252 additions and 173 deletions.
2 changes: 0 additions & 2 deletions src/application.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,6 @@ pub fn get_app_status(name: &String) -> Result<ApplicationInfo> {

loop {
let read = stream.read(&mut received)?;

if read > 0 {
return Ok(serde_json::from_slice::<ApplicationInfo>(
&received[..read],
Expand All @@ -140,7 +139,6 @@ pub fn ping_app(name: &String) -> Result<SocketEvent> {

loop {
let read = stream.read(&mut received)?;

if read > 0 {
return Ok(serde_json::from_slice::<SocketEvent>(&received[..read])?);
}
Expand Down
5 changes: 2 additions & 3 deletions src/commands/attach.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{
application,
subprocess::{read_socket_stream, SocketEvent},
subprocess::{self, SocketEvent},
tail,
};
use anyhow::{anyhow, Result};
Expand Down Expand Up @@ -269,7 +269,6 @@ fn socket_handler(
match event {
Ok(event) => {
s.write_all(&event).unwrap();
s.flush().unwrap();
}
Err(err) => {
debug!("Error serializing event: {err}")
Expand All @@ -283,7 +282,7 @@ fn socket_handler(
let mut read: usize = 0;

thread::spawn(move || {
while read_socket_stream(&mut stream, &mut received, &mut read) > 0 {
while subprocess::read_socket_stream(&mut stream, &mut received, &mut read) > 0 {
match serde_json::from_slice::<SocketEvent>(&received[..read]) {
Ok(message) => {
sender.send(TerminalEvent::SocketEvent(message)).unwrap();
Expand Down
20 changes: 8 additions & 12 deletions src/commands/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ pub struct ListArgs;
struct ApplicationInfo {
#[tabled(rename = "Name")]
name: String,
#[tabled(rename = "Crescent PID")]
#[tabled(rename = "crescent PID")]
crescent_pid: Pid,
#[tabled(rename = "Subprocess PID")]
subprocess_pid: String,
Expand All @@ -25,16 +25,14 @@ struct ApplicationInfo {

impl ListArgs {
pub fn run(self) -> Result<()> {
let mut crescent_pathbuf = crescent::crescent_dir()?;
let apps_dir = crescent::get_apps_dir()?;

crescent_pathbuf.push("apps");

let crescent_dir = crescent_pathbuf
let dirs = apps_dir
.read_dir()
.context("Error reading crescent directory.")?
.context("Error reading apps directory.")?
.flatten();

let apps = self.get_applications_info(crescent_dir)?;
let apps = self.get_applications_info(dirs)?;

if apps.is_empty() {
println!("No application running.");
Expand Down Expand Up @@ -116,18 +114,16 @@ mod tests {
test_utils::start_long_running_service(name)?;
assert!(test_utils::check_app_is_running(name)?);

let mut crescent_pathbuf = crescent::crescent_dir()?;

crescent_pathbuf.push("apps");
let apps_dir = crescent::get_apps_dir()?;

let crescent_dir = crescent_pathbuf
let dirs = apps_dir
.read_dir()
.context("Error reading crescent directory.")?
.flatten();

let list_command = ListArgs {};

let apps = list_command.get_applications_info(crescent_dir)?;
let apps = list_command.get_applications_info(dirs)?;
let app = apps.into_iter().find(|app| app.name == name).unwrap();

assert_eq!(&app.name, &name);
Expand Down
66 changes: 60 additions & 6 deletions src/commands/profile.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,78 @@
use crate::crescent::{self, Profile};
use crate::{crescent, util};
use anyhow::Result;
use clap::Args;
use std::fs;

#[derive(Args)]
#[command(about = "Verify and print a profile.")]
pub struct ProfileArgs {
#[arg(help = "Profile name.")]
pub profile: String,

#[arg(short, long, help = "Prints the profile in prettified json.")]
pub json: bool,
}

impl ProfileArgs {
pub fn run(self) -> Result<()> {
let profile_path = crescent::get_profile_path(self.profile)?;
let json_str = fs::read_to_string(profile_path)?;
let profile: Profile = serde_json::from_str(&json_str)?;
let profile = crescent::get_profile(&self.profile)?;
let profile_pretty = serde_json::to_string_pretty(&profile)?;

println!("{profile_pretty}");
if self.json {
println!("{profile_pretty}");
return Ok(());
}

util::print_title_cyan(&format!("Profile '{}'", self.profile));

if let Some(comment) = profile.__comment {
util::println_field_white("Comment", comment);
}

if let Some(version) = profile.__version {
util::println_field_white("Version", version);
}

if let Some(file_path) = profile.file_path {
util::println_field_white("File Path", file_path);
}

if let Some(name) = profile.name {
util::println_field_white("Name", name);
}

if let Some(interpreter) = profile.interpreter {
util::println_field_white("Interpreter", interpreter);
}

if let Some(interpreter_arguments) = profile.interpreter_arguments {
util::println_field_white("Interpreter arguments", interpreter_arguments.join(" "));
}

if let Some(application_arguments) = profile.application_arguments {
util::println_field_white("Application arguments", application_arguments.join(" "));
}

if let Some(stop_command) = profile.stop_command {
util::println_field_white("Stop command", stop_command);
}

Ok(())
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn unit_profile_run() -> Result<()> {
let command = ProfileArgs {
profile: "profile_not_found".to_string(),
json: false,
};
assert_eq!(command.profile, "profile_not_found");
let err = command.run().unwrap_err();
assert_eq!(format!("{}", err), "Profile not found.");
Ok(())
}
}
1 change: 0 additions & 1 deletion src/commands/send.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ impl SendArgs {
let event = serde_json::to_vec(&SocketEvent::WriteStdin(self.command.join(" ")))?;

stream.write_all(&event)?;
stream.flush()?;

println!("Command sent.");

Expand Down
4 changes: 1 addition & 3 deletions src/commands/start.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,7 @@ impl StartArgs {
let stop_command = match &self.profile {
Some(profile_str) => {
profile_name = profile_str.clone();
let profile_path = crescent::get_profile_path(profile_str.to_string())?;
let string = fs::read_to_string(profile_path)?;
let profile: Profile = serde_json::from_str(&string)?;
let profile = crescent::get_profile(profile_str)?;
self = self.overwrite_args(profile.clone().into())?;
profile.stop_command
}
Expand Down
59 changes: 20 additions & 39 deletions src/commands/status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use crate::{application, util};
use anyhow::Result;
use chrono::{DateTime, Local, TimeZone, Utc};
use clap::Args;
use crossterm::style::Stylize;
use std::println;
use sysinfo::{ProcessExt, System, SystemExt};

Expand Down Expand Up @@ -32,20 +31,14 @@ impl StatusArgs {
system.refresh_process(subprocess_pid);
system.refresh_memory();

println!("{}", "Application information:".bold().cyan());
println!("{} {}", "Name:".white(), status.name);
println!(
"{} \"{}\"",
"Interpreter arguments:".white(),
status.interpreter_args.join(" ")
);
println!(
"{} \"{}\"",
"Application arguments:".white(),
status.application_args.join(" ")
);
println!("{} {}", "Profile:".white(), status.profile);
println!("{} {}", "crescent PID:".white(), pids[0]);
util::print_title_cyan("Application information");

util::println_field_white("Name", status.name);
util::println_field_white("Interpreter arguments", status.interpreter_args.join(" "));
util::println_field_white("Application arguments", status.application_args.join(" "));
util::println_field_white("Profile", status.profile);
util::println_field_white("crescent PID", pids[0]);

println!();

if let Some(process) = system.process(subprocess_pid) {
Expand All @@ -56,33 +49,21 @@ impl StatusArgs {
.unwrap();
let start_time: DateTime<Local> = DateTime::from(utc);

println!("{}", "Subprocess information:".bold().cyan());
println!("{} {}", "Subprocess PID:".white(), subprocess_pid);
println!("{} {:?}", "CWD:".white(), process.cwd());
println!(
"{} \"{}\"",
"Full command line:".white(),
status.cmd.join(" ")
);
util::print_title_cyan("Subprocess information");

println!(
"{} {:.2}%",
"CPU usage:".white(),
process.cpu_usage() / cpu_count,
util::println_field_white("Subprocess PID", subprocess_pid);
util::println_field_white("CWD", process.cwd().to_string_lossy());
util::println_field_white("Full command line", status.cmd.join(" "));
util::println_field_white(
"CPU usage",
format!("{:.2}", process.cpu_usage() / cpu_count),
);
println!(
"{} {:.2}% ({} Mb)",
"Memory usage:".white(),
memory,
process.memory() / 1024 / 1024
);

println!("{} {}", "Started at:".white(), start_time);
println!(
"{} {}",
"Uptime:".white(),
util::get_uptime_from_seconds(process.run_time())
util::println_field_white(
"Memory usage",
format!("{:.2}% ({} Mb)", memory, process.memory() / 1024 / 1024),
);
util::println_field_white("Started at", start_time);
util::println_field_white("Uptime", util::get_uptime_from_seconds(process.run_time()));
}

Ok(())
Expand Down
9 changes: 3 additions & 6 deletions src/commands/stop.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
use std::{io::Write, os::unix::net::UnixStream};

use crate::{application, subprocess::SocketEvent};

use super::signal;
use crate::{application, subprocess::SocketEvent};
use anyhow::{Context, Result};
use clap::Args;
use std::{io::Write, os::unix::net::UnixStream};

#[derive(Args)]
#[command(about = "Send a stop command or a SIGTERM signal to the application subprocess.")]
Expand Down Expand Up @@ -41,9 +39,8 @@ impl StopArgs {
let event = serde_json::to_vec(&SocketEvent::Stop())?;

stream.write_all(&event)?;
stream.flush()?;

println!("Stop command event sent.");
println!("Stop command sent.");

Ok(())
}
Expand Down

0 comments on commit 92c75f7

Please sign in to comment.