From 34f6eac00677d103164e1909fa87019ef5027457 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Julien=20Fastr=C3=A9?= Date: Fri, 15 Mar 2024 23:10:21 +0100 Subject: [PATCH] allow to assign automatically current user on new work package --- Cargo.lock | 39 ++++++++-------- Cargo.toml | 1 + src/cli.rs | 8 ++-- src/config.rs | 2 +- src/debug.rs | 19 ++++++++ src/error.rs | 2 +- src/gitlab/issue.rs | 10 +++-- src/gitlab/mod.rs | 7 ++- src/main.rs | 31 ++++++++----- src/openproject/client.rs | 59 +++++++++++++++++++----- src/openproject/hal.rs | 13 ++++++ src/openproject/mod.rs | 6 ++- src/openproject/root.rs | 42 ++++++++++++++++++ src/openproject/user.rs | 40 +++++++++++++++++ src/openproject/work.rs | 30 +++++-------- src/planning/issue2work.rs | 91 +++++++++++++++++++++++++++++++------- src/planning/mod.rs | 2 +- 17 files changed, 310 insertions(+), 92 deletions(-) create mode 100644 src/debug.rs create mode 100644 src/openproject/hal.rs create mode 100644 src/openproject/root.rs create mode 100644 src/openproject/user.rs diff --git a/Cargo.lock b/Cargo.lock index 89e6ced..c05560c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -25,7 +25,7 @@ checksum = "b9ccdd8f2a161be9bd5c023df56f1b2a0bd1d83872ae53b71a84a12c9bf6e842" dependencies = [ "proc-macro2", "quote", - "syn 2.0.10", + "syn 2.0.52", ] [[package]] @@ -110,6 +110,7 @@ version = "0.1.0" dependencies = [ "clap", "gitlab", + "log", "reqwest", "serde", "simple-home-dir", @@ -142,7 +143,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.10", + "syn 2.0.52", ] [[package]] @@ -228,7 +229,7 @@ dependencies = [ "proc-macro2", "quote", "scratch", - "syn 2.0.10", + "syn 2.0.52", ] [[package]] @@ -245,7 +246,7 @@ checksum = "2345488264226bf682893e25de0769f3360aac9957980ec49361b083ddaa5bc5" dependencies = [ "proc-macro2", "quote", - "syn 2.0.10", + "syn 2.0.52", ] [[package]] @@ -931,7 +932,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.10", + "syn 2.0.52", ] [[package]] @@ -984,18 +985,18 @@ checksum = "69d3587f8a9e599cc7ec2c00e331f71c4e69a5f9a4b8a6efd5b07466b9736f9a" [[package]] name = "proc-macro2" -version = "1.0.54" +version = "1.0.79" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e472a104799c74b514a57226160104aa483546de37e839ec50e3c2e41dd87534" +checksum = "e835ff2298f5721608eb1a980ecaee1aef2c132bf95ecc026a11b7bf3c01c02e" dependencies = [ "unicode-ident", ] [[package]] name = "quote" -version = "1.0.26" +version = "1.0.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4424af4bf778aae2051a77b60283332f386554255d722233d09fbfc7e30da2fc" +checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef" dependencies = [ "proc-macro2", ] @@ -1195,29 +1196,29 @@ dependencies = [ [[package]] name = "serde" -version = "1.0.158" +version = "1.0.197" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "771d4d9c4163ee138805e12c710dd365e4f44be8be0503cb1bb9eb989425d9c9" +checksum = "3fb1c873e1b9b056a4dc4c0c198b24c3ffa059243875552b2bd0933b1aee4ce2" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.158" +version = "1.0.197" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e801c1712f48475582b7696ac71e0ca34ebb30e09338425384269d9717c62cad" +checksum = "7eb0b34b42edc17f6b7cac84a52a1c5f0e1bb2227e997ca9011ea3dd34e8610b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.10", + "syn 2.0.52", ] [[package]] name = "serde_json" -version = "1.0.94" +version = "1.0.114" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c533a59c9d8a93a09c6ab31f0fd5e5f4dd1b8fc9434804029839884765d04ea" +checksum = "c5f09b1bd632ef549eaa9f60a1f8de742bdbc698e6cee2095fc84dde5f549ae0" dependencies = [ "itoa", "ryu", @@ -1304,9 +1305,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.10" +version = "2.0.52" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5aad1363ed6d37b84299588d62d3a7d95b5a5c2d9aad5c85609fda12afaa1f40" +checksum = "b699d15b36d1f02c3e7c69f8ffef53de37aefae075d8488d4ba1a7788d574a07" dependencies = [ "proc-macro2", "quote", @@ -1373,7 +1374,7 @@ checksum = "f9456a42c5b0d803c8cd86e73dd7cc9edd429499f37a3550d286d5e86720569f" dependencies = [ "proc-macro2", "quote", - "syn 2.0.10", + "syn 2.0.52", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index c277988..2cd682c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,3 +14,4 @@ toml = "0.7.3" url = "2.3.1" tokio = { version = "1.0.0", features = ["rt", "rt-multi-thread", "macros"] } simple-home-dir = "0.2.1" +log = "0.4.17" diff --git a/src/cli.rs b/src/cli.rs index e4578b4..44edd08 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -13,18 +13,20 @@ pub(crate) struct Cli { #[derive(Subcommand)] pub(crate) enum Commands { - #[command(subcommand)] - Planning(Planning) + Planning(Planning), + Test, } #[derive(Subcommand)] pub(crate) enum Planning { - I2work(Issue2Work) + I2work(Issue2Work), } #[derive(Args, Debug)] pub(crate) struct Issue2Work { pub issue_url: String, pub project_id: String, + #[arg(short, long)] + pub assign_to_me: bool, } diff --git a/src/config.rs b/src/config.rs index fa2244e..c6ee4e9 100644 --- a/src/config.rs +++ b/src/config.rs @@ -15,4 +15,4 @@ pub(crate) struct GitlabConfig { pub(crate) struct OpenProjectConfig { pub token: String, pub base_url: String, -} \ No newline at end of file +} diff --git a/src/debug.rs b/src/debug.rs new file mode 100644 index 0000000..68362b1 --- /dev/null +++ b/src/debug.rs @@ -0,0 +1,19 @@ +use crate::config::Config; +use crate::error::GeneralError; +use crate::openproject::client::Client; +use crate::openproject::root::RootClient; +use crate::openproject::user::GetMe; + +pub(crate) async fn debug(config: Config) -> Result<(), GeneralError> { + println!("test"); + + let open_project_client = Client::from_config(&config.openproject); + println!("base_url: {}", open_project_client.base_url); + println!("base_url: will get root"); + let r = open_project_client.root().await?; + println!("root: {:?}", r); + let u = open_project_client.me().await?; + println!("me: {:?}", u); + + Ok(()) +} diff --git a/src/error.rs b/src/error.rs index 6f9e34f..c39d1aa 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,4 +1,4 @@ - +#[derive(Debug)] pub struct GeneralError { pub(crate) description: String, } diff --git a/src/gitlab/issue.rs b/src/gitlab/issue.rs index 2a61698..d76316d 100644 --- a/src/gitlab/issue.rs +++ b/src/gitlab/issue.rs @@ -2,13 +2,17 @@ use gitlab::Issue; use gitlab::Project; /// A struct which contains Issue and Project +#[derive(Debug)] pub struct IssueBundle { pub issue: Issue, - pub project: Project + pub project: Project, } impl IssueBundle { pub fn new(issue: &Issue, project: &Project) -> Self { - IssueBundle{issue: issue.clone(), project: project.clone()} + IssueBundle { + issue: issue.clone(), + project: project.clone(), + } } -} \ No newline at end of file +} diff --git a/src/gitlab/mod.rs b/src/gitlab/mod.rs index a3afa9f..1a94752 100644 --- a/src/gitlab/mod.rs +++ b/src/gitlab/mod.rs @@ -1,13 +1,12 @@ pub mod issue; -use gitlab::GitlabError; use crate::error::GeneralError; +use gitlab::GitlabError; impl From for GeneralError { fn from(value: GitlabError) -> Self { - GeneralError{ - description: value.to_string() + GeneralError { + description: value.to_string(), } } } - diff --git a/src/main.rs b/src/main.rs index 6deabd1..19789f7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,24 +1,25 @@ -extern crate serde; extern crate clap; extern crate reqwest; +extern crate serde; extern crate simple_home_dir; mod cli; mod config; -mod planning; -mod openproject; +mod debug; mod error; mod gitlab; +mod openproject; +mod planning; -use std::fs; -use std::path::PathBuf; -use std::process::exit; +use crate::cli::Commands::{Planning, Test}; +use crate::cli::Planning::I2work; +use crate::error::GeneralError; use clap::Parser; use cli::Cli; use config::Config; -use crate::cli::Commands::Planning; -use crate::cli::Planning::I2work; -use crate::error::GeneralError; +use std::fs; +use std::path::PathBuf; +use std::process::exit; #[tokio::main] async fn main() { @@ -29,13 +30,16 @@ async fn main() { let config_path = match cli.config.as_deref() { Some(p) => p, - None => &default_config_path + None => &default_config_path, }; let config_path_content = match fs::read_to_string(config_path) { Ok(content) => content, Err(e) => { - println!("Could not read config file at {:?}, error: {}", config_path, e); + println!( + "Could not read config file at {:?}, error: {}", + config_path, e + ); exit(1); } }; @@ -44,7 +48,10 @@ async fn main() { let result = match cli.command { Some(Planning(I2work(args))) => planning::issue2work::issue2work(config, &args).await, - None => Err(GeneralError{description: "No command launched".to_string()}) + Some(Test) => debug::debug(config).await, + None => Err(GeneralError { + description: "No command launched".to_string(), + }), }; match result { diff --git a/src/openproject/client.rs b/src/openproject/client.rs index 3151caf..540a788 100644 --- a/src/openproject/client.rs +++ b/src/openproject/client.rs @@ -1,41 +1,80 @@ use crate::config::OpenProjectConfig; use crate::error::GeneralError; -use crate::openproject::work::{WorkPackageWriter, WorkPackage}; +use crate::openproject::work::{WorkPackage, WorkPackageWriter}; +use reqwest::Response; +use serde::Deserialize; +#[derive(Deserialize, Debug)] pub(crate) struct Error { - description: String, + pub(crate) description: String, } impl From for Error { fn from(value: reqwest::Error) -> Self { Error { - description: format!("Error while connecting to openproject instance: {}", value) + description: format!("Error while connecting to openproject instance: {}", value), } } } impl From for GeneralError { fn from(value: Error) -> GeneralError { - GeneralError{description: value.description} + GeneralError { + description: value.description, + } } } pub(crate) struct Client { - base_url: String, - token: String, + pub(crate) base_url: String, + pub(crate) token: String, +} + +pub async fn handle_response_status serde::Deserialize<'de>>( + response: Response, + error_message: &str, +) -> Result { + if !response.status().is_success() { + let status = response.status().to_string().clone(); + let content = response + .text() + .await + .unwrap_or_else(|_| "Impossible to decode".into()) + .clone(); + + return Err(Error { + description: format!( + "{}, status: {}, content: {}", + error_message, status, content + ), + }); + } + + let t = response.json().await?; + + Ok(t) } impl Client { pub fn from_config(config: &OpenProjectConfig) -> Client { - Client{base_url: config.base_url.clone(), token: config.token.clone()} + Client { + base_url: config.base_url.clone(), + token: config.token.clone(), + } } - pub async fn create_work_package(&self, work_package: &WorkPackageWriter, project_id: &String) -> Result { - + pub async fn create_work_package( + &self, + work_package: &WorkPackageWriter, + project_id: &String, + ) -> Result { let client = reqwest::Client::new(); let work_package: WorkPackage = client - .post(format!("{}/api/v3/projects/{}/work_packages", self.base_url, project_id)) + .post(format!( + "{}/api/v3/projects/{}/work_packages", + self.base_url, project_id + )) .basic_auth("apikey", Some(&self.token)) .json(&work_package) .send() diff --git a/src/openproject/hal.rs b/src/openproject/hal.rs new file mode 100644 index 0000000..581e758 --- /dev/null +++ b/src/openproject/hal.rs @@ -0,0 +1,13 @@ +use serde::Deserialize; + +#[derive(Deserialize, Debug)] +pub struct HalEntity { + #[serde(rename = "_type")] + pub d_type: String, +} + +#[derive(Deserialize, Debug, Clone)] +pub struct Link { + pub href: String, + pub title: Option, +} diff --git a/src/openproject/mod.rs b/src/openproject/mod.rs index 533ff88..0916fe7 100644 --- a/src/openproject/mod.rs +++ b/src/openproject/mod.rs @@ -1,3 +1,5 @@ pub(crate) mod client; -mod work; - +mod hal; +pub(crate) mod root; +pub(crate) mod user; +pub(crate) mod work; diff --git a/src/openproject/root.rs b/src/openproject/root.rs new file mode 100644 index 0000000..4070c03 --- /dev/null +++ b/src/openproject/root.rs @@ -0,0 +1,42 @@ +use crate::openproject::client::{handle_response_status, Client, Error}; +use crate::openproject::hal::HalEntity; +use serde::Deserialize; + +#[derive(Deserialize, Debug)] +pub struct User { + pub href: String, + pub title: String, +} +#[derive(Deserialize, Debug)] +pub struct Links { + pub user: User, +} +#[derive(Deserialize, Debug)] +pub struct Root { + #[serde(rename = "instanceName")] + pub instance_name: String, + #[serde(rename = "_links")] + pub links: Links, + #[serde(flatten)] + pub hal_entity: HalEntity, +} + +pub trait RootClient { + async fn root(&self) -> Result; +} + +impl RootClient for Client { + async fn root(&self) -> Result { + let client = reqwest::Client::new(); + + let response = client + .get(format!("{}/api/v3", self.base_url)) + .basic_auth("apikey", Some(&self.token)) + .send() + .await?; + + let r = handle_response_status(response, "Error while retrieving root").await?; + + Ok(r) + } +} diff --git a/src/openproject/user.rs b/src/openproject/user.rs new file mode 100644 index 0000000..2f3551a --- /dev/null +++ b/src/openproject/user.rs @@ -0,0 +1,40 @@ +use crate::openproject::client::{handle_response_status, Client, Error}; +use crate::openproject::hal::Link; +use crate::openproject::root::RootClient; +use serde::Deserialize; + +#[derive(Deserialize, Debug, Clone)] +pub struct UserLink { + #[serde(rename = "self")] + pub d_self: Link, +} +#[derive(Deserialize, Debug, Clone)] +pub struct User { + #[serde(rename = "_type")] + pub d_type: String, + pub id: u64, + pub name: String, + #[serde(rename = "_links")] + pub d_links: UserLink, +} + +pub trait GetMe { + async fn me(&self) -> Result; +} + +impl GetMe for Client { + async fn me(&self) -> Result { + let r = self.root().await?; + let client = reqwest::Client::new(); + + let response = client + .get(format!("{}{}", self.base_url, r.links.user.href)) + .basic_auth("apikey", Some(&self.token)) + .send() + .await?; + + let u = handle_response_status(response, "Error while retrieving user").await?; + + Ok(u) + } +} diff --git a/src/openproject/work.rs b/src/openproject/work.rs index fcc6ea2..63e074a 100644 --- a/src/openproject/work.rs +++ b/src/openproject/work.rs @@ -1,18 +1,22 @@ use serde::{Deserialize, Serialize}; -use crate::gitlab::issue::IssueBundle; +#[derive(Serialize, Debug)] +pub struct WorkPackageWriterAssignee { + pub(crate) href: String, +} #[derive(Serialize, Debug)] pub struct WorkPackageWriter { - subject: String, + pub(crate) subject: String, #[serde(alias = "type")] - work_type: String, - description: DescriptionWriter, + pub(crate) work_type: String, + pub(crate) description: DescriptionWriter, + pub assignee: Option, } #[derive(Serialize, Debug)] pub struct DescriptionWriter { - format: String, - raw: String, + pub(crate) format: String, + pub(crate) raw: String, } #[derive(Deserialize, Debug)] @@ -20,17 +24,3 @@ pub struct WorkPackage { pub id: u64, pub subject: String, } - -impl From<&IssueBundle> for WorkPackageWriter { - - fn from(value: &IssueBundle) -> Self { - WorkPackageWriter { - subject: format!("{} ({}/{})", value.issue.title, value.project.name_with_namespace, value.issue.iid), - work_type: "TASK".into(), - description: DescriptionWriter { - format: "markdown".into(), - raw: format!("From gitlab: {}", value.issue.web_url) - } - } - } -} diff --git a/src/planning/issue2work.rs b/src/planning/issue2work.rs index e08d31b..ebe1a51 100644 --- a/src/planning/issue2work.rs +++ b/src/planning/issue2work.rs @@ -1,11 +1,13 @@ use crate::cli::Issue2Work; use crate::config::Config; -use crate::openproject::client::Client; -use gitlab::{ GitlabBuilder, Issue, Project}; -use gitlab::api::{issues, AsyncQuery, projects}; -use url::Url; use crate::error::GeneralError; use crate::gitlab::issue::IssueBundle; +use crate::openproject::client::Client; +use crate::openproject::user::{GetMe, User}; +use crate::openproject::work::WorkPackageWriterAssignee; +use gitlab::api::{issues, projects, AsyncQuery}; +use gitlab::{GitlabBuilder, Issue, Project}; +use url::Url; #[derive(Debug)] struct IssueInfo { @@ -13,19 +15,56 @@ struct IssueInfo { iid: u64, } +/// details on how to create a work package from various informations +#[derive(Debug)] +struct Issue2WorkPackageDTO { + pub issue: IssueBundle, + pub assign_to: Option, +} + +impl From<&Issue2WorkPackageDTO> for Option { + fn from(value: &Issue2WorkPackageDTO) -> Self { + match &value.assign_to { + None => None, + Some(w) => Some(WorkPackageWriterAssignee { + href: w.clone().d_links.d_self.href, + }), + } + } +} + +impl From<&Issue2WorkPackageDTO> for crate::openproject::work::WorkPackageWriter { + fn from(value: &Issue2WorkPackageDTO) -> Self { + crate::openproject::work::WorkPackageWriter { + subject: format!( + "{} ({}/{})", + value.issue.issue.title, + value.issue.project.name_with_namespace, + value.issue.issue.iid + ), + work_type: "TASK".into(), + description: crate::openproject::work::DescriptionWriter { + format: "markdown".into(), + raw: format!("From gitlab: {}", value.issue.issue.web_url), + }, + assignee: value.into(), + } + } +} + pub(crate) async fn issue2work(config: Config, args: &Issue2Work) -> Result<(), GeneralError> { - let url = Url::parse(&*args.issue_url) - .expect("issue_url is not valid"); + let url = Url::parse(&*args.issue_url).expect("issue_url is not valid"); let data = extract_issue_info(&url).unwrap(); - let client = GitlabBuilder::new("gitlab.com", config.gitlab.token).build_async().await?; + let client = GitlabBuilder::new("gitlab.com", config.gitlab.token) + .build_async() + .await?; let endpoint = issues::ProjectIssues::builder() .iid(data.iid) .project(String::from(data.project)) .build() - .unwrap() - ; + .unwrap(); let issues: Vec = endpoint.query_async(&client).await.unwrap(); let issue = issues.first().unwrap(); @@ -41,15 +80,33 @@ pub(crate) async fn issue2work(config: Config, args: &Issue2Work) -> Result<(), let open_project_client = Client::from_config(&config.openproject); - let work_package = open_project_client.create_work_package(&(&issue_bundle).into(), &args.project_id).await?; + let dto = Issue2WorkPackageDTO { + issue: issue_bundle, + assign_to: match args.assign_to_me { + true => { + let u = open_project_client.me().await?; + Some(u) + } + false => None, + }, + }; - println!("new work package created: {:?}, edit at {}/projects/{}/work_packages/{}", work_package.subject, config.openproject.base_url, args.project_id, work_package.id); + let work_package = open_project_client + .create_work_package(&(&dto).into(), &args.project_id) + .await?; + + println!( + "new work package created: {:?}, edit at {}/projects/{}/work_packages/{}", + work_package.subject, config.openproject.base_url, args.project_id, work_package.id + ); Ok(()) } fn extract_issue_info(url: &Url) -> Option { - let parts = url.path_segments().expect("Could not parse path segment of given url"); + let parts = url + .path_segments() + .expect("Could not parse path segment of given url"); let mut project_url: Vec = Vec::with_capacity(3); let mut iid: Option = None; @@ -61,7 +118,7 @@ fn extract_issue_info(url: &Url) -> Option { continue; } if el == "issues" { - continue + continue; } if !project_found { project_url.push(String::from(el)); @@ -74,7 +131,9 @@ fn extract_issue_info(url: &Url) -> Option { Some(IssueInfo { project: project_url.join("/"), - iid: iid.expect("iid of the issue not found") - .parse().expect("could not transform issue id to u64") + iid: iid + .expect("iid of the issue not found") + .parse() + .expect("could not transform issue id to u64"), }) -} \ No newline at end of file +} diff --git a/src/planning/mod.rs b/src/planning/mod.rs index 3a7adda..dd9b3f9 100644 --- a/src/planning/mod.rs +++ b/src/planning/mod.rs @@ -1 +1 @@ -pub(crate) mod issue2work; \ No newline at end of file +pub(crate) mod issue2work;