Skip to content

Commit

Permalink
[swhks] Log flag added
Browse files Browse the repository at this point in the history
* Defaults to XDG_DATA_HOME
* Added debug flag to swhks
* Documented new swhks flags
* Removed clippy warnings

Signed-off-by: Shinyzenith <aakashsensharma@gmail.com>
  • Loading branch information
Shinyzenith committed Aug 17, 2022
1 parent 2997d94 commit a2cdcee
Show file tree
Hide file tree
Showing 8 changed files with 129 additions and 49 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

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

16 changes: 16 additions & 0 deletions docs/swhks.1.scd
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,22 @@ swhks - Server for swhkd, used to run user level commands over IPC.

*swhks*

# OPTIONS

*-h*, *--help*
Print help message and quit.

*-V*, *--version*
Print version information.

*-l*, *--log* <LOG_FILE_PATH>
Set a log file path.
If *XDG_DATA_HOME* exists then we use *swhks/swhks-current_time.log* relative to
it, else we use *~/.local/share/swhks/swhks-current_time.log*.

*-d*, *--debug*
Enable debug mode.

# AUTHORS

Maintained by Shinyzenith <aakashsensharma@gmail.com>, EdenQwQ <lsahlm1eden@gmail.com>, and Angelo Fallaria <ba.fallaria@gmail.com>.
Expand Down
9 changes: 3 additions & 6 deletions swhkd/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,10 @@ use std::{
};

fn main() {
match Command::new("scdoc").spawn() {
Err(e) => {
if let ErrorKind::NotFound = e.kind() {
exit(0);
}
if let Err(e) = Command::new("scdoc").spawn() {
if let ErrorKind::NotFound = e.kind() {
exit(0);
}
_ => {}
}

let mut man_pages: Vec<(String, String)> = Vec::new();
Expand Down
6 changes: 3 additions & 3 deletions swhkd/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ pub enum Error {
InvalidConfig(ParseError),
}

#[derive(Debug, PartialEq)]
#[derive(Debug, PartialEq, Eq)]
pub enum ParseError {
// u32 is the line number where an error occured
UnknownSymbol(PathBuf, u32),
Expand All @@ -34,7 +34,7 @@ impl From<std::io::Error> for Error {

impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &*self {
match self {
Error::ConfigNotFound => "Config file not found.".fmt(f),

Error::Io(io_err) => format!("I/O Error while parsing config file: {}", io_err).fmt(f),
Expand Down Expand Up @@ -66,7 +66,7 @@ pub const MODE_END_STATEMENT: &str = "endmode";
pub const MODE_ENTER_STATEMENT: &str = "@enter";
pub const MODE_ESCAPE_STATEMENT: &str = "@escape";

#[derive(Debug, PartialEq, Clone)]
#[derive(Debug, PartialEq, Clone, Eq)]
pub struct Config {
pub path: PathBuf,
pub contents: String,
Expand Down
6 changes: 2 additions & 4 deletions swhkd/src/daemon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,15 +81,13 @@ async fn main() -> Result<(), Box<dyn Error>> {

log::debug!("Using config file path: {:#?}", config_file_path);

let modes = match config::load(&config_file_path) {
match config::load(&config_file_path) {
Err(e) => {
log::error!("Config Error: {}", e);
exit(1)
}
Ok(out) => out,
};

modes
}
};

let mut modes = load_config();
Expand Down
4 changes: 2 additions & 2 deletions swhkd/src/uinput.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ pub fn create_uinput_device() -> Result<VirtualDevice, Box<dyn std::error::Error
Ok(device)
}
pub fn get_all_keys() -> Vec<evdev::Key> {
return vec![
vec![
evdev::Key::KEY_RESERVED,
evdev::Key::KEY_ESC,
evdev::Key::KEY_1,
Expand Down Expand Up @@ -565,5 +565,5 @@ pub fn get_all_keys() -> Vec<evdev::Key> {
evdev::Key::BTN_TRIGGER_HAPPY38,
evdev::Key::BTN_TRIGGER_HAPPY39,
evdev::Key::BTN_TRIGGER_HAPPY40,
];
]
}
1 change: 1 addition & 0 deletions swhks/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ env_logger = "0.9.0"
log = "0.4.14"
nix = "0.23.1"
sysinfo = "0.23.5"
clap = "3.1.6"

[[bin]]
name = "swhks"
Expand Down
135 changes: 101 additions & 34 deletions swhks/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,49 +1,83 @@
use clap::arg;
use nix::{
libc::daemon,
sys::stat::{umask, Mode},
unistd,
};
use std::io::prelude::*;
use std::os::unix::net::UnixListener;
use std::{
env, fs,
fs::OpenOptions,
io::prelude::*,
os::unix::net::UnixListener,
path::Path,
process::{exit, id, Command, Stdio},
time::{SystemTime, UNIX_EPOCH},
};
use sysinfo::{ProcessExt, System, SystemExt};

fn get_file_paths() -> (String, String) {
match env::var("XDG_RUNTIME_DIR") {
Ok(val) => {
log::info!(
"XDG_RUNTIME_DIR Variable is present, using it's value as default file path."
);

let pid_file_path = format!("{}/swhks.pid", val);
let sock_file_path = format!("{}/swhkd.sock", val);

(pid_file_path, sock_file_path)
}
Err(e) => {
log::trace!("XDG_RUNTIME_DIR Variable is not set, falling back on hardcoded path.\nError: {:#?}", e);

let pid_file_path = format!("/run/user/{}/swhks.pid", unistd::Uid::current());
let sock_file_path = format!("/run/user/{}/swhkd.sock", unistd::Uid::current());
fn main() -> std::io::Result<()> {
env::set_var("RUST_LOG", "swhks=warn");

(pid_file_path, sock_file_path)
}
let app = clap::Command::new("swhks")
.version(env!("CARGO_PKG_VERSION"))
.author(env!("CARGO_PKG_AUTHORS"))
.about("IPC Server for swhkd")
.arg(arg!(-l --log <FILE>).required(false).takes_value(true).help(
"Set a custom log file. (Defaults to ${XDG_DATA_HOME:-$HOME/.local/share}/swhks-current_unix_time.log)",
))
.arg(arg!(-d --debug).required(false).takes_value(false).help(
"Enable debug mode."
));
let args = app.get_matches();
if args.is_present("debug") {
env::set_var("RUST_LOG", "swhks=trace");
}
}

fn main() -> std::io::Result<()> {
env::set_var("RUST_LOG", "swhks=trace");
env_logger::init();

log::trace!("Setting process umask.");
umask(Mode::S_IWGRP | Mode::S_IWOTH);

let (pid_file_path, sock_file_path) = get_file_paths();

let log_file_name = if let Some(val) = args.value_of("log") {
val.to_string()
} else {
let time = match SystemTime::now().duration_since(UNIX_EPOCH) {
Ok(n) => n.as_secs().to_string(),
Err(_) => {
log::error!("SystemTime before UnixEpoch!");
exit(1);
}
};

match env::var("XDG_DATA_HOME") {
Ok(val) => {
log::info!(
"XDG_DATA_HOME Variable is present, using it's value for default file path."
);
format!("{}/swhks/swhks-{}.log", val, time)
}
Err(e) => {
log::trace!(
"XDG_DATA_HOME Variable is not set, falling back on hardcoded path.\nError: {:#?}",
e
);

format!("~/.local/share/swhks/swhks-{}.log", time)
}
}
};

let log_path = Path::new(&log_file_name);
if let Some(p) = log_path.parent() {
if !p.exists() {
if let Err(e) = fs::create_dir_all(p) {
log::error!("Failed to create log dir: {}", e);
}
}
}

if Path::new(&pid_file_path).exists() {
log::trace!("Reading {} file and checking for running instances.", pid_file_path);
let swhks_pid = match fs::read_to_string(&pid_file_path) {
Expand Down Expand Up @@ -93,30 +127,63 @@ fn main() -> std::io::Result<()> {
Ok((mut socket, address)) => {
let mut response = String::new();
socket.read_to_string(&mut response)?;
run_system_command(&response);
run_system_command(&response, log_path);
log::debug!("Socket: {:?} Address: {:?} Response: {}", socket, address, response);
}
Err(e) => log::error!("accept function failed: {:?}", e),
}
}
}

fn run_system_command(command: &str) {
fn get_file_paths() -> (String, String) {
match env::var("XDG_RUNTIME_DIR") {
Ok(val) => {
log::info!(
"XDG_RUNTIME_DIR Variable is present, using it's value as default file path."
);

let pid_file_path = format!("{}/swhks.pid", val);
let sock_file_path = format!("{}/swhkd.sock", val);

(pid_file_path, sock_file_path)
}
Err(e) => {
log::trace!("XDG_RUNTIME_DIR Variable is not set, falling back on hardcoded path.\nError: {:#?}", e);

let pid_file_path = format!("/run/user/{}/swhks.pid", unistd::Uid::current());
let sock_file_path = format!("/run/user/{}/swhkd.sock", unistd::Uid::current());

(pid_file_path, sock_file_path)
}
}
}

fn run_system_command(command: &str, log_path: &Path) {
unsafe {
daemon(1, 0);
}
match Command::new("sh")

if let Err(e) = Command::new("sh")
.arg("-c")
.arg(command)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.stdout(match OpenOptions::new().append(true).create(true).open(log_path) {
Ok(file) => file,
Err(e) => {
_ = Command::new("notify-send").arg(format!("ERROR {}", e)).spawn();
exit(1);
}
})
.stderr(match OpenOptions::new().append(true).create(true).open(log_path) {
Ok(file) => file,
Err(e) => {
_ = Command::new("notify-send").arg(format!("ERROR {}", e)).spawn();
exit(1);
}
})
.spawn()
{
Ok(_) => {}
Err(e) => {
log::error!("Failed to execute {}", command);
log::error!("Error, {}", e);
}
log::error!("Failed to execute {}", command);
log::error!("Error: {}", e);
}
}

0 comments on commit a2cdcee

Please sign in to comment.