Skip to content

Commit

Permalink
completion command
Browse files Browse the repository at this point in the history
  • Loading branch information
Kyagara committed Jun 28, 2023
1 parent bf5d8f8 commit f908fad
Show file tree
Hide file tree
Showing 8 changed files with 79 additions and 40 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

All notable changes to this project will be documented in this file.

## [Unreleased]

### Added

- `complete <terminal>` command to create a basic completions file for the selected terminal. `cres complete > /usr/share/bash-completion/completions/cres`.

## [0.5.0] - 2023-06-23

### Added
Expand Down
10 changes: 10 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 @@ -39,6 +39,7 @@ chrono = { version = "0.4.26", default-features = false }
libc = { version = "0.2.146" }
serde = { version = "1.0.164", features = ["derive"] }
serde_json = "1.0.96"
clap_complete = "4.3.1"

[dev-dependencies]
anyhow.workspace = true
Expand Down
12 changes: 6 additions & 6 deletions src/commands/start.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@ use super::save::SaveFile;
use crate::{
application::{self, Application},
crescent::{self, Profile},
logger, subprocess,
util::{self, print_title_cyan},
logger, subprocess, util,
};
use anyhow::{anyhow, Context, Result};
use clap::Args;
use clap::{Args, ValueHint};
use daemonize::Daemonize;
use log::LevelFilter;
use serde::{Deserialize, Serialize};
Expand All @@ -18,6 +17,7 @@ use std::{
#[derive(Args, Clone, Serialize, Deserialize, Default)]
#[command(about = "Start an application from the file path provided.")]
pub struct StartArgs {
#[arg(value_hint = ValueHint::AnyPath)]
pub file_path: Option<String>,

#[arg(
Expand Down Expand Up @@ -231,12 +231,12 @@ fn start_saved() -> Result<()> {
return Err(anyhow!("List of apps is empty."));
}

print_title_cyan("Starting applications.");
util::print_title_cyan("Starting applications.");

for app_info in save_file.apps {
if application::app_already_running(&app_info.name)? {
println!(
"An application with the name `{}` is already running. Skipping.",
"An application with the name '{}' is already running. Skipping.",
app_info.name
);

Expand Down Expand Up @@ -290,7 +290,7 @@ pub fn start(app_info: Application) -> Result<()> {

fs::create_dir_all(&app_dir).context("Error creating application directory.")?;

eprintln!("Starting `{}` application.", app_info.name);
eprintln!("Starting '{}' application.", app_info.name);

{
let log = File::create(app_dir.join(app_info.name.clone() + ".log"))?;
Expand Down
56 changes: 33 additions & 23 deletions src/commands/status.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::{application, util};
use anyhow::Result;
use anyhow::{anyhow, Result};
use chrono::{DateTime, Local, TimeZone, Utc};
use clap::Args;
use std::println;
Expand Down Expand Up @@ -38,40 +38,50 @@ impl StatusArgs {

util::print_title_cyan("Application information");

util::println_field_white("crescent PID", pids[0]);
util::println_field_white("Name", status.name);
util::println_field_white("Interpreter arguments", i_args);
util::println_field_white("Application arguments", a_args);
util::println_field_white(
"Profile",
status.start_args.profile.unwrap_or(String::new()),
);
util::println_field_white("crescent PID", pids[0]);

println!();

if let Some(process) = system.process(subprocess_pid) {
let memory = process.memory() as f64 / system.total_memory() as f64 * 100.0;
let cpu_count = system.physical_core_count().unwrap() as f32;
let utc = Utc
.timestamp_opt(process.start_time().try_into().unwrap(), 0)
.unwrap();
let start_time: DateTime<Local> = DateTime::from(utc);
util::print_title_cyan("Subprocess information");
util::println_field_white("PID", subprocess_pid);
util::println_field_white("Full command line", status.cmd.join(" "));

util::print_title_cyan("Subprocess information");
match system.process(subprocess_pid) {
Some(process) => {
let memory = process.memory() as f64 / system.total_memory() as f64 * 100.0;
let cpu_count = system.physical_core_count().unwrap() as f32;
let utc = Utc
.timestamp_opt(process.start_time().try_into().unwrap(), 0)
.unwrap();
let start_time: DateTime<Local> = DateTime::from(utc);

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),
);
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()));
util::println_field_white("CWD", process.cwd().to_string_lossy());
util::println_field_white(
"CPU usage",
format!("{:.2}", process.cpu_usage() / cpu_count),
);
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()),
);
}
None => {
return Err(anyhow!(
"Error retrieving subprocess information, process does not exist."
))
}
}

Ok(())
Expand Down
6 changes: 1 addition & 5 deletions src/commands/stop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,7 @@ pub struct StopArgs {
#[arg(help = "Application name.")]
pub name: String,

#[arg(
short,
long,
help = "Ignore 'stop command' if defined and send a SIGTERM signal."
)]
#[arg(short, long, help = "Ignore 'stop_command' and send a SIGTERM signal.")]
pub force: bool,
}

Expand Down
16 changes: 12 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ use crate::commands::{
};
use crate::Commands::*;
use anyhow::Result;
use clap::{Parser, Subcommand};
use clap::{CommandFactory, Parser, Subcommand};
use clap_complete::Shell;
use std::io;

mod application;
mod commands;
Expand Down Expand Up @@ -35,6 +37,10 @@ enum Commands {
Status(StatusArgs),
Profile(ProfileArgs),
Save(SaveArgs),
#[command(about = "Print a completions file for the specified shell.")]
Complete {
shell: Shell,
},
}

fn main() -> Result<()> {
Expand All @@ -52,7 +58,9 @@ fn main() -> Result<()> {
Kill(args) => KillArgs::run(args),
Profile(args) => ProfileArgs::run(args),
Save(args) => SaveArgs::run(args),
}?;

Ok(())
Complete { shell } => {
clap_complete::generate(shell, &mut Crescent::command(), "cres", &mut io::stdout());
Ok(())
}
}
}
12 changes: 10 additions & 2 deletions tests/not_exist.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
use anyhow::Result;

#[test]
fn create_completions() -> Result<()> {
let mut cmd = test_utils::get_base_command();
cmd.args(vec!["complete", "bash"]);
cmd.assert().success();
Ok(())
}

#[test]
fn log_no_apps_running() -> Result<()> {
test_utils::execute_against_app_not_exist(vec!["log", "test_app_not_exist"])
Expand Down Expand Up @@ -27,10 +35,10 @@ fn stop_no_apps_running() -> Result<()> {

#[test]
fn kill_no_apps_running() -> Result<()> {
test_utils::execute_against_app_not_exist(vec!["kill", "test_app_not_available"])
test_utils::execute_against_app_not_exist(vec!["kill", "test_app_not_exist"])
}

#[test]
fn attach_no_apps_running() -> Result<()> {
test_utils::execute_against_app_not_exist(vec!["attach", "test_app_not_available"])
test_utils::execute_against_app_not_exist(vec!["attach", "test_app_not_exist"])
}

0 comments on commit f908fad

Please sign in to comment.