Compare commits

..

No commits in common. "3c790efb2836bdd45a7802da9463975e5a68cdf7" and "279551eb54fba733ea0c0eaf9c1e19160faf00cf" have entirely different histories.

9 changed files with 60 additions and 165 deletions

View File

@ -1,16 +0,0 @@
name: "Build Rust binary in release mode"
on: push
jobs:
build:
name: "build"
runs-on: rust-bookworm
steps:
- name: Install build dependencies
run: |
apt-get update
apt-get install -y libasound2-dev
- name: Check out repository code
uses: actions/checkout@v4
- name: Build binary
run: cargo build --release

13
.gitlab-ci.yml Normal file
View File

@ -0,0 +1,13 @@
default:
image: rust
stages:
- build
before_script:
- apt update && apt install -y libasound2-dev
build:
stage: build
script:
- cargo build --release

View File

@ -1,6 +1,6 @@
[package]
name = "gitlabci-launchpad-controller"
version = "1.0.0"
name = "gitlab-rust"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

View File

@ -18,30 +18,6 @@ I used mainly two libraries for this project:
These two libraries are maintained at the moment this README is being written.
## Using
### Open associated project
Clicking on a tile opens the corresponding web page for the project linked to
this tile.
### Retry/create pipeline for project
Clicking on the `A` button will engage the `restart` mode. As long as it is
lit up, the mode is engaged.
If you click on a tile while the `A` button is lit up, it will retry or create a
new pipeline for this project and for this ref. You can disengage the mode by
pressing again the `A` button.
### Show project name on launchpad
Clicking on the `B` button will engage the `show text` mode. As long as it is
lit up, the mode is engaged.
If you click on a tile while the `B` button is lit up, it will show the project
name. You can disengage the mode by pressing again the `B` button.
## Building
As any other `cargo` project, it can be built with a simple command:
@ -65,6 +41,12 @@ in the current working directory. An example configuration file is provided,
The abs\_x and abs\_y coordinate are defined using the top-left grid tile as
the origin.
Clicking on a tile opens the corresponding web page for the project linked to
this tile. Clicking on the `A` button will light it up, it is the restart button.
If you click on a tile with the `A` button lit up, it will retry or create a
new pipeline for this project and for this ref. You can disengage the restart
mode by pressing again the `A` button.
## Limitations
This project has some limitations right now, and some of them will be fixed:
@ -72,6 +54,4 @@ This project has some limitations right now, and some of them will be fixed:
- the program is able to talk to one and only one gitlab API right now
- the configuration file has to be in the current working directory
- only one page is allowed, but 8 could be leveraged later using the 8 selectors
- the refresh delay is fixed for all threads and is at 2 seconds
- the launchpad mini is the only launchpad that can be used with this project

View File

@ -1,12 +0,0 @@
{
"host": "gitlab host",
"token": "gitlab token",
"projects": [
{
"name": "lovallat/lovallat",
"ref_": "master",
"abs_x": 0,
"abs_y": 0
}
]
}

View File

@ -1,17 +1,18 @@
use serde::{Deserialize, Serialize};
use log::{trace, warn};
use std::path::Path;
const CONFIG_FILENAME: &str = "./config.json";
#[derive(Clone, Debug, Deserialize, Serialize)]
// TODO REMOVE PUB AND REPLACE BY FN
#[derive(Clone, Deserialize, Serialize)]
pub struct Config {
pub host: String,
pub token: String,
pub key: String,
pub projects: Vec<Project>
}
// TODO REMOVE PUB AND REPLACE BY FN
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Project {
pub name: String,
@ -21,21 +22,15 @@ pub struct Project {
}
pub fn get_config() -> Option<Config> {
trace!("Trying to read config file at location '{}'.", CONFIG_FILENAME);
if Path::exists(Path::new(CONFIG_FILENAME)) {
return serde_json::from_str(
std::fs::read_to_string(CONFIG_FILENAME)
.expect("Cannot read configuration file.").as_str())
.expect("Cannot deserialize configuration file.");
std::fs::read_to_string(CONFIG_FILENAME).unwrap().as_str())
.unwrap();
}
warn!("Configuration file doesn't exist at location '{}'.", CONFIG_FILENAME);
return None;
}
pub fn save_config(config: &Config) {
trace!("Saving configuration file with content {:?}.", config);
std::fs::write(Path::new(CONFIG_FILENAME),
serde_json::to_string_pretty(config)
.expect("Could not serialize the configuration class to JSON."))
.expect("Could not write serialized configuration file.");
serde_json::to_string_pretty(config).unwrap()).unwrap();
}

View File

@ -2,7 +2,7 @@ use std::{thread::{sleep, self, JoinHandle}, time::Duration};
use launchy::{launchpad_mini::{Button, Color, Output, DoubleBufferingBehavior}, OutputDevice};
use serde::Deserialize;
use log::{warn, trace, debug, error};
use log::info;
use gitlab::{Gitlab, api::{projects::pipelines::{Pipelines, PipelineOrderBy}, Query}};
use crate::config_manager::{Config, Project};
@ -15,7 +15,6 @@ pub struct Pipeline {
status: String
}
#[derive(Debug)]
enum PipelineStatus {
Created,
WaitingForResource,
@ -32,7 +31,6 @@ enum PipelineStatus {
impl PipelineStatus {
fn from(s: &str) -> Option<PipelineStatus> {
trace!("Trying to convert '{}' to PipelineStatus.", s);
return match s {
"created" => Some(PipelineStatus::Created),
"waiting_for_resource" => Some(PipelineStatus::WaitingForResource),
@ -45,37 +43,29 @@ impl PipelineStatus {
"skipped" => Some(PipelineStatus::Skipped),
"manual" => Some(PipelineStatus::Manual),
"scheduled" => Some(PipelineStatus::Scheduled),
_ => { warn!("Could not find correspondance for status '{}'.", s); None }
_ => None
}
}
fn get_color(&self) -> (Color, bool) {
trace!("Getting color for PipelineStatus '{:?}'.", self);
return match self {
PipelineStatus::Pending => (Color::YELLOW, false),
PipelineStatus::Running => (Color::AMBER, true),
PipelineStatus::Success => (Color::GREEN, false),
PipelineStatus::Failed => (Color::RED, false),
PipelineStatus::Created => (Color::ORANGE, false),
_ => { warn!("Unknown color for pipeline status {:?}.", self);
(Color::OFF, false) }
_ => (Color::OFF, false)
};
}
}
pub fn refresh_on_timer(client: Gitlab, project: Project) {
trace!("Starting a refresh on timer task for project {:?}.", project);
let mut output = Output::guess().unwrap();
loop {
let pipeline = get_latest_pipelines(&client, &project);
if pipeline.is_none() {
error!("Project {:?} has no existing pipeline. Ignoring.", project);
return;
}
if pipeline.is_none() { return; }
let c = PipelineStatus::from(pipeline.unwrap().status.as_str())
.unwrap();
debug!("Project {:?} has a pipeline status of {:?}, updating.", project, c);
output.set_button(Button::GridButton { x: project.abs_x, y: project.abs_y },
c.get_color().0,
if c.get_color().1 { DoubleBufferingBehavior::Clear }
@ -85,65 +75,42 @@ pub fn refresh_on_timer(client: Gitlab, project: Project) {
}
pub fn load_from_config(config: Config) -> Vec<JoinHandle<()>> {
trace!("Loading gitlab manager from configuration.");
info!("Loading gitlab manager from configuration.");
let mut threads = vec![];
for p in config.projects.iter() {
let client = Gitlab::new(config.host.as_str(), config.token.as_str()).unwrap();
let client = Gitlab::new(config.host.as_str(), config.key.as_str()).unwrap();
let project = p.clone();
debug!("Spawning refresh thread for project {:?}.", project);
threads.push(thread::spawn(move|| refresh_on_timer(client, project)));
}
debug!("Spawned {} threads for the refreshes.", threads.len());
return threads;
}
pub fn get_latest_pipelines(client: &Gitlab, project: &Project) -> Option<Pipeline> {
trace!("Getting latest pipeline for project {:?}.", project);
let endpoint = Pipelines::builder()
.project(project.name.as_str()).ref_(project.ref_.as_str())
.order_by(PipelineOrderBy::Id).build().unwrap();
.order_by(PipelineOrderBy::UpdatedAt).build().unwrap();
let pipelines: Vec<Pipeline> = endpoint.query(client).unwrap_or(vec![]);
if pipelines.is_empty() {
warn!("No pipeline found for project {:?}.", project);
return None;
} else {
let pipeline = pipelines.first().unwrap().to_owned();
debug!("Found {:?} as latest pipeline for project {:?}.",
pipeline, project);
return Some(pipeline);
}
return if pipelines.is_empty() { None } else {
Some(pipelines.first().unwrap().to_owned()) };
}
pub fn retry_pipeline(host: &str, token: &str, project: &Project) {
trace!("Retrying pipeline for project {:?}.", project);
let client = Gitlab::new(host, token).unwrap();
let pipeline = get_latest_pipelines(&client, &project);
if pipeline.is_none() {
warn!("{:?} has no pipeline, ignoring.", project);
return;
}
let res: Option<Pipeline>;
if pipeline.is_none() { return; }
let _res: Pipeline;
if pipeline.clone().unwrap().status == "success" {
debug!("Latest pipeline for {:?} has a 'success' status, creating another one.",
project);
let endpoint = gitlab::api::projects::pipelines::CreatePipeline::builder()
.project(project.name.clone())
.ref_(project.ref_.clone())
.build().unwrap();
res = endpoint.query(&client).ok();
_res = endpoint.query(&client).unwrap();
} else {
debug!("Latest pipeline status for {:?} wasn't a success, retrying.",
project);
let endpoint = gitlab::api::projects::pipelines::RetryPipeline::builder()
.project(project.name.clone())
.pipeline(pipeline.unwrap().id)
.build().unwrap();
res = endpoint.query(&client).ok();
}
if res.is_none() {
error!("Could not retry/create a new pipeline for project {:?}. Ignoring.", project);
} else {
debug!("API answer was {:?}.", res.unwrap());
_res = endpoint.query(&client).unwrap();
}
}

View File

@ -1,67 +1,42 @@
use launchy::{OutputDevice, InputDevice, launchpad_mini::{Output, Input, Buffer, Button, Color, DoubleBuffering, DoubleBufferingBehavior, Message}, MsgPollingWrapper};
use log::{trace, debug, warn};
use crate::{config_manager::Config, gitlab_controller::retry_pipeline};
const RESTART_BUTTON: Button = Button::GridButton { x: 8, y: 0 }; // A BUTTON
const SHOW_TEXT_BUTTON: Button = Button::GridButton { x: 8, y: 1 }; // B BUTTON
const RESTART_BUTTON: Button = Button::GridButton { x: 8, y: 0 };
fn set_restart_light(output: &mut Output, status: bool) {
trace!("{} restart mode.", if status { "Engaged" } else { "Disengaged" });
output.set_button(RESTART_BUTTON,
if status { Color::DIM_GREEN } else { Color::OFF },
DoubleBufferingBehavior::Copy).unwrap();
fn engage_restart(output: &mut Output) {
output.set_button(RESTART_BUTTON, Color::DIM_GREEN, DoubleBufferingBehavior::Copy).unwrap();
}
fn set_show_text_light(output: &mut Output, status: bool) {
trace!("{} show text mode.", if status { "Engaged" } else { "Disengaged" });
output.set_button(SHOW_TEXT_BUTTON,
if status { Color::DIM_GREEN } else { Color::OFF },
DoubleBufferingBehavior::Copy).unwrap();
fn disengage_restart(output: &mut Output) {
output.set_button(RESTART_BUTTON, Color::OFF, DoubleBufferingBehavior::Copy).unwrap();
}
fn running_thread(config: Config) {
trace!("Starting a thread dedicated to the Launchpad input.");
let mut output = Output::guess().unwrap();
let input = Input::guess_polling().unwrap();
let (mut restart, mut show) = (false, false);
let mut restart = false;
for msg in input.iter() {
debug!("Got message from Launchpad: {:?}.", msg);
if let Message::Release { button } = msg {
if button == RESTART_BUTTON {
debug!("Restart button has been pressed.");
restart = !restart;
set_restart_light(&mut output, restart);
} else if button == SHOW_TEXT_BUTTON {
debug!("Show text button has been pressed.");
show = !show;
set_show_text_light(&mut output, show);
if !restart {
restart = true;
engage_restart(&mut output);
} else {
restart = false;
disengage_restart(&mut output);
}
} else if button.abs_x() != 8 {
debug!("A project tile has been pressed.");
let project = config.projects.iter()
.find(|p| p.abs_x == button.abs_x() && p.abs_y + 1 == button.abs_y());
if project.is_none() {
warn!("The tile {:?} has no project associated. Ignoring.", button);
continue;
}
if project.is_none() { continue; }
let project = project.unwrap();
debug!("Tile {:?} has an associated project {:?}.", button, project);
if restart {
debug!("Restart mode is engaged, attempting to restart pipeline for project {:?}.",
project);
restart = false;
retry_pipeline(config.host.as_str(), config.token.as_str(), project);
set_restart_light(&mut output, restart);
} else if show {
debug!("Showing project name on launchpad for project {:?}.", project);
show = false;
set_show_text_light(&mut output, show);
output.scroll_text(project.name.as_bytes(), Color::RED, false).unwrap();
retry_pipeline(config.host.as_str(), config.key.as_str(), project);
disengage_restart(&mut output);
} else {
let url = format!("https://{}/{}", config.host, project.name);
debug!("Restart mode isn't engaged. Trying to open project {:?} in browser with URL {}.",
project, url);
open::that_in_background(url);
open::that_in_background(format!("https://{}/{}", config.host, project.name));
}
}
}
@ -69,17 +44,13 @@ fn running_thread(config: Config) {
}
pub fn init(config: Config) {
trace!("Initializing launchpad.");
let mut output = launchy::launchpad_mini::Output::guess().unwrap();
debug!("Resetting launchpad state.");
output.reset().unwrap();
debug!("Setting up the double buffering behavior for the launchpad.");
output.control_double_buffering(DoubleBuffering {
copy: false,
flash: true,
edited_buffer: Buffer::A,
displayed_buffer: Buffer::A
}).unwrap();
debug!("Spawning a thread for handling to launchpad I/O.");
std::thread::spawn(move || running_thread(config));
}

View File

@ -1,4 +1,4 @@
use log::{info, error, trace};
use log::error;
use crate::config_manager::Config;
use crate::config_manager::Project;
@ -9,13 +9,11 @@ mod gitlab_controller;
fn main() {
env_logger::init();
trace!("Starting main application.");
let conf = config_manager::get_config();
if conf.is_none() {
info!("Configuration file cannot be loaded, saving a default one.");
config_manager::save_config(&Config {
host: "gitlab-host".to_string(),
token: "your-gitlab-key".to_string(),
key: "your-gitlab-key".to_string(),
projects: vec![Project {
name: "example".to_string(),
ref_: "master".to_string(),
@ -29,7 +27,6 @@ fn main() {
let conf = conf.unwrap();
launchpad_controller::init(conf.clone());
let threads = gitlab_controller::load_from_config(conf);
trace!("Joining timer threads.");
for t in threads {
t.join().unwrap();
}