From da87692db2077665a4741d59223398f0104b2530 Mon Sep 17 00:00:00 2001 From: ByteOtter Date: Thu, 1 Aug 2024 11:42:04 +0200 Subject: [PATCH 01/25] Add screen view module Implement image capturing Format code --- isototest/Cargo.toml | 1 + isototest/src/action.rs | 6 -- isototest/src/connection.rs | 5 +- isototest/src/lib.rs | 1 + isototest/src/view.rs | 109 ++++++++++++++++++++++++++++++++++++ 5 files changed, 115 insertions(+), 7 deletions(-) create mode 100644 isototest/src/view.rs diff --git a/isototest/Cargo.toml b/isototest/Cargo.toml index 3b8918b..b2e4b7d 100644 --- a/isototest/Cargo.toml +++ b/isototest/Cargo.toml @@ -8,6 +8,7 @@ repository = "https://github.com/ByteOtter/isotest-ng/tree/main/isototest" license = "GPL-2.0" [dependencies] +image = "0.25.2" tokio = "1.38.1" vnc-rs = "0.5.1" diff --git a/isototest/src/action.rs b/isototest/src/action.rs index a3d8156..4a8c468 100644 --- a/isototest/src/action.rs +++ b/isototest/src/action.rs @@ -68,12 +68,6 @@ pub async fn write_to_console( Ok(()) } -#[allow(unused)] -/// Receive a screenshot of the remote machine. -pub async fn read_screen(client: &VncClient) -> Result<(), VncError> { - todo!("Not implemented yet!") -} - /// Encapsulate the `client.input()` function calls to avoid repitition. /// /// Press and release a button or release it manually, if it is pressed. diff --git a/isototest/src/connection.rs b/isototest/src/connection.rs index 637c0fe..00ed5db 100644 --- a/isototest/src/connection.rs +++ b/isototest/src/connection.rs @@ -49,8 +49,11 @@ pub async fn create_vnc_client( .add_encoding(vnc::VncEncoding::Zrle) .add_encoding(vnc::VncEncoding::CopyRect) .add_encoding(vnc::VncEncoding::Raw) + .add_encoding(vnc::VncEncoding::Trle) + .add_encoding(vnc::VncEncoding::CursorPseudo) + .add_encoding(vnc::VncEncoding::DesktopSizePseudo) .allow_shared(true) - .set_pixel_format(PixelFormat::bgra()) + .set_pixel_format(PixelFormat::rgba()) .build()? .try_start() .await? diff --git a/isototest/src/lib.rs b/isototest/src/lib.rs index 39cf48f..7bd5dad 100644 --- a/isototest/src/lib.rs +++ b/isototest/src/lib.rs @@ -1,3 +1,4 @@ pub mod action; pub mod connection; mod types; +pub mod view; diff --git a/isototest/src/view.rs b/isototest/src/view.rs new file mode 100644 index 0000000..028b373 --- /dev/null +++ b/isototest/src/view.rs @@ -0,0 +1,109 @@ +use image::{GenericImage, ImageFormat, Rgba}; +use std::{ + path::Path, + time::{Duration, Instant}, +}; + +use image::ImageBuffer; + +use image::DynamicImage::ImageRgba8; +use vnc::{Rect, VncClient, VncError, VncEvent, X11Event}; + +/// Receive a screenshot of the remote machine. +pub async fn read_screen( + client: &VncClient, + file_path: &str, + resolution: Option<(u32, u32)>, + timeout: Duration, +) -> Result<(u32, u32), VncError> { + // Request screen update + client.input(X11Event::Refresh).await?; + + let mut img_parts: Vec<(Rect, Vec)> = Vec::new(); + let mut width; + let mut height; + match resolution { + Some((x, y)) => { + width = Some(x); + height = Some(y); + } + None => match client.recv_event().await? { + VncEvent::SetResolution(screen) => { + println!("Screen resolution: {}x{}", screen.width, screen.height); + width = Some(screen.width as u32); + height = Some(screen.height as u32); + + client.input(X11Event::Refresh).await?; + } + _ => { + return Err(VncError::General( + "[error] No resolution found!".to_string(), + )) + } + }, + } + let path: &Path = Path::new(file_path); + + let idle_timer = Instant::now(); + + loop { + match client.poll_event().await? { + Some(x) => match x { + VncEvent::SetResolution(screen) => { + println!("Screen resolution: {}x{}", screen.width, screen.height); + width = Some(screen.width as u32); + height = Some(screen.height as u32); + + client.input(X11Event::Refresh).await?; + } + VncEvent::RawImage(rect, data) => { + img_parts.push((rect, data)); + } + VncEvent::Error(e) => { + eprintln!("[error] {}", e); + break; + } + x => { + println!("{:?}", x); + break; + } + }, + None => { + if idle_timer.elapsed() >= timeout { + break; + } + } + } + } + let mut image: ImageBuffer, _> = ImageBuffer::new(width.unwrap(), height.unwrap()); + + // Reconstruct image. + for (rect, data) in img_parts { + let mut view = image.sub_image( + rect.x as u32, + rect.y as u32, + rect.width as u32, + rect.height as u32, + ); + let image_buffer: ImageBuffer, _> = + ImageBuffer::from_raw(rect.width as u32, rect.height as u32, data.to_vec()) + .ok_or("Failed to create image buffer!") + .unwrap(); + + for x in 0..rect.width { + for y in 0..rect.height { + view.put_pixel( + x as u32, + y as u32, + image_buffer.get_pixel(x as u32, y as u32).to_owned(), + ); + } + } + } + ImageRgba8(image) + .save_with_format(path, ImageFormat::Png) + .unwrap(); + + println!("Screenshot saved to {}", file_path); + Ok((width.unwrap(), height.unwrap())) +} From b43eff69d82a53bc5ded4ca5edbbfab539d1c2d3 Mon Sep 17 00:00:00 2001 From: ByteOtter Date: Fri, 2 Aug 2024 17:19:28 +0200 Subject: [PATCH 02/25] Update test application --- vnc-test/src/main.rs | 36 ++++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/vnc-test/src/main.rs b/vnc-test/src/main.rs index 62efa0e..1cb328a 100644 --- a/vnc-test/src/main.rs +++ b/vnc-test/src/main.rs @@ -1,9 +1,11 @@ use isototest::action::write_to_console; use isototest::connection::create_vnc_client; +use isototest::view::read_screen; use nix::sys::socket::{self, sockaddr_in, AddressFamily, SockType}; use std::process::exit; use std::process::{Command, Stdio}; use std::ptr::null_mut; +use std::time::Duration; use tokio::{ self, net::{TcpListener, TcpStream}, @@ -78,7 +80,7 @@ async fn main() -> Result<(), Box> { // let addr = vnc_server.srv.as_ref().unwrap().local_addr()?; let addr = ""; let psw = "password".to_string(); - let client = match create_vnc_client(addr.to_string(), Some(psw)).await { + let mut client = match create_vnc_client(addr.to_string(), Some(psw.clone())).await { Ok(client) => { println!("Client created. Handshake successful."); client @@ -89,7 +91,19 @@ async fn main() -> Result<(), Box> { } }; - match write_to_console(&client, include_str!("test.txt").to_string(), None).await { + let mut res; + match read_screen(&client, "screenshot.png", None, Duration::from_secs(1)).await { + Ok(x) => { + println!("Screenshot saved!"); + res = x; + }, + Err(e) => { + eprintln!("{}", e); + exit(1); + } + } + + match write_to_console(&client, include_str!("hello.txt").to_string(), None).await { Ok(_) => { println!("Test text sent!"); } @@ -99,5 +113,23 @@ async fn main() -> Result<(), Box> { } } + match read_screen(&client, "screenshot2.png", Some(res), Duration::from_secs(1)).await { + Ok(_) => { + println!("Screenshot saved!"); + }, + Err(e) => { + eprintln!("{}", e); + exit(1); + } + } + match read_screen(&client, "screenshot3.png", Some(res), Duration::from_secs(1)).await { + Ok(_) => { + println!("Screenshot saved!"); + }, + Err(e) => { + eprintln!("{}", e); + exit(1); + } + } Ok(()) } From 8b4c8d321f8ccfc253309c854bb0ff445349ee52 Mon Sep 17 00:00:00 2001 From: ByteOtter Date: Fri, 2 Aug 2024 17:31:56 +0200 Subject: [PATCH 03/25] Document read_screen function --- isototest/src/connection.rs | 2 ++ isototest/src/view.rs | 32 +++++++++++++++++++++++++++++--- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/isototest/src/connection.rs b/isototest/src/connection.rs index 00ed5db..b893cd7 100644 --- a/isototest/src/connection.rs +++ b/isototest/src/connection.rs @@ -53,6 +53,8 @@ pub async fn create_vnc_client( .add_encoding(vnc::VncEncoding::CursorPseudo) .add_encoding(vnc::VncEncoding::DesktopSizePseudo) .allow_shared(true) + // NOTE: If the color encoding is changed in the following line, you must also change it in + // view.rs to avoid the saved screenshots from having swapped colors. .set_pixel_format(PixelFormat::rgba()) .build()? .try_start() diff --git a/isototest/src/view.rs b/isototest/src/view.rs index 028b373..1622f75 100644 --- a/isototest/src/view.rs +++ b/isototest/src/view.rs @@ -10,18 +10,40 @@ use image::DynamicImage::ImageRgba8; use vnc::{Rect, VncClient, VncError, VncEvent, X11Event}; /// Receive a screenshot of the remote machine. +/// +/// # Parameters +/// +/// * client: `&VncClient` - The client instance used for connection. +/// * file_path: `&str` - A file path you want to save your screenshot under as a `str`. +/// * resolution: `Option` - The resolution of the VNC session. +/// * timeout: `Duration` - The `Duration` this function should wait for a `VncEvent` before it +/// continues. +/// +/// **NOTE**: The `resolution` must be passed to all calls of `read_screen` except the first one. +/// If it is not passed, the function will attempt to detect the resolution from the VNC server. +/// This only works for the first time though. The client cannot retrieve the resolution a second +/// time by itself as long as it has not changed. We recommend to save the `Ok()` return value of +/// the function so you have a global resolution tate to return to when calling. +/// +/// # Returns +/// +/// * `Ok((u32, u32))` - The resolution of the VNC machine we connect to. +/// * `Err(VncError)` - Variation of `VncError` if something goes wrong. pub async fn read_screen( client: &VncClient, file_path: &str, resolution: Option<(u32, u32)>, timeout: Duration, ) -> Result<(u32, u32), VncError> { - // Request screen update + // Request screen update. client.input(X11Event::Refresh).await?; let mut img_parts: Vec<(Rect, Vec)> = Vec::new(); let mut width; let mut height; + + // Try to detect screen resolution of the remote machine if it has not been passed. + // **This will cause issues, if you try to use this functionality a second time.** match resolution { Some((x, y)) => { width = Some(x); @@ -42,11 +64,12 @@ pub async fn read_screen( } }, } - let path: &Path = Path::new(file_path); + let path: &Path = Path::new(file_path); let idle_timer = Instant::now(); loop { + // Poll new vnc events. match client.poll_event().await? { Some(x) => match x { VncEvent::SetResolution(screen) => { @@ -77,7 +100,7 @@ pub async fn read_screen( } let mut image: ImageBuffer, _> = ImageBuffer::new(width.unwrap(), height.unwrap()); - // Reconstruct image. + // Reconstruct image from snippets sent by VNC server. for (rect, data) in img_parts { let mut view = image.sub_image( rect.x as u32, @@ -100,6 +123,9 @@ pub async fn read_screen( } } } + + // Save image to file system in PNG format. + // NOTE: If the image color encoding is changed here, you must also change it in connection.rs! ImageRgba8(image) .save_with_format(path, ImageFormat::Png) .unwrap(); From c0581d3271328b8359dc6347b28a3e2831e2456f Mon Sep 17 00:00:00 2001 From: ByteOtter Date: Mon, 5 Aug 2024 09:30:56 +0200 Subject: [PATCH 04/25] Add type annotations --- isototest/src/view.rs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/isototest/src/view.rs b/isototest/src/view.rs index 1622f75..5a6f1c2 100644 --- a/isototest/src/view.rs +++ b/isototest/src/view.rs @@ -39,8 +39,8 @@ pub async fn read_screen( client.input(X11Event::Refresh).await?; let mut img_parts: Vec<(Rect, Vec)> = Vec::new(); - let mut width; - let mut height; + let mut width: Option; + let mut height: Option; // Try to detect screen resolution of the remote machine if it has not been passed. // **This will cause issues, if you try to use this functionality a second time.** @@ -66,7 +66,7 @@ pub async fn read_screen( } let path: &Path = Path::new(file_path); - let idle_timer = Instant::now(); + let idle_timer: Instant = Instant::now(); loop { // Poll new vnc events. @@ -84,10 +84,13 @@ pub async fn read_screen( } VncEvent::Error(e) => { eprintln!("[error] {}", e); - break; + return Err(VncError::General(e)); } x => { - println!("{:?}", x); + println!( + "[warning] Function 'read_screen' got unexpected event '{:?}'.", + x + ); break; } }, @@ -98,6 +101,7 @@ pub async fn read_screen( } } } + let mut image: ImageBuffer, _> = ImageBuffer::new(width.unwrap(), height.unwrap()); // Reconstruct image from snippets sent by VNC server. From 1ca86f0b4bf8b5f7aee14c0c85a6ecd9ff82e919 Mon Sep 17 00:00:00 2001 From: Christopher Hock Date: Thu, 1 Aug 2024 13:45:35 +0200 Subject: [PATCH 05/25] Update CONTRIBUTING.md Signed-off-by: Christopher Hock --- docs/CONTRIBUTING.md | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md index 98d5aff..6566a3a 100644 --- a/docs/CONTRIBUTING.md +++ b/docs/CONTRIBUTING.md @@ -42,14 +42,3 @@ Code without tests might be rejected or take longer to process. If you discover a security vulnerability in our code, please inform us privately immediately according to our [Security Policy](./SECURITY.md). If you wish to fix a vulnerability, please also inform us and stand by for our green light. We would still like to investigate the vulnerability for ourselves to get an overview over the severity and scope of the problem. *Please refrain from publishing a fix until we came back to you or have published a security advisory*. - -## Disclaimer - -By contributing to this project you agree to surrender your contribution to the Nazara Project. - -Your contribution to this project will be subject to the same licensing terms as the rest of the project. - -This is a standard practice in open-source projects to ensure that all contributions are compatible with the project's overall license and to maintain consistency in the project's legal framework. - -It's important for contributors to be aware of this agreement to ensure that their contributions are properly integrated into the project without any legal conflicts. -#### Thank you for your contribution! From 8cdfe9471f4db5963f8083fbe02240b1f026a3f8 Mon Sep 17 00:00:00 2001 From: ByteOtter Date: Tue, 6 Aug 2024 13:30:28 +0200 Subject: [PATCH 06/25] Fix typo in view module docstring --- isototest/src/view.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/isototest/src/view.rs b/isototest/src/view.rs index 5a6f1c2..d85aabf 100644 --- a/isototest/src/view.rs +++ b/isototest/src/view.rs @@ -23,7 +23,7 @@ use vnc::{Rect, VncClient, VncError, VncEvent, X11Event}; /// If it is not passed, the function will attempt to detect the resolution from the VNC server. /// This only works for the first time though. The client cannot retrieve the resolution a second /// time by itself as long as it has not changed. We recommend to save the `Ok()` return value of -/// the function so you have a global resolution tate to return to when calling. +/// the function so you have a global resolution state to return to when calling. /// /// # Returns /// From 6e7e6ccff805c780bf5051b0f3fd8db1c3bf6a0c Mon Sep 17 00:00:00 2001 From: ByteOtter Date: Tue, 6 Aug 2024 14:41:12 +0200 Subject: [PATCH 07/25] Restructure library * Restructure library with submodules * Add Documentation with examples --- .../src/{action.rs => action/keyboard.rs} | 20 ++++-- isototest/src/action/mod.rs | 3 + isototest/src/{ => action}/view.rs | 1 + isototest/src/connection.rs | 4 +- isototest/src/lib.rs | 71 ++++++++++++++++++- isototest/src/types.rs | 6 +- 6 files changed, 93 insertions(+), 12 deletions(-) rename isototest/src/{action.rs => action/keyboard.rs} (90%) create mode 100644 isototest/src/action/mod.rs rename isototest/src/{ => action}/view.rs (99%) diff --git a/isototest/src/action.rs b/isototest/src/action/keyboard.rs similarity index 90% rename from isototest/src/action.rs rename to isototest/src/action/keyboard.rs index 4a8c468..75085bd 100644 --- a/isototest/src/action.rs +++ b/isototest/src/action/keyboard.rs @@ -1,8 +1,13 @@ // SPDX-FileCopyrightText: Christopher Hock // SPDX-LicenseIdentifier: GPL-2.0-or-later -//! Action +//! # Keyboard Module //! -//! This module handles interactions between the VncClient and VncServer. +//! This module handles text-based interactions between the VncClient and VncServer. +//! +//! It uses [`X11Event::KeyEvent`](https://docs.rs/vnc-rs/0.5.1/vnc/event/struct.ClientKeyEvent.html) to send +//! individual key press or release events to the VNC server. +//! +//! To view what characters and control sequences are currently supported, see [`crate::types`]. extern crate proc_macro; use std::{thread::sleep, time::Duration}; @@ -25,7 +30,7 @@ macro_rules! wait_for_frame { }; } -/// Write given text to console +/// Send given text to VNC server. /// /// Uses `X11Event`s to send keypresses to the server. According to the [RFC](https://www.rfc-editor.org/rfc/rfc6143.html#section-7.5.4) /// it does not matter whether the X-Window System is running or not. @@ -34,6 +39,8 @@ macro_rules! wait_for_frame { /// /// * client: `&VncClient` - The client to be used for connections /// * text: `String` - The text to write. +/// * framerate: `Option` - The framerate of the remote machine. Used to time intervals in +/// which key signals are sent. If `None`, signal intervals are calculated according to a default. (30FPS) /// /// # Returns /// @@ -70,7 +77,7 @@ pub async fn write_to_console( /// Encapsulate the `client.input()` function calls to avoid repitition. /// -/// Press and release a button or release it manually, if it is pressed. +/// Will put the given key into a state according to the [crate::types::KeyEventType] parameter. /// /// # Parameters /// @@ -186,7 +193,10 @@ fn framerate_to_nanos(rate: Option) -> Result { } } -/// Assign a given character its corresponding `VirtualKeyCode`. +/// Assign a given character its corresponding [`crate::types::KeyCode`]. +/// +/// Will return the u32 representation of the actualkeycode as this is required by +/// [`vnc-rs`](https://docs.rs/vnc-rs/0.5.1/vnc/event/struct.ClientKeyEvent.html) /// /// # Parameters /// diff --git a/isototest/src/action/mod.rs b/isototest/src/action/mod.rs new file mode 100644 index 0000000..e856867 --- /dev/null +++ b/isototest/src/action/mod.rs @@ -0,0 +1,3 @@ +//! This module is used to interact with the VNC server in any capacity. +pub mod keyboard; +pub mod view; diff --git a/isototest/src/view.rs b/isototest/src/action/view.rs similarity index 99% rename from isototest/src/view.rs rename to isototest/src/action/view.rs index d85aabf..05060ea 100644 --- a/isototest/src/view.rs +++ b/isototest/src/action/view.rs @@ -1,3 +1,4 @@ +//! # View module use image::{GenericImage, ImageFormat, Rgba}; use std::{ path::Path, diff --git a/isototest/src/connection.rs b/isototest/src/connection.rs index b893cd7..566b022 100644 --- a/isototest/src/connection.rs +++ b/isototest/src/connection.rs @@ -1,8 +1,6 @@ // SPDX-FileCopyrightTest: Christopher Hock // SPDX-License-Identifier: GPL-2.0-or-later -//! # Connection Module -//! //! This module handles the VncClient and its connection to the VncServer. use tokio::{self, net::TcpStream}; use vnc::{PixelFormat, VncClient, VncConnector, VncError}; @@ -64,7 +62,7 @@ pub async fn create_vnc_client( Ok(vnc) } -/// Stop VNC engine, release all resources +/// Stop VNC engine, release all resources. /// /// # Parameters /// diff --git a/isototest/src/lib.rs b/isototest/src/lib.rs index 7bd5dad..8e4e83c 100644 --- a/isototest/src/lib.rs +++ b/isototest/src/lib.rs @@ -1,4 +1,71 @@ +//! Schedule and run tests for [openQA](https://open.qa). +//! +//! This crate's only responsibility is to schedule and run tests for the openQA project. +//! To this end it connects to the test environment on a remote worker machine (VM or bare metal) which has been prepared +//! by its two "sister-libraries" `isotoenv` and `ìsotomachine` via VNC and executes commands +//! specified by the openQA test to run. +//! +//! ## Example +//! +//! To use this crate, you need to create a `VncClient` instance, which will connect you to your +//! VNC server. This instance must be passed to any function which communicated with the VNC +//! server. +//! +//! ```no_run +//! use isototest::connection::{create_vnc_client, kill_client}; +//! use isototest::action::keyboard::write_to_console; +//! use isototest::action::view::read_screen; +//! use tokio::{self}; +//! use std::process::exit; +//! use std::time::Duration; +//! +//! #[tokio::main] +//! async fn main() -> Result<(), Box> { +//! let addr = "127.0.0.1:5900"; +//! let psw = "password".to_string(); // Value irrelevant if the server does not use authentication. +//! let mut client = match create_vnc_client(addr.to_string(), Some(psw.clone())).await { +//! Ok(client) => { +//! println!("Client created. Handshake successful."); +//! client +//! }, +//! Err(e) => { +//! eprintln!("[Error] {:?}", e); +//! exit(1) +//! } +//! }; +//! +//! // Request screenshot from the remote machine, save the resolution as the client can not +//! // request it again as long as it does not change. +//! let res; +//! let mut resolution = match read_screen(&client, "screenshot.png", None, Duration::from_secs(1)).await { +//! Ok(x) => { +//! println!("Screenshot received!"); +//! res = x; +//! } +//! Err(e) => { +//! eprintln!("{}", e); +//! exit(1); +//! } +//! }; +//! +//! // Send a series of keypresses to the VNC server to type out the given text. +//! // Can be used to execute commands on the Terminal. +//! match write_to_console(&client, "Hello World!\n".to_string(), None).await { +//! Ok(_) => { +//! println!("Test text sent!"); +//! } +//! Err(e) => { +//! eprintln!("[error] {:?}", e); +//! exit(1); +//! } +//! } +//! +//! // Kill VNC connection and release resources. +//! kill_client(client).await?; +//! Ok(()) +//! } +//! ``` + pub mod action; pub mod connection; -mod types; -pub mod view; +pub(crate) mod types; diff --git a/isototest/src/types.rs b/isototest/src/types.rs index 31a66a2..cab3bce 100644 --- a/isototest/src/types.rs +++ b/isototest/src/types.rs @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: Christopher Hock // SPDX-LicenseIdentifier: GPL-2.0-or-later +//! Common types for `isototest`. + /// Type of key press. /// /// # Members @@ -8,7 +10,7 @@ /// * `Press` - To signal a press and hold of the given key. /// * `Release` - To signal the release of a given key. /// * `Tap` - To signal a tap (press & release) of the given key. -pub enum KeyEventType { +pub(crate) enum KeyEventType { Press, Release, Tap, @@ -19,7 +21,7 @@ pub enum KeyEventType { /// /// Oriented on [this table](https://theasciicode.com.ar/ascii-printable-characters/exclamation-mark-ascii-code-33.html) /// Hex reprentations taken from [here](https://www.rfc-editor.org/rfc/rfc6143.html#section-7.5.4). -pub enum KeyCode { +pub(crate) enum KeyCode { NULL = 00, SOH = 01, STX = 02, From 0890235cd62de172e52e7676fd84f64d5f072aec Mon Sep 17 00:00:00 2001 From: ByteOtter Date: Tue, 6 Aug 2024 17:15:49 +0200 Subject: [PATCH 08/25] Add logging feature * Add status logging to functions * Add default logger configuration behind an optional feature --- isototest/Cargo.toml | 6 ++++++ isototest/src/action/keyboard.rs | 4 ++++ isototest/src/action/view.rs | 18 +++++++++++----- isototest/src/connection.rs | 37 ++++++++++++++++++++++++++------ isototest/src/lib.rs | 11 ++++++++++ isototest/src/logging.rs | 26 ++++++++++++++++++++++ 6 files changed, 90 insertions(+), 12 deletions(-) create mode 100644 isototest/src/logging.rs diff --git a/isototest/Cargo.toml b/isototest/Cargo.toml index b2e4b7d..d81075e 100644 --- a/isototest/Cargo.toml +++ b/isototest/Cargo.toml @@ -9,8 +9,14 @@ license = "GPL-2.0" [dependencies] image = "0.25.2" +log = "0.4.22" tokio = "1.38.1" vnc-rs = "0.5.1" +env_logger = { version= "0.10", optional=true } [dev-dependencies] mockito = "1.4.0" + +[features] +# Feature to enable default logging configuration +default-logging = ["env_logger"] diff --git a/isototest/src/action/keyboard.rs b/isototest/src/action/keyboard.rs index 75085bd..b5aa00a 100644 --- a/isototest/src/action/keyboard.rs +++ b/isototest/src/action/keyboard.rs @@ -11,8 +11,10 @@ extern crate proc_macro; use std::{thread::sleep, time::Duration}; +use log::info; use vnc::{client::VncClient, ClientKeyEvent, VncError, X11Event}; +use crate::logging::LOG_TARGET; use crate::types::{KeyCode, KeyEventType}; /// Sleep. @@ -52,6 +54,7 @@ pub async fn write_to_console( framerate: Option, ) -> Result<(), VncError> { // Translate each character to a keycode + info!(target: LOG_TARGET, "Sending text '{}' with intervall of {}FPS....", text, framerate.unwrap_or(30 as f64)); let mut keycode: u32; for ch in text.chars() { @@ -72,6 +75,7 @@ pub async fn write_to_console( press_button(client, modifier, KeyEventType::Release, framerate).await?; } } + info!(target: LOG_TARGET, "Text '{}' sent.", text); Ok(()) } diff --git a/isototest/src/action/view.rs b/isototest/src/action/view.rs index 05060ea..01aab50 100644 --- a/isototest/src/action/view.rs +++ b/isototest/src/action/view.rs @@ -10,6 +10,10 @@ use image::ImageBuffer; use image::DynamicImage::ImageRgba8; use vnc::{Rect, VncClient, VncError, VncEvent, X11Event}; +use log::{error, info, warn}; + +use crate::logging::LOG_TARGET; + /// Receive a screenshot of the remote machine. /// /// # Parameters @@ -36,6 +40,7 @@ pub async fn read_screen( resolution: Option<(u32, u32)>, timeout: Duration, ) -> Result<(u32, u32), VncError> { + info!(target: LOG_TARGET, "Requesting screenshot..."); // Request screen update. client.input(X11Event::Refresh).await?; @@ -47,21 +52,23 @@ pub async fn read_screen( // **This will cause issues, if you try to use this functionality a second time.** match resolution { Some((x, y)) => { + info!(target: LOG_TARGET, "Resolution provided; proceeding..."); width = Some(x); height = Some(y); } None => match client.recv_event().await? { VncEvent::SetResolution(screen) => { - println!("Screen resolution: {}x{}", screen.width, screen.height); + info!(target: LOG_TARGET, "Resolution received. Screen resolution: {}x{}", screen.width, screen.height); width = Some(screen.width as u32); height = Some(screen.height as u32); client.input(X11Event::Refresh).await?; } _ => { + error!(target: LOG_TARGET, "Failed to retrieve screen resolution. Aborting..."); return Err(VncError::General( "[error] No resolution found!".to_string(), - )) + )); } }, } @@ -88,8 +95,8 @@ pub async fn read_screen( return Err(VncError::General(e)); } x => { - println!( - "[warning] Function 'read_screen' got unexpected event '{:?}'.", + warn!(target: LOG_TARGET, + "Function 'read_screen' got unexpected event '{:?}'.", x ); break; @@ -97,6 +104,7 @@ pub async fn read_screen( }, None => { if idle_timer.elapsed() >= timeout { + warn!(target: LOG_TARGET, "Timeout while waiting for VNC Event."); break; } } @@ -135,6 +143,6 @@ pub async fn read_screen( .save_with_format(path, ImageFormat::Png) .unwrap(); - println!("Screenshot saved to {}", file_path); + info!(target: LOG_TARGET, "Screenshot saved to '{}'", file_path); Ok((width.unwrap(), height.unwrap())) } diff --git a/isototest/src/connection.rs b/isototest/src/connection.rs index 566b022..0e67d3b 100644 --- a/isototest/src/connection.rs +++ b/isototest/src/connection.rs @@ -2,9 +2,12 @@ // SPDX-License-Identifier: GPL-2.0-or-later //! This module handles the VncClient and its connection to the VncServer. +use log::{debug, error, info}; use tokio::{self, net::TcpStream}; use vnc::{PixelFormat, VncClient, VncConnector, VncError}; +use crate::logging::LOG_TARGET; + /// Create a new VNC client. /// /// During the connection process the connection to the VNC server is @@ -29,19 +32,23 @@ pub async fn create_vnc_client( target_ip: String, mut psw: Option, ) -> Result { + info!(target: LOG_TARGET, "Creating VNC client for target IP: '{}'", target_ip); + if psw.is_none() { + debug!("No password provided; using empty password."); psw = Some(String::new()); } let tcp: TcpStream = match TcpStream::connect(target_ip).await { Ok(tcp) => tcp, Err(e) => { + error!(target: LOG_TARGET, "Failed to connect: {}", e); let err = VncError::IoError(e); return Err(err); } }; - let vnc: VncClient = VncConnector::new(tcp) + let vnc: VncClient = match VncConnector::new(tcp) .set_auth_method(async move { Ok(psw.unwrap()) }) .add_encoding(vnc::VncEncoding::Tight) .add_encoding(vnc::VncEncoding::Zrle) @@ -54,10 +61,19 @@ pub async fn create_vnc_client( // NOTE: If the color encoding is changed in the following line, you must also change it in // view.rs to avoid the saved screenshots from having swapped colors. .set_pixel_format(PixelFormat::rgba()) - .build()? - .try_start() - .await? - .finish()?; + .build() + { + Ok(vnc) => vnc, + Err(e) => { + error!(target: LOG_TARGET, "Failed to build VNC client: {}", e); + return Err(e); + } + } + .try_start() + .await? + .finish()?; + + info!("VNC Client successfully built and started."); Ok(vnc) } @@ -74,10 +90,17 @@ pub async fn create_vnc_client( /// * `Err(VncError)` - Escalates the `VncError` upwards, if the `.close()` function of `vnc-rs` /// returns an error. pub async fn kill_client(client: VncClient) -> Result<(), VncError> { + info!(target: LOG_TARGET, "Closing connection..."); match client.close().await { - Ok(_) => {} - Err(e) => return Err(e), + Ok(_) => { + info!(target: LOG_TARGET, "Connection closed."); + } + Err(e) => { + error!(target: LOG_TARGET, "Unable to close connection: {}", e); + return Err(e); + } }; drop(client); + info!(target: LOG_TARGET, "Client dropped."); Ok(()) } diff --git a/isototest/src/lib.rs b/isototest/src/lib.rs index 8e4e83c..e13e040 100644 --- a/isototest/src/lib.rs +++ b/isototest/src/lib.rs @@ -65,7 +65,18 @@ //! Ok(()) //! } //! ``` +//! +//! ## Optional Features +//! +//! * `default-logging` - Provides you with a sensible logger configuration using the `env_logger` +//! crate. pub mod action; pub mod connection; +pub mod logging; pub(crate) mod types; + +#[cfg(feature = "default-logging")] +pub fn init_logging() { + logging::initialize_default_logging(); +} diff --git a/isototest/src/logging.rs b/isototest/src/logging.rs new file mode 100644 index 0000000..8b161e4 --- /dev/null +++ b/isototest/src/logging.rs @@ -0,0 +1,26 @@ +//! This module provides a sensible default configuration of a logging system. + +#[cfg(feature = "default-logging")] +use env_logger::Builder; +#[cfg(feature = "default-logging")] +use std::io::Write; + +pub const LOG_TARGET: &str = "[isototest]"; + +#[cfg(feature = "default-logging")] +/// Initialize default logging configuration. +pub fn initialize_default_logging() { + Builder::new() + .filter_level(log::LevelFilter::Info) + .format(|bug, record| { + writeln!( + buf, + "{} [{}] {}: {}", + buf.timestamp, + record.level(), + record.target(), + record.args() + ) + }) + .init(); +} From 1226e6b344da857a457ba5dfdd56b32dc8f9f731 Mon Sep 17 00:00:00 2001 From: ByteOtter Date: Tue, 6 Aug 2024 18:31:18 +0200 Subject: [PATCH 09/25] Fix small typo in logging.rs --- isototest/src/action/view.rs | 4 ++-- isototest/src/logging.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/isototest/src/action/view.rs b/isototest/src/action/view.rs index 01aab50..edeaa99 100644 --- a/isototest/src/action/view.rs +++ b/isototest/src/action/view.rs @@ -81,7 +81,7 @@ pub async fn read_screen( match client.poll_event().await? { Some(x) => match x { VncEvent::SetResolution(screen) => { - println!("Screen resolution: {}x{}", screen.width, screen.height); + info!(target: LOG_TARGET, "Screen resolution: {}x{}", screen.width, screen.height); width = Some(screen.width as u32); height = Some(screen.height as u32); @@ -91,7 +91,7 @@ pub async fn read_screen( img_parts.push((rect, data)); } VncEvent::Error(e) => { - eprintln!("[error] {}", e); + error!(target: LOG_TARGET, "Error event received: {}", e); return Err(VncError::General(e)); } x => { diff --git a/isototest/src/logging.rs b/isototest/src/logging.rs index 8b161e4..72af562 100644 --- a/isototest/src/logging.rs +++ b/isototest/src/logging.rs @@ -12,11 +12,11 @@ pub const LOG_TARGET: &str = "[isototest]"; pub fn initialize_default_logging() { Builder::new() .filter_level(log::LevelFilter::Info) - .format(|bug, record| { + .format(|buf, record| { writeln!( buf, "{} [{}] {}: {}", - buf.timestamp, + buf.timestamp(), record.level(), record.target(), record.args() From cc5dc0be6692cb8d93a85e992f728492ae6b7f5d Mon Sep 17 00:00:00 2001 From: ByteOtter Date: Wed, 7 Aug 2024 11:09:47 +0200 Subject: [PATCH 10/25] Update .gitignore with IDE configs --- .gitignore | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index ae12eb9..106ff17 100644 --- a/.gitignore +++ b/.gitignore @@ -13,10 +13,13 @@ Cargo.lock # MSVC Windows builds of rustc generate these, which store debugging information *.pdb - # Added by cargo - /target # Local test binary vnc-test/ + +# Editor Configs +.idea/ +.vscode/ +.lvim-config.lua From 48c100408ffa36dd4979f1c0b4b6dc617bb5f5e6 Mon Sep 17 00:00:00 2001 From: ByteOtter Date: Wed, 7 Aug 2024 16:03:52 +0200 Subject: [PATCH 11/25] Fix labeler workflow --- .github/labeler.yml | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/.github/labeler.yml b/.github/labeler.yml index d306538..b0d63c9 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -1,12 +1,22 @@ -rust: -- **/**/*.rs - dependencies: - Cargo.toml -- **/Cargo.toml -- **/Cargo.lock +- isototest/Cargo.toml +- isototest/Cargo.lock +- isotoenv/Cargo.toml +- isotoenv/Cargo.lock +- isotomachine/Cargo.toml +- isotomachine/Cargo.lock - Cargo.lock +isototest: +- isototest/* + +isotomachine: +- isotomachine/* + +isotoenv: +- isotoenv/* + documentation: - docs/** - README.md From f75ed3aa91e2550dbecc3d0b084447e6a75e0585 Mon Sep 17 00:00:00 2001 From: ByteOtter Date: Wed, 7 Aug 2024 15:51:46 +0200 Subject: [PATCH 12/25] Add composing of images * Layer new image data (delta from previous image) onto a copy of the previous image --- isototest/Cargo.toml | 1 + isototest/src/action/view.rs | 120 +++++++++++++++++++++++++++++++---- isototest/src/lib.rs | 15 ----- 3 files changed, 108 insertions(+), 28 deletions(-) diff --git a/isototest/Cargo.toml b/isototest/Cargo.toml index d81075e..637da3c 100644 --- a/isototest/Cargo.toml +++ b/isototest/Cargo.toml @@ -13,6 +13,7 @@ log = "0.4.22" tokio = "1.38.1" vnc-rs = "0.5.1" env_logger = { version= "0.10", optional=true } +chrono = "0.4.38" [dev-dependencies] mockito = "1.4.0" diff --git a/isototest/src/action/view.rs b/isototest/src/action/view.rs index edeaa99..f0f7084 100644 --- a/isototest/src/action/view.rs +++ b/isototest/src/action/view.rs @@ -1,13 +1,14 @@ //! # View module -use image::{GenericImage, ImageFormat, Rgba}; +//! +//! This module handles everything related to requesting visual data from the VNC server. +use chrono::Utc; +use image::ImageBuffer; +use image::{DynamicImage, GenericImage, GenericImageView, ImageFormat, Rgba}; use std::{ + env, path::Path, time::{Duration, Instant}, }; - -use image::ImageBuffer; - -use image::DynamicImage::ImageRgba8; use vnc::{Rect, VncClient, VncError, VncEvent, X11Event}; use log::{error, info, warn}; @@ -36,7 +37,7 @@ use crate::logging::LOG_TARGET; /// * `Err(VncError)` - Variation of `VncError` if something goes wrong. pub async fn read_screen( client: &VncClient, - file_path: &str, + file_path: Option<&Path>, resolution: Option<(u32, u32)>, timeout: Duration, ) -> Result<(u32, u32), VncError> { @@ -73,7 +74,6 @@ pub async fn read_screen( }, } - let path: &Path = Path::new(file_path); let idle_timer: Instant = Instant::now(); loop { @@ -137,12 +137,106 @@ pub async fn read_screen( } } - // Save image to file system in PNG format. - // NOTE: If the image color encoding is changed here, you must also change it in connection.rs! - ImageRgba8(image) - .save_with_format(path, ImageFormat::Png) - .unwrap(); + let mut prefix; + match file_path { + Some(x) => { + prefix = x.to_owned(); + } + None => { + let dir = env::current_dir()?; + prefix = dir.to_owned(); + } + } - info!(target: LOG_TARGET, "Screenshot saved to '{}'", file_path); + let last_modified_file = std::fs::read_dir(&prefix) + .expect("Couldn't access local directory") + .flatten() // Remove failed + .filter(|f| f.metadata().unwrap().is_file()) // Filter out directories (only consider files) + .max_by_key(|x| x.metadata().unwrap().modified().unwrap()); // Get the most recently modified file + + prefix.push(format!("frame_{}.png", Utc::now())); + + match last_modified_file { + Some(x) => { + let prev_image = image::open(x.path()).unwrap(); + // Layer the image data on top of the previous image. + let composed_image = compose_image(&prev_image, &DynamicImage::ImageRgba8(image)); + // image = prev_image.to_rgba8() + composed_image + .save_with_format(&prefix, ImageFormat::Png) + .unwrap(); + } + None => { + // Save image to file system in PNG format. + // NOTE: If the image color encoding is changed here, you must also change it in connection.rs! + DynamicImage::ImageRgba8(image) + .save_with_format(&prefix, ImageFormat::Png) + .unwrap(); + } + } + + info!(target: LOG_TARGET, "Screenshot saved to '{}'", prefix.to_str().unwrap()); Ok((width.unwrap(), height.unwrap())) } + +/// Compose new image data to the previous image and save copy. +/// +/// This is needed for subsequent calls of `read_screen` as the VNC server will only return the +/// last pixels changed since the previous request. +/// While this is handy for performance, it is no recommended for our use case as we need to have a +/// full picture of the screen to compare the current state of the test worker against expected +/// output. +/// +/// # Parameters +/// +/// * `base: &DynamicImage` - The image you want to lay the delta on top of. +/// * `overlay: &DynamicImage` - The new image data, which only includes this pixels that have +/// changed since the last screen request. +/// +/// # Returns +/// +/// * `DynamicImage` - New `DynamicImage` consisting of the already read parts of the screen +/// overlayed with the requested delta. +fn compose_image(prev_image: &DynamicImage, new: &DynamicImage) -> DynamicImage { + info!(target: LOG_TARGET, "Combining new pixel data with previous image."); + let (width, height) = (prev_image.width(), prev_image.height()); + let mut new_image = prev_image.to_rgba8(); + + for x in 0..width { + for y in 0..height { + let base_pixel = prev_image.get_pixel(x, y); + let overlay_pixel = new.get_pixel(x, y); + new_image.put_pixel(x, y, blend_pixels(base_pixel, overlay_pixel)); + } + } + DynamicImage::ImageRgba8(new_image) +} + +/// Blend two pixels together based on their alpha values (transparency). +/// +/// This function blends a pixel from the base image with a pixel from the overlay image. The +/// blending is done by considering the alpha (transparency) of the overlay pixel, which determines +/// how much of the overlay pixel should be visible over the base pixel. +/// +/// # Parameters +/// +/// * `base: Rgba` - The base pixel. +/// * `overlay: Rgba` - The pixel of the image you want to overlay. +/// +/// # Returns +/// +/// * `Rgba` - The pixel's new alpha value. +fn blend_pixels(base: Rgba, overlay: Rgba) -> Rgba { + let alpha_overlay = overlay[3] as f32 / 255.0; + + let func = |b, o| -> u8 { + (((b as f32 * (1.0 - alpha_overlay)) + (o as f32 * alpha_overlay)) * 255.0) as u8 + }; + + Rgba([ + func(base[0], overlay[0]), + func(base[1], overlay[1]), + func(base[2], overlay[2]), + 255 as u8, + ]) +} diff --git a/isototest/src/lib.rs b/isototest/src/lib.rs index e13e040..c32004d 100644 --- a/isototest/src/lib.rs +++ b/isototest/src/lib.rs @@ -17,7 +17,6 @@ //! use isototest::action::view::read_screen; //! use tokio::{self}; //! use std::process::exit; -//! use std::time::Duration; //! //! #[tokio::main] //! async fn main() -> Result<(), Box> { @@ -34,20 +33,6 @@ //! } //! }; //! -//! // Request screenshot from the remote machine, save the resolution as the client can not -//! // request it again as long as it does not change. -//! let res; -//! let mut resolution = match read_screen(&client, "screenshot.png", None, Duration::from_secs(1)).await { -//! Ok(x) => { -//! println!("Screenshot received!"); -//! res = x; -//! } -//! Err(e) => { -//! eprintln!("{}", e); -//! exit(1); -//! } -//! }; -//! //! // Send a series of keypresses to the VNC server to type out the given text. //! // Can be used to execute commands on the Terminal. //! match write_to_console(&client, "Hello World!\n".to_string(), None).await { From df415aa3ed2715fff53c109a99406f36440de90e Mon Sep 17 00:00:00 2001 From: ByteOtter Date: Thu, 8 Aug 2024 16:32:55 +0200 Subject: [PATCH 13/25] Update documentation in view module --- isototest/src/action/view.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/isototest/src/action/view.rs b/isototest/src/action/view.rs index f0f7084..8f9ddf8 100644 --- a/isototest/src/action/view.rs +++ b/isototest/src/action/view.rs @@ -20,7 +20,8 @@ use crate::logging::LOG_TARGET; /// # Parameters /// /// * client: `&VncClient` - The client instance used for connection. -/// * file_path: `&str` - A file path you want to save your screenshot under as a `str`. +/// * file_path: `Option<&Path>` - A file path you want to save your screenshot under as a `&Path`. +/// (If `None` -> `CWD` is set as output dir.) /// * resolution: `Option` - The resolution of the VNC session. /// * timeout: `Duration` - The `Duration` this function should wait for a `VncEvent` before it /// continues. From 86cb73b80066d8ffbd4a3158a6f54225983bac96 Mon Sep 17 00:00:00 2001 From: ByteOtter Date: Fri, 9 Aug 2024 11:20:21 +0200 Subject: [PATCH 14/25] Add explicit types --- isototest/src/action/view.rs | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/isototest/src/action/view.rs b/isototest/src/action/view.rs index 8f9ddf8..55e0c51 100644 --- a/isototest/src/action/view.rs +++ b/isototest/src/action/view.rs @@ -2,8 +2,9 @@ //! //! This module handles everything related to requesting visual data from the VNC server. use chrono::Utc; -use image::ImageBuffer; use image::{DynamicImage, GenericImage, GenericImageView, ImageFormat, Rgba}; +use image::{ImageBuffer, RgbaImage}; +use std::path::PathBuf; use std::{ env, path::Path, @@ -138,7 +139,7 @@ pub async fn read_screen( } } - let mut prefix; + let mut prefix: PathBuf; match file_path { Some(x) => { prefix = x.to_owned(); @@ -149,7 +150,7 @@ pub async fn read_screen( } } - let last_modified_file = std::fs::read_dir(&prefix) + let last_modified_file: Option = std::fs::read_dir(&prefix) .expect("Couldn't access local directory") .flatten() // Remove failed .filter(|f| f.metadata().unwrap().is_file()) // Filter out directories (only consider files) @@ -159,9 +160,10 @@ pub async fn read_screen( match last_modified_file { Some(x) => { - let prev_image = image::open(x.path()).unwrap(); + let prev_image: DynamicImage = image::open(x.path()).unwrap(); // Layer the image data on top of the previous image. - let composed_image = compose_image(&prev_image, &DynamicImage::ImageRgba8(image)); + let composed_image: DynamicImage = + compose_image(&prev_image, &DynamicImage::ImageRgba8(image)); // image = prev_image.to_rgba8() composed_image .save_with_format(&prefix, ImageFormat::Png) @@ -200,13 +202,13 @@ pub async fn read_screen( /// overlayed with the requested delta. fn compose_image(prev_image: &DynamicImage, new: &DynamicImage) -> DynamicImage { info!(target: LOG_TARGET, "Combining new pixel data with previous image."); - let (width, height) = (prev_image.width(), prev_image.height()); - let mut new_image = prev_image.to_rgba8(); + let (width, height): (u32, u32) = (prev_image.width(), prev_image.height()); + let mut new_image: RgbaImage = prev_image.to_rgba8(); for x in 0..width { for y in 0..height { - let base_pixel = prev_image.get_pixel(x, y); - let overlay_pixel = new.get_pixel(x, y); + let base_pixel: Rgba = prev_image.get_pixel(x, y); + let overlay_pixel: Rgba = new.get_pixel(x, y); new_image.put_pixel(x, y, blend_pixels(base_pixel, overlay_pixel)); } } @@ -228,7 +230,7 @@ fn compose_image(prev_image: &DynamicImage, new: &DynamicImage) -> DynamicImage /// /// * `Rgba` - The pixel's new alpha value. fn blend_pixels(base: Rgba, overlay: Rgba) -> Rgba { - let alpha_overlay = overlay[3] as f32 / 255.0; + let alpha_overlay: f32 = overlay[3] as f32 / 255.0; let func = |b, o| -> u8 { (((b as f32 * (1.0 - alpha_overlay)) + (o as f32 * alpha_overlay)) * 255.0) as u8 From d1f483faa60934f63519ce9fc5c06d0eafbe2c58 Mon Sep 17 00:00:00 2001 From: ByteOtter Date: Fri, 9 Aug 2024 14:18:52 +0200 Subject: [PATCH 15/25] Add editorconfig --- .editorconfig | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 .editorconfig diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..7d03613 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,26 @@ +root = true + +[*] +indent_style = space +indent_size = 4 +insert_final_newline = true +trim_trailing_whitespace = true + +[*.rs] +charset = utf-8 +max_line_length = 120 + +[*.toml] +indent_style = space +indent_size = 2 + +[*.yml] +indent_style = space +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false + +[*.sh] +indent_style = space +indent_size = 4 From 747ee379758cb7d1843f3e90b1a7d54a9b50ddec Mon Sep 17 00:00:00 2001 From: Christopher Hock Date: Fri, 9 Aug 2024 14:28:46 +0200 Subject: [PATCH 16/25] Update SECURITY.md Signed-off-by: Christopher Hock --- docs/SECURITY.md | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 2891627..b35d08a 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -3,7 +3,7 @@ ## Reporting a Vulnerability If you discover a security vulnerability in this project, please report it by emailing the -[project owner](mailto:christopher-hock@protonmail.com). Please provide detailed information about the vulnerability, +[project owner](mailto:christopher-hock@suse.com). Please provide detailed information about the vulnerability, including steps to reproduce, possible ways of exploitation and any relevant details about your environment. We appreciate responsible disclosure. @@ -22,8 +22,3 @@ dependencies which you may be planning to introduce to the project beforehand to This security policy is subject to change. It is the responsibility of all project contributors and users to stay updated on any modifications. By participating in this project, you agree to abide by this security policy. - -Nazara is designed to run only within your local network. The user is responsible for their network setup -themselves. - -We are not liable for any damages that are caused by insufficient network security. From 93a1beee71b2a2c83a46f8d9983ef2729dc99295 Mon Sep 17 00:00:00 2001 From: ByteOtter Date: Mon, 12 Aug 2024 11:54:16 +0200 Subject: [PATCH 17/25] Update logging functionality with optional debug and trace log levels --- isototest/src/errors/mod.rs | 3 ++ isototest/src/errors/util_errors.rs | 20 ++++++++++++ isototest/src/lib.rs | 31 +++++++++++++++++-- isototest/src/logging.rs | 48 ++++++++++++++++++++++++++++- 4 files changed, 98 insertions(+), 4 deletions(-) create mode 100644 isototest/src/errors/mod.rs create mode 100644 isototest/src/errors/util_errors.rs diff --git a/isototest/src/errors/mod.rs b/isototest/src/errors/mod.rs new file mode 100644 index 0000000..ad22c76 --- /dev/null +++ b/isototest/src/errors/mod.rs @@ -0,0 +1,3 @@ +//! This module defines custom error types to be returned by `isototest`. +//! These types are thematically split into submodules. +pub mod util_errors; diff --git a/isototest/src/errors/util_errors.rs b/isototest/src/errors/util_errors.rs new file mode 100644 index 0000000..5f6ec3d --- /dev/null +++ b/isototest/src/errors/util_errors.rs @@ -0,0 +1,20 @@ +//! This module defines and implements error type which refer to the supporting util of this library. +//! This means functionality like logging and similar supporting functionality, which do not necessarily +//! impact the core functionality of this library itself. +use std::fmt; + +#[derive(Debug)] +#[cfg(feature = "default-logging")] +/// Error used for checking given log level. +/// Only available as part of the `default-logging` feature. +pub struct InvalidLogLevelError(pub String); + +#[cfg(feature = "default-logging")] +impl fmt::Display for InvalidLogLevelError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "[error] Invalid log level: '{}'", self.0) + } +} + +#[cfg(feature = "default-logging")] +impl std::error::Error for InvalidLogLevelError {} diff --git a/isototest/src/lib.rs b/isototest/src/lib.rs index c32004d..6f073c1 100644 --- a/isototest/src/lib.rs +++ b/isototest/src/lib.rs @@ -11,7 +11,7 @@ //! VNC server. This instance must be passed to any function which communicated with the VNC //! server. //! -//! ```no_run +//! ``` no_run //! use isototest::connection::{create_vnc_client, kill_client}; //! use isototest::action::keyboard::write_to_console; //! use isototest::action::view::read_screen; @@ -56,12 +56,37 @@ //! * `default-logging` - Provides you with a sensible logger configuration using the `env_logger` //! crate. +// Organize library structure. pub mod action; pub mod connection; +pub mod errors; pub mod logging; pub(crate) mod types; +// Provide code on the root level of the library +use crate::logging::LOG_TARGET; +use log::{debug, trace}; + #[cfg(feature = "default-logging")] -pub fn init_logging() { - logging::initialize_default_logging(); +pub fn init_logging(level: Option<&str>) -> Result<(), errors::util_errors::InvalidLogLevelError> { + match level { + Some("debug") => { + logging::init_debug_logging(); + debug!(target: LOG_TARGET, "Logging initialized. Running with 'debug' log level."); + Ok(()) + } + Some("trace") => { + logging::init_trace(); + trace!(target: LOG_TARGET, "Logging initialized. Running with 'trace' log level."); + Ok(()) + } + None => { + logging::init_default_logging(); + Ok(()) + } + Some(invalid) => Err(errors::util_errors::InvalidLogLevelError(format!( + "[error] Invalid log level defined: '{}'", + invalid + ))), + } } diff --git a/isototest/src/logging.rs b/isototest/src/logging.rs index 72af562..7300cc0 100644 --- a/isototest/src/logging.rs +++ b/isototest/src/logging.rs @@ -9,7 +9,9 @@ pub const LOG_TARGET: &str = "[isototest]"; #[cfg(feature = "default-logging")] /// Initialize default logging configuration. -pub fn initialize_default_logging() { +/// +/// By default, we will only log `info` leves and higher. +pub fn init_default_logging() { Builder::new() .filter_level(log::LevelFilter::Info) .format(|buf, record| { @@ -24,3 +26,47 @@ pub fn initialize_default_logging() { }) .init(); } + +#[cfg(feature = "default-logging")] +/// Initialize debug logging. +/// +/// Will log every event with the `debug` log level and higher. +/// +/// **Should only be used for development purposes.** +pub fn init_debug_logging() { + Builder::new() + .filter_level(log::LevelFilter::Debug) + .format(|buf, record| { + writeln!( + buf, + "{} [{}] {}: {}", + buf.timestamp(), + record.level(), + record.target(), + record.args() + ) + }) + .init(); +} + +#[cfg(feature = "default-logging")] +/// Initialize trace. +/// +/// Will log every event. +/// +/// **Should only be used for development purposes.** +pub fn init_trace() { + Builder::new() + .filter_level(log::LevelFilter::Trace) + .format(|buf, record| { + writeln!( + buf, + "{} [{}] {}: {}", + buf.timestamp(), + record.level(), + record.target(), + record.args() + ) + }) + .init(); +} From 87d9f92ffdc52e9cbe86d5c2b3c78d79cb13df1c Mon Sep 17 00:00:00 2001 From: ByteOtter Date: Mon, 12 Aug 2024 16:31:24 +0200 Subject: [PATCH 18/25] Hide log use statements behind feature flag --- isototest/src/lib.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/isototest/src/lib.rs b/isototest/src/lib.rs index 6f073c1..11924bb 100644 --- a/isototest/src/lib.rs +++ b/isototest/src/lib.rs @@ -64,7 +64,9 @@ pub mod logging; pub(crate) mod types; // Provide code on the root level of the library +#[cfg(feature = "default-logging")] use crate::logging::LOG_TARGET; +#[cfg(feature = "default-logging")] use log::{debug, trace}; #[cfg(feature = "default-logging")] From 644eea2a1bc436f4fe641de0fdbb9d0a85bff802 Mon Sep 17 00:00:00 2001 From: ByteOtter Date: Wed, 14 Aug 2024 11:04:35 +0200 Subject: [PATCH 19/25] Make use of enumerated error types for consolidated log level checking --- isototest/src/connection.rs | 2 +- isototest/src/errors/util_errors.rs | 20 +++++-- isototest/src/lib.rs | 28 ++-------- isototest/src/logging.rs | 86 ++++++++++++----------------- 4 files changed, 55 insertions(+), 81 deletions(-) diff --git a/isototest/src/connection.rs b/isototest/src/connection.rs index 0e67d3b..9de442a 100644 --- a/isototest/src/connection.rs +++ b/isototest/src/connection.rs @@ -57,7 +57,7 @@ pub async fn create_vnc_client( .add_encoding(vnc::VncEncoding::Trle) .add_encoding(vnc::VncEncoding::CursorPseudo) .add_encoding(vnc::VncEncoding::DesktopSizePseudo) - .allow_shared(true) + .allow_shared(true) // Allow for multiple other VNC sessions to be connected at once. // NOTE: If the color encoding is changed in the following line, you must also change it in // view.rs to avoid the saved screenshots from having swapped colors. .set_pixel_format(PixelFormat::rgba()) diff --git a/isototest/src/errors/util_errors.rs b/isototest/src/errors/util_errors.rs index 5f6ec3d..40ba78e 100644 --- a/isototest/src/errors/util_errors.rs +++ b/isototest/src/errors/util_errors.rs @@ -5,16 +5,24 @@ use std::fmt; #[derive(Debug)] #[cfg(feature = "default-logging")] -/// Error used for checking given log level. -/// Only available as part of the `default-logging` feature. -pub struct InvalidLogLevelError(pub String); +pub enum LoggingError { + LoggingInitError(String), + InvalidLogLevelError(String), +} #[cfg(feature = "default-logging")] -impl fmt::Display for InvalidLogLevelError { +impl fmt::Display for LoggingError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "[error] Invalid log level: '{}'", self.0) + match self { + LoggingError::LoggingInitError(msg) => { + write!(f, "[error] Logging initialization failed: '{}'", msg) + } + LoggingError::InvalidLogLevelError(msg) => { + write!(f, "[error] Invalid log level: '{}'", msg) + } + } } } #[cfg(feature = "default-logging")] -impl std::error::Error for InvalidLogLevelError {} +impl std::error::Error for LoggingError {} diff --git a/isototest/src/lib.rs b/isototest/src/lib.rs index 11924bb..5460173 100644 --- a/isototest/src/lib.rs +++ b/isototest/src/lib.rs @@ -65,30 +65,12 @@ pub(crate) mod types; // Provide code on the root level of the library #[cfg(feature = "default-logging")] -use crate::logging::LOG_TARGET; +use crate::logging::init_default_logging; #[cfg(feature = "default-logging")] -use log::{debug, trace}; +use crate::errors::util_errors::LoggingError; #[cfg(feature = "default-logging")] -pub fn init_logging(level: Option<&str>) -> Result<(), errors::util_errors::InvalidLogLevelError> { - match level { - Some("debug") => { - logging::init_debug_logging(); - debug!(target: LOG_TARGET, "Logging initialized. Running with 'debug' log level."); - Ok(()) - } - Some("trace") => { - logging::init_trace(); - trace!(target: LOG_TARGET, "Logging initialized. Running with 'trace' log level."); - Ok(()) - } - None => { - logging::init_default_logging(); - Ok(()) - } - Some(invalid) => Err(errors::util_errors::InvalidLogLevelError(format!( - "[error] Invalid log level defined: '{}'", - invalid - ))), - } +pub fn init_logging(level: Option<&str>) -> Result<(), LoggingError> { + init_default_logging(level)?; + Ok(()) } diff --git a/isototest/src/logging.rs b/isototest/src/logging.rs index 7300cc0..814f5ed 100644 --- a/isototest/src/logging.rs +++ b/isototest/src/logging.rs @@ -4,69 +4,53 @@ use env_logger::Builder; #[cfg(feature = "default-logging")] use std::io::Write; +#[cfg(feature = "default-logging")] +use crate::errors::util_errors::LoggingError; pub const LOG_TARGET: &str = "[isototest]"; #[cfg(feature = "default-logging")] -/// Initialize default logging configuration. -/// -/// By default, we will only log `info` leves and higher. -pub fn init_default_logging() { - Builder::new() - .filter_level(log::LevelFilter::Info) - .format(|buf, record| { - writeln!( - buf, - "{} [{}] {}: {}", - buf.timestamp(), - record.level(), - record.target(), - record.args() - ) - }) - .init(); -} - -#[cfg(feature = "default-logging")] -/// Initialize debug logging. +/// Initialize default logging configuration with given log level. /// -/// Will log every event with the `debug` log level and higher. +/// Log Level can be: +/// * "info" - Default log level also adapted if level is `none`. Logs events relevant for general usage. +/// * "debug" - Debug level for extended logging. Should only be used for development purposes. +/// * "trace" - Extensive log evel logging every event. Should only be used for development purposes. /// -/// **Should only be used for development purposes.** -pub fn init_debug_logging() { - Builder::new() - .filter_level(log::LevelFilter::Debug) - .format(|buf, record| { - writeln!( - buf, - "{} [{}] {}: {}", - buf.timestamp(), - record.level(), - record.target(), - record.args() - ) - }) - .init(); +pub(crate) fn init_default_logging(level: Option<&str>) -> Result<(), LoggingError> { + match level { + Some("info") | None => { + log_builder(log::LevelFilter::Info); + Ok(()) + }, + Some("debug") => { + log_builder(log::LevelFilter::Debug); + Ok(()) + }, + Some("trace") => { + log_builder(log::LevelFilter::Trace); + Ok(()) + }, + Some(invalid) => { + Err(LoggingError::InvalidLogLevelError(format!("Invalid log level '{}'!", invalid))) + } + } } #[cfg(feature = "default-logging")] -/// Initialize trace. -/// -/// Will log every event. -/// -/// **Should only be used for development purposes.** -pub fn init_trace() { +fn log_builder(level: log::LevelFilter) { Builder::new() - .filter_level(log::LevelFilter::Trace) + .filter_level(level) .format(|buf, record| { writeln!( - buf, - "{} [{}] {}: {}", - buf.timestamp(), - record.level(), - record.target(), - record.args() - ) + buf, + "{} [{}] {}: {}", + buf.timestamp(), + record.level(), + record.target(), + record.args() + ) }) .init(); } + From bbdd84f6446b1523ad76cdf8168c007b1513f60e Mon Sep 17 00:00:00 2001 From: ByteOtter Date: Wed, 14 Aug 2024 11:09:32 +0200 Subject: [PATCH 20/25] Update repository link in isototest/Cargo.toml --- isototest/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/isototest/Cargo.toml b/isototest/Cargo.toml index 637da3c..3b3c687 100644 --- a/isototest/Cargo.toml +++ b/isototest/Cargo.toml @@ -4,7 +4,7 @@ version = "0.1.0" edition = "2021" description = "A library for executing openQA test on workers" readme = "README.md" -repository = "https://github.com/ByteOtter/isotest-ng/tree/main/isototest" +repository = "https://github.com/os-autoinst/isotest-ng/tree/main/isototest" license = "GPL-2.0" [dependencies] From 3ee6f2bfbd356e6550bc260e58f4599f02dd794b Mon Sep 17 00:00:00 2001 From: ByteOtter Date: Wed, 14 Aug 2024 12:45:54 +0200 Subject: [PATCH 21/25] Fix unused import warning in isototest error module --- isototest/src/errors/util_errors.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/isototest/src/errors/util_errors.rs b/isototest/src/errors/util_errors.rs index 40ba78e..1e5d977 100644 --- a/isototest/src/errors/util_errors.rs +++ b/isototest/src/errors/util_errors.rs @@ -1,6 +1,7 @@ //! This module defines and implements error type which refer to the supporting util of this library. //! This means functionality like logging and similar supporting functionality, which do not necessarily //! impact the core functionality of this library itself. +#[cfg(feature = "default-logging")] // HACK: Until other error types implement fmt. use std::fmt; #[derive(Debug)] From 6e82bab80fa58f5faf460d80a1729d8ec60ff548 Mon Sep 17 00:00:00 2001 From: ByteOtter Date: Wed, 14 Aug 2024 12:46:42 +0200 Subject: [PATCH 22/25] Update obsolete dependency in isototest --- isototest/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/isototest/Cargo.toml b/isototest/Cargo.toml index 3b3c687..b9d21d7 100644 --- a/isototest/Cargo.toml +++ b/isototest/Cargo.toml @@ -12,7 +12,7 @@ image = "0.25.2" log = "0.4.22" tokio = "1.38.1" vnc-rs = "0.5.1" -env_logger = { version= "0.10", optional=true } +env_logger = { version= "0.11.5", optional=true } chrono = "0.4.38" [dev-dependencies] From e2c08aeab9d11bdde93b30acc33f339b68e50213 Mon Sep 17 00:00:00 2001 From: ByteOtter Date: Wed, 14 Aug 2024 12:46:58 +0200 Subject: [PATCH 23/25] Copy logging and error modules to isotomachine --- isotomachine/Cargo.toml | 6 ++- isotomachine/src/errors/mod.rs | 3 ++ isotomachine/src/errors/util_errors.rs | 28 +++++++++++++ isotomachine/src/lib.rs | 31 +++++++++----- isotomachine/src/logging.rs | 56 ++++++++++++++++++++++++++ 5 files changed, 112 insertions(+), 12 deletions(-) create mode 100644 isotomachine/src/errors/mod.rs create mode 100644 isotomachine/src/errors/util_errors.rs create mode 100644 isotomachine/src/logging.rs diff --git a/isotomachine/Cargo.toml b/isotomachine/Cargo.toml index 281dafe..b38dbec 100644 --- a/isotomachine/Cargo.toml +++ b/isotomachine/Cargo.toml @@ -8,4 +8,8 @@ repository = "https://github.com/ByteOtter/isotest-ng/tree/main/isotomachine" license = "GPL-2.0" [dependencies] -vnc-rs = "0.5.1" +env_logger = { version = "0.11.5", optional = true } +log = "0.4.22" + +[features] +default-logging = ["env_logger"] diff --git a/isotomachine/src/errors/mod.rs b/isotomachine/src/errors/mod.rs new file mode 100644 index 0000000..ad22c76 --- /dev/null +++ b/isotomachine/src/errors/mod.rs @@ -0,0 +1,3 @@ +//! This module defines custom error types to be returned by `isototest`. +//! These types are thematically split into submodules. +pub mod util_errors; diff --git a/isotomachine/src/errors/util_errors.rs b/isotomachine/src/errors/util_errors.rs new file mode 100644 index 0000000..40ba78e --- /dev/null +++ b/isotomachine/src/errors/util_errors.rs @@ -0,0 +1,28 @@ +//! This module defines and implements error type which refer to the supporting util of this library. +//! This means functionality like logging and similar supporting functionality, which do not necessarily +//! impact the core functionality of this library itself. +use std::fmt; + +#[derive(Debug)] +#[cfg(feature = "default-logging")] +pub enum LoggingError { + LoggingInitError(String), + InvalidLogLevelError(String), +} + +#[cfg(feature = "default-logging")] +impl fmt::Display for LoggingError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + LoggingError::LoggingInitError(msg) => { + write!(f, "[error] Logging initialization failed: '{}'", msg) + } + LoggingError::InvalidLogLevelError(msg) => { + write!(f, "[error] Invalid log level: '{}'", msg) + } + } + } +} + +#[cfg(feature = "default-logging")] +impl std::error::Error for LoggingError {} diff --git a/isotomachine/src/lib.rs b/isotomachine/src/lib.rs index 7d12d9a..f4b3491 100644 --- a/isotomachine/src/lib.rs +++ b/isotomachine/src/lib.rs @@ -1,14 +1,23 @@ -pub fn add(left: usize, right: usize) -> usize { - left + right -} +//! Prepare a [openQA](https://open.qa) test worker. +//! +//! This crate is responsible for setting up a `openQA` worker machine or VM. +//! +//! ## Optional Features +//! +//! * `default-logging` - Provides you with a sensible logger configuration using the `env_logger` crate. + +// Organize library structure +pub mod logging; +pub mod errors; -#[cfg(test)] -mod tests { - use super::*; +// Provide code on the root level of the library +#[cfg(feature = "default-logging")] +use crate::logging::init_default_logging; +#[cfg(feature = "default-logging")] +use crate::errors::util_errors::LoggingError; - #[test] - fn it_works() { - let result = add(2, 2); - assert_eq!(result, 4); - } +#[cfg(feature = "default-logging")] +pub fn init_logging(level: Option<&str>) -> Result<(), LoggingError> { + init_default_logging(level)?; + Ok(()) } diff --git a/isotomachine/src/logging.rs b/isotomachine/src/logging.rs new file mode 100644 index 0000000..814f5ed --- /dev/null +++ b/isotomachine/src/logging.rs @@ -0,0 +1,56 @@ +//! This module provides a sensible default configuration of a logging system. + +#[cfg(feature = "default-logging")] +use env_logger::Builder; +#[cfg(feature = "default-logging")] +use std::io::Write; +#[cfg(feature = "default-logging")] +use crate::errors::util_errors::LoggingError; + +pub const LOG_TARGET: &str = "[isototest]"; + +#[cfg(feature = "default-logging")] +/// Initialize default logging configuration with given log level. +/// +/// Log Level can be: +/// * "info" - Default log level also adapted if level is `none`. Logs events relevant for general usage. +/// * "debug" - Debug level for extended logging. Should only be used for development purposes. +/// * "trace" - Extensive log evel logging every event. Should only be used for development purposes. +/// +pub(crate) fn init_default_logging(level: Option<&str>) -> Result<(), LoggingError> { + match level { + Some("info") | None => { + log_builder(log::LevelFilter::Info); + Ok(()) + }, + Some("debug") => { + log_builder(log::LevelFilter::Debug); + Ok(()) + }, + Some("trace") => { + log_builder(log::LevelFilter::Trace); + Ok(()) + }, + Some(invalid) => { + Err(LoggingError::InvalidLogLevelError(format!("Invalid log level '{}'!", invalid))) + } + } +} + +#[cfg(feature = "default-logging")] +fn log_builder(level: log::LevelFilter) { + Builder::new() + .filter_level(level) + .format(|buf, record| { + writeln!( + buf, + "{} [{}] {}: {}", + buf.timestamp(), + record.level(), + record.target(), + record.args() + ) + }) + .init(); +} + From 50b3f8942fe47ddb4aff5c44377e8cdfefa32557 Mon Sep 17 00:00:00 2001 From: ByteOtter Date: Wed, 14 Aug 2024 12:47:10 +0200 Subject: [PATCH 24/25] Create isotoenv library --- isotoenv/.gitignore | 21 ++ isotoenv/Cargo.toml | 18 ++ isotoenv/LICENSE | 339 +++++++++++++++++++++++++++++ isotoenv/README.md | 3 + isotoenv/src/errors/mod.rs | 3 + isotoenv/src/errors/util_errors.rs | 28 +++ isotoenv/src/lib.rs | 23 ++ isotoenv/src/logging.rs | 56 +++++ 8 files changed, 491 insertions(+) create mode 100644 isotoenv/.gitignore create mode 100644 isotoenv/Cargo.toml create mode 100644 isotoenv/LICENSE create mode 100644 isotoenv/README.md create mode 100644 isotoenv/src/errors/mod.rs create mode 100644 isotoenv/src/errors/util_errors.rs create mode 100644 isotoenv/src/lib.rs create mode 100644 isotoenv/src/logging.rs diff --git a/isotoenv/.gitignore b/isotoenv/.gitignore new file mode 100644 index 0000000..3c0d3d2 --- /dev/null +++ b/isotoenv/.gitignore @@ -0,0 +1,21 @@ +# Generated by Cargo +# will have compiled files and executables +debug/ +target/ + +# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries +# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html +Cargo.lock + +# These are backup files generated by rustfmt +**/*.rs.bk + +# MSVC Windows builds of rustc generate these, which store debugging information +*.pdb + +# Added by cargo +/target + +# Editor Configs +.idea/ +.vscode/ diff --git a/isotoenv/Cargo.toml b/isotoenv/Cargo.toml new file mode 100644 index 0000000..c8b454e --- /dev/null +++ b/isotoenv/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "isotoenv" +version = "0.1.0" +edition = "2021" +description = "A library for creating an openQA test environment on a designated target" +readme = "README.md" +repository = "https://github.com/os-autoinst/isotest-ng/tree/main/isotoenv" +license = "GPL-2.0" + +[dependencies] +log = "0.4.22" +env_logger = { version = "0.11.5", optional = true } + +[dev-dependencies] + +[features] +# Feature to enable default logging configuration +default-logging = ["env_logger"] diff --git a/isotoenv/LICENSE b/isotoenv/LICENSE new file mode 100644 index 0000000..d159169 --- /dev/null +++ b/isotoenv/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/isotoenv/README.md b/isotoenv/README.md new file mode 100644 index 0000000..cfd345e --- /dev/null +++ b/isotoenv/README.md @@ -0,0 +1,3 @@ +# isotoenv + +Set up a [openQA](https://open.qa) test environment on a remote worker. diff --git a/isotoenv/src/errors/mod.rs b/isotoenv/src/errors/mod.rs new file mode 100644 index 0000000..ad22c76 --- /dev/null +++ b/isotoenv/src/errors/mod.rs @@ -0,0 +1,3 @@ +//! This module defines custom error types to be returned by `isototest`. +//! These types are thematically split into submodules. +pub mod util_errors; diff --git a/isotoenv/src/errors/util_errors.rs b/isotoenv/src/errors/util_errors.rs new file mode 100644 index 0000000..40ba78e --- /dev/null +++ b/isotoenv/src/errors/util_errors.rs @@ -0,0 +1,28 @@ +//! This module defines and implements error type which refer to the supporting util of this library. +//! This means functionality like logging and similar supporting functionality, which do not necessarily +//! impact the core functionality of this library itself. +use std::fmt; + +#[derive(Debug)] +#[cfg(feature = "default-logging")] +pub enum LoggingError { + LoggingInitError(String), + InvalidLogLevelError(String), +} + +#[cfg(feature = "default-logging")] +impl fmt::Display for LoggingError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + LoggingError::LoggingInitError(msg) => { + write!(f, "[error] Logging initialization failed: '{}'", msg) + } + LoggingError::InvalidLogLevelError(msg) => { + write!(f, "[error] Invalid log level: '{}'", msg) + } + } + } +} + +#[cfg(feature = "default-logging")] +impl std::error::Error for LoggingError {} diff --git a/isotoenv/src/lib.rs b/isotoenv/src/lib.rs new file mode 100644 index 0000000..517cddc --- /dev/null +++ b/isotoenv/src/lib.rs @@ -0,0 +1,23 @@ +//! Prepare a test environment for [openQA](https://open.qa). +//! +//! This crate is responsible for preparing an `openQA` worker machine or VM for executing the test suite. +//! +//! ## Optional Features +//! +//! * `default-logging` - Provides you with a sensible logger configuration using the `env_logger` crate. + +// Organize library structure +pub mod logging; +pub mod errors; + +// Provide code on the root level of the library +#[cfg(feature = "default-logging")] +use crate::logging::init_default_logging; +#[cfg(feature = "default-logging")] +use crate::errors::util_errors::LoggingError; + +#[cfg(feature = "default-logging")] +pub fn init_logging(level: Option<&str>) -> Result<(), LoggingError> { + init_default_logging(level)?; + Ok(()) +} diff --git a/isotoenv/src/logging.rs b/isotoenv/src/logging.rs new file mode 100644 index 0000000..814f5ed --- /dev/null +++ b/isotoenv/src/logging.rs @@ -0,0 +1,56 @@ +//! This module provides a sensible default configuration of a logging system. + +#[cfg(feature = "default-logging")] +use env_logger::Builder; +#[cfg(feature = "default-logging")] +use std::io::Write; +#[cfg(feature = "default-logging")] +use crate::errors::util_errors::LoggingError; + +pub const LOG_TARGET: &str = "[isototest]"; + +#[cfg(feature = "default-logging")] +/// Initialize default logging configuration with given log level. +/// +/// Log Level can be: +/// * "info" - Default log level also adapted if level is `none`. Logs events relevant for general usage. +/// * "debug" - Debug level for extended logging. Should only be used for development purposes. +/// * "trace" - Extensive log evel logging every event. Should only be used for development purposes. +/// +pub(crate) fn init_default_logging(level: Option<&str>) -> Result<(), LoggingError> { + match level { + Some("info") | None => { + log_builder(log::LevelFilter::Info); + Ok(()) + }, + Some("debug") => { + log_builder(log::LevelFilter::Debug); + Ok(()) + }, + Some("trace") => { + log_builder(log::LevelFilter::Trace); + Ok(()) + }, + Some(invalid) => { + Err(LoggingError::InvalidLogLevelError(format!("Invalid log level '{}'!", invalid))) + } + } +} + +#[cfg(feature = "default-logging")] +fn log_builder(level: log::LevelFilter) { + Builder::new() + .filter_level(level) + .format(|buf, record| { + writeln!( + buf, + "{} [{}] {}: {}", + buf.timestamp(), + record.level(), + record.target(), + record.args() + ) + }) + .init(); +} + From 6241069e68e096f0cc59f20b4ff10fceca0b9cfb Mon Sep 17 00:00:00 2001 From: ByteOtter Date: Wed, 14 Aug 2024 13:58:12 +0200 Subject: [PATCH 25/25] Apply proper formatting --- isotoenv/src/lib.rs | 6 +++--- isotoenv/src/logging.rs | 30 +++++++++++++++--------------- isotomachine/src/lib.rs | 6 +++--- isotomachine/src/logging.rs | 30 +++++++++++++++--------------- isototest/src/lib.rs | 4 ++-- isototest/src/logging.rs | 30 +++++++++++++++--------------- 6 files changed, 53 insertions(+), 53 deletions(-) diff --git a/isotoenv/src/lib.rs b/isotoenv/src/lib.rs index 517cddc..d2f399f 100644 --- a/isotoenv/src/lib.rs +++ b/isotoenv/src/lib.rs @@ -7,14 +7,14 @@ //! * `default-logging` - Provides you with a sensible logger configuration using the `env_logger` crate. // Organize library structure -pub mod logging; pub mod errors; +pub mod logging; // Provide code on the root level of the library #[cfg(feature = "default-logging")] -use crate::logging::init_default_logging; -#[cfg(feature = "default-logging")] use crate::errors::util_errors::LoggingError; +#[cfg(feature = "default-logging")] +use crate::logging::init_default_logging; #[cfg(feature = "default-logging")] pub fn init_logging(level: Option<&str>) -> Result<(), LoggingError> { diff --git a/isotoenv/src/logging.rs b/isotoenv/src/logging.rs index 814f5ed..3cf5304 100644 --- a/isotoenv/src/logging.rs +++ b/isotoenv/src/logging.rs @@ -1,11 +1,11 @@ //! This module provides a sensible default configuration of a logging system. +#[cfg(feature = "default-logging")] +use crate::errors::util_errors::LoggingError; #[cfg(feature = "default-logging")] use env_logger::Builder; #[cfg(feature = "default-logging")] use std::io::Write; -#[cfg(feature = "default-logging")] -use crate::errors::util_errors::LoggingError; pub const LOG_TARGET: &str = "[isototest]"; @@ -22,18 +22,19 @@ pub(crate) fn init_default_logging(level: Option<&str>) -> Result<(), LoggingErr Some("info") | None => { log_builder(log::LevelFilter::Info); Ok(()) - }, + } Some("debug") => { log_builder(log::LevelFilter::Debug); Ok(()) - }, + } Some("trace") => { log_builder(log::LevelFilter::Trace); Ok(()) - }, - Some(invalid) => { - Err(LoggingError::InvalidLogLevelError(format!("Invalid log level '{}'!", invalid))) } + Some(invalid) => Err(LoggingError::InvalidLogLevelError(format!( + "Invalid log level '{}'!", + invalid + ))), } } @@ -43,14 +44,13 @@ fn log_builder(level: log::LevelFilter) { .filter_level(level) .format(|buf, record| { writeln!( - buf, - "{} [{}] {}: {}", - buf.timestamp(), - record.level(), - record.target(), - record.args() - ) + buf, + "{} [{}] {}: {}", + buf.timestamp(), + record.level(), + record.target(), + record.args() + ) }) .init(); } - diff --git a/isotomachine/src/lib.rs b/isotomachine/src/lib.rs index f4b3491..b7b7175 100644 --- a/isotomachine/src/lib.rs +++ b/isotomachine/src/lib.rs @@ -7,14 +7,14 @@ //! * `default-logging` - Provides you with a sensible logger configuration using the `env_logger` crate. // Organize library structure -pub mod logging; pub mod errors; +pub mod logging; // Provide code on the root level of the library #[cfg(feature = "default-logging")] -use crate::logging::init_default_logging; -#[cfg(feature = "default-logging")] use crate::errors::util_errors::LoggingError; +#[cfg(feature = "default-logging")] +use crate::logging::init_default_logging; #[cfg(feature = "default-logging")] pub fn init_logging(level: Option<&str>) -> Result<(), LoggingError> { diff --git a/isotomachine/src/logging.rs b/isotomachine/src/logging.rs index 814f5ed..3cf5304 100644 --- a/isotomachine/src/logging.rs +++ b/isotomachine/src/logging.rs @@ -1,11 +1,11 @@ //! This module provides a sensible default configuration of a logging system. +#[cfg(feature = "default-logging")] +use crate::errors::util_errors::LoggingError; #[cfg(feature = "default-logging")] use env_logger::Builder; #[cfg(feature = "default-logging")] use std::io::Write; -#[cfg(feature = "default-logging")] -use crate::errors::util_errors::LoggingError; pub const LOG_TARGET: &str = "[isototest]"; @@ -22,18 +22,19 @@ pub(crate) fn init_default_logging(level: Option<&str>) -> Result<(), LoggingErr Some("info") | None => { log_builder(log::LevelFilter::Info); Ok(()) - }, + } Some("debug") => { log_builder(log::LevelFilter::Debug); Ok(()) - }, + } Some("trace") => { log_builder(log::LevelFilter::Trace); Ok(()) - }, - Some(invalid) => { - Err(LoggingError::InvalidLogLevelError(format!("Invalid log level '{}'!", invalid))) } + Some(invalid) => Err(LoggingError::InvalidLogLevelError(format!( + "Invalid log level '{}'!", + invalid + ))), } } @@ -43,14 +44,13 @@ fn log_builder(level: log::LevelFilter) { .filter_level(level) .format(|buf, record| { writeln!( - buf, - "{} [{}] {}: {}", - buf.timestamp(), - record.level(), - record.target(), - record.args() - ) + buf, + "{} [{}] {}: {}", + buf.timestamp(), + record.level(), + record.target(), + record.args() + ) }) .init(); } - diff --git a/isototest/src/lib.rs b/isototest/src/lib.rs index 5460173..c3ed3c0 100644 --- a/isototest/src/lib.rs +++ b/isototest/src/lib.rs @@ -65,9 +65,9 @@ pub(crate) mod types; // Provide code on the root level of the library #[cfg(feature = "default-logging")] -use crate::logging::init_default_logging; -#[cfg(feature = "default-logging")] use crate::errors::util_errors::LoggingError; +#[cfg(feature = "default-logging")] +use crate::logging::init_default_logging; #[cfg(feature = "default-logging")] pub fn init_logging(level: Option<&str>) -> Result<(), LoggingError> { diff --git a/isototest/src/logging.rs b/isototest/src/logging.rs index 814f5ed..3cf5304 100644 --- a/isototest/src/logging.rs +++ b/isototest/src/logging.rs @@ -1,11 +1,11 @@ //! This module provides a sensible default configuration of a logging system. +#[cfg(feature = "default-logging")] +use crate::errors::util_errors::LoggingError; #[cfg(feature = "default-logging")] use env_logger::Builder; #[cfg(feature = "default-logging")] use std::io::Write; -#[cfg(feature = "default-logging")] -use crate::errors::util_errors::LoggingError; pub const LOG_TARGET: &str = "[isototest]"; @@ -22,18 +22,19 @@ pub(crate) fn init_default_logging(level: Option<&str>) -> Result<(), LoggingErr Some("info") | None => { log_builder(log::LevelFilter::Info); Ok(()) - }, + } Some("debug") => { log_builder(log::LevelFilter::Debug); Ok(()) - }, + } Some("trace") => { log_builder(log::LevelFilter::Trace); Ok(()) - }, - Some(invalid) => { - Err(LoggingError::InvalidLogLevelError(format!("Invalid log level '{}'!", invalid))) } + Some(invalid) => Err(LoggingError::InvalidLogLevelError(format!( + "Invalid log level '{}'!", + invalid + ))), } } @@ -43,14 +44,13 @@ fn log_builder(level: log::LevelFilter) { .filter_level(level) .format(|buf, record| { writeln!( - buf, - "{} [{}] {}: {}", - buf.timestamp(), - record.level(), - record.target(), - record.args() - ) + buf, + "{} [{}] {}: {}", + buf.timestamp(), + record.level(), + record.target(), + record.args() + ) }) .init(); } -