From 2eec34f267ffd76c7c2ca5fb67573ba00e5757bb Mon Sep 17 00:00:00 2001 From: Christine Dodrill Date: Wed, 8 Jul 2020 17:35:08 -0400 Subject: [PATCH 1/8] add gitea crate --- gitea/Cargo.toml | 13 +++ gitea/src/lib.rs | 241 ++++++++++++++++++++++++++++++++++++++++++++ src/cmd/delete.rs | 25 ----- src/cmd/download.rs | 59 ----------- src/cmd/edit.rs | 48 --------- src/cmd/info.rs | 97 ------------------ src/cmd/upload.rs | 32 ------ src/gitea.rs | 212 -------------------------------------- 8 files changed, 254 insertions(+), 473 deletions(-) create mode 100644 gitea/Cargo.toml create mode 100644 gitea/src/lib.rs delete mode 100644 src/cmd/delete.rs delete mode 100644 src/cmd/download.rs delete mode 100644 src/cmd/edit.rs delete mode 100644 src/cmd/info.rs delete mode 100644 src/cmd/upload.rs delete mode 100644 src/gitea.rs diff --git a/gitea/Cargo.toml b/gitea/Cargo.toml new file mode 100644 index 0000000..33b2d21 --- /dev/null +++ b/gitea/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "gitea" +version = "0.1.0" +authors = ["Christine Dodrill "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +thiserror = "1" +reqwest = { version = "0.10", features = ["json"] } +serde_json = "1.0" +serde = { version = "1.0", features = ["derive"] } diff --git a/gitea/src/lib.rs b/gitea/src/lib.rs new file mode 100644 index 0000000..4b4a739 --- /dev/null +++ b/gitea/src/lib.rs @@ -0,0 +1,241 @@ +use reqwest::header; +use serde::{Deserialize, Serialize}; +use std::result::Result as StdResult; +use thiserror::Error; + +#[derive(Error, Debug)] +pub enum Error { + #[error("error from reqwest: {0:#?}")] + Reqwest(#[from] reqwest::Error), + + #[error("bad API token: {0:#?}")] + BadAPIToken(#[from] reqwest::header::InvalidHeaderValue), + + #[error("error parsing/serializing json: {0:#?}")] + Json(#[from] serde_json::Error), + + #[error("tag not found: {0}")] + TagNotFound(String), +} + +pub type Result = StdResult; + +#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Author { + pub id: i64, + pub login: String, + pub full_name: String, + pub email: String, + pub avatar_url: String, + pub language: String, + pub is_admin: bool, + pub last_login: String, + pub created: String, + pub username: String, +} + +#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Release { + pub id: i64, + pub tag_name: String, + pub target_commitish: String, + pub name: String, + pub body: String, + pub url: String, + pub tarball_url: String, + pub zipball_url: String, + pub draft: bool, + pub prerelease: bool, + pub created_at: String, + pub published_at: String, + pub author: Author, + pub assets: Vec, +} + +#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct CreateRelease { + pub body: String, + pub draft: bool, + pub name: String, + pub prerelease: bool, + pub tag_name: String, + pub target_commitish: String, +} + +#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Attachment { + pub id: i64, + pub name: String, + pub size: i64, + pub download_count: i64, + pub created_at: String, + pub uuid: String, + pub browser_download_url: String, +} + +#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Repo { + pub allow_merge_commits: bool, + pub allow_rebase: bool, + pub allow_rebase_explicit: bool, + pub allow_squash_merge: bool, + pub archived: bool, + pub avatar_url: String, + pub clone_url: String, + pub created_at: String, + pub default_branch: String, + pub description: String, + pub empty: bool, + pub fork: bool, + pub forks_count: i64, + pub full_name: String, + pub has_issues: bool, + pub has_pull_requests: bool, + pub has_wiki: bool, + pub html_url: String, + pub id: i64, + pub ignore_whitespace_conflicts: bool, + pub mirror: bool, + pub name: String, + pub open_issues_count: i64, + pub open_pr_counter: i64, + pub original_url: String, + pub owner: User, + pub permissions: Permissions, + pub private: bool, + pub release_counter: i64, + pub size: i64, + pub ssh_url: String, + pub stars_count: i64, + pub template: bool, + pub updated_at: String, + pub watchers_count: i64, + pub website: String, +} + +#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct User { + pub avatar_url: String, + pub created: String, + pub email: String, + pub full_name: String, + pub id: i64, + pub is_admin: bool, + pub language: String, + pub last_login: String, + pub login: String, +} + +#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Permissions { + pub admin: bool, + pub pull: bool, + pub push: bool, +} + +#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Version { + pub version: String, +} + +pub struct Client { + cli: reqwest::Client, + base_url: String, +} + +impl Client { + pub fn new(base_url: String, token: String, user_agent: String) -> Result { + let mut headers = header::HeaderMap::new(); + let auth = format!("token {}", token); + let auth = auth.as_str(); + headers.insert(header::AUTHORIZATION, header::HeaderValue::from_str(auth)?); + let cli = reqwest::Client::builder() + .user_agent(user_agent) + .default_headers(headers) + .build()?; + Ok(Self { + cli: cli, + base_url: base_url, + }) + } + + pub async fn version(&self) -> Result { + Ok(self + .cli + .get(&format!("{}/api/v1/version", self.base_url)) + .send() + .await? + .error_for_status()? + .json() + .await?) + } + + pub async fn get_release_by_tag( + &self, + owner: String, + repo: String, + tag: String, + ) -> Result { + let releases: Vec = self.get_releases(owner, repo).await?; + let mut release: Option = None; + + for rls in releases { + if *tag == rls.tag_name { + release = Some(rls); + } + } + + match release { + None => Err(Error::TagNotFound(tag)), + Some(release) => Ok(release), + } + } + + pub async fn get_repo(&self, owner: String, repo: String) -> Result { + Ok(self + .cli + .get(&format!( + "{}/api/v1/repos/{}/{}", + self.base_url, owner, repo + )) + .send() + .await? + .error_for_status()? + .json() + .await?) + } + + pub async fn get_releases(&self, owner: String, repo: String) -> Result> { + Ok(self + .cli + .get(&format!( + "{}/api/v1/repos/{}/{}/releases", + self.base_url, owner, repo + )) + .send() + .await? + .error_for_status()? + .json() + .await?) + } + + pub async fn create_release( + &self, + owner: String, + repo: String, + cr: CreateRelease, + ) -> Result { + Ok(self + .cli + .post(&format!( + "{}/api/v1/repos/{}/{}/releases", + self.base_url, owner, repo + )) + .json(&cr) + .send() + .await? + .error_for_status()? + .json() + .await?) + } +} diff --git a/src/cmd/delete.rs b/src/cmd/delete.rs deleted file mode 100644 index 3eb991d..0000000 --- a/src/cmd/delete.rs +++ /dev/null @@ -1,25 +0,0 @@ -use crate::{gitea::*, *}; -use anyhow::{anyhow, Result}; - -pub(crate) async fn run(common: Common, tag: String) -> Result<()> { - let cli = client(&common)?; - let release = - get_release_by_tag(&cli, &common.server, &common.owner, &common.repo, &tag).await?; - - let resp = cli - .delete( - format!( - "{}/api/v1/repos/{}/{}/releases/{}", - &common.server, &common.owner, &common.repo, release.id - ) - .as_str(), - ) - .send() - .await?; - - if resp.status() != http::StatusCode::from_u16(204)? { - Err(anyhow!("wanted 204, got {}", resp.status())) - } else { - Ok(()) - } -} diff --git a/src/cmd/download.rs b/src/cmd/download.rs deleted file mode 100644 index 665049c..0000000 --- a/src/cmd/download.rs +++ /dev/null @@ -1,59 +0,0 @@ -use crate::{gitea::*, *}; -use anyhow::{anyhow, Result}; -use cli_table::{Cell, Row, Table}; -use std::fs::File; -use std::io::Write; - -pub(crate) async fn run(common: Common, fname: Option, tag: String) -> Result<()> { - let cli = client(&common)?; - let release = - get_release_by_tag(&cli, &common.server, &common.owner, &common.repo, &tag).await?; - let attachments = get_attachments_for_release( - &cli, - &common.server, - &common.owner, - &common.repo, - &release.id, - ) - .await?; - - match fname { - None => { - let mut rows: Vec = vec![Row::new(vec![ - Cell::new(&"name", Default::default()), - Cell::new(&"size", Default::default()), - Cell::new(&"url", Default::default()), - ])]; - for attachment in attachments { - rows.push(attachment.row()) - } - - let table = Table::new(rows, Default::default())?; - table.print_stdout()?; - - Ok(()) - } - - Some(fname) => { - let mut url: Option = None; - let fname = fname.into_os_string().into_string().unwrap(); - - for attachment in attachments { - if &fname == &attachment.name { - url = Some(attachment.browser_download_url); - } - } - - if url.is_none() { - return Err(anyhow!("no attachment named {}", fname)); - } - - let data = &cli.get(url.unwrap().as_str()).send().await?.bytes().await?; - let mut fout = File::create(&fname)?; - - fout.write(data)?; - - Ok(()) - } - } -} diff --git a/src/cmd/edit.rs b/src/cmd/edit.rs deleted file mode 100644 index c89caa2..0000000 --- a/src/cmd/edit.rs +++ /dev/null @@ -1,48 +0,0 @@ -use crate::{gitea::*, *}; -use anyhow::{anyhow, Result}; - -pub(crate) async fn run( - common: Common, - description: Option, - rm: ReleaseMeta, - tag: String, -) -> Result<()> { - let cli = client(&common)?; - let release = - get_release_by_tag(&cli, &common.server, &common.owner, &common.repo, &tag).await?; - - let mut cr = CreateRelease { - body: release.body, - draft: release.draft, - name: release.name, - prerelease: release.prerelease, - tag_name: release.tag_name, - target_commitish: release.target_commitish, - }; - - if let Some(description) = description { - cr.body = description; - } - - if let Some(name) = rm.name { - cr.name = name; - } - - cr.draft = rm.draft; - cr.prerelease = rm.pre_release; - - let resp = cli - .post(&format!( - "{}/api/v1/repos/{}/{}/releases/{}", - common.server, common.owner, common.repo, release.id - )) - .json(&cr) - .send() - .await?; - - if !resp.status().is_success() { - return Err(anyhow!("{:?}", resp.status())); - } - - Ok(()) -} diff --git a/src/cmd/info.rs b/src/cmd/info.rs deleted file mode 100644 index 35c8512..0000000 --- a/src/cmd/info.rs +++ /dev/null @@ -1,97 +0,0 @@ -use crate::{gitea::*, *}; -use anyhow::{anyhow, Result}; -use cli_table::{Cell, Row, Table}; - -pub(crate) async fn run(common: Common, json: bool, tag: Option) -> Result<()> { - let cli = client(&common)?; - - let releases: Vec = cli - .get( - format!( - "{}/api/v1/repos/{}/{}/releases", - &common.server, &common.owner, &common.repo - ) - .as_str(), - ) - .send() - .await? - .json() - .await?; - - match tag { - Some(tag) => { - let mut release: Option = None; - - for rls in releases { - if tag == rls.tag_name { - release = Some(rls); - } - } - - if release.is_none() { - return Err(anyhow!("tag {} not found", tag)); - } - - if json { - println!("{}", serde_json::to_string_pretty(&release)?); - } else { - let rls = release.unwrap(); - let table = Table::new( - vec![ - Row::new(vec![ - Cell::new(&"id", Default::default()), - Cell::new(&rls.id, Default::default()), - ]), - Row::new(vec![ - Cell::new(&"author", Default::default()), - Cell::new( - &format!("{} - {}", rls.author.full_name, rls.author.username), - Default::default(), - ), - ]), - Row::new(vec![ - Cell::new(&"tag", Default::default()), - Cell::new(&rls.tag_name, Default::default()), - ]), - Row::new(vec![ - Cell::new(&"created at", Default::default()), - Cell::new(&rls.created_at, Default::default()), - ]), - Row::new(vec![ - Cell::new(&"name", Default::default()), - Cell::new(&rls.name, Default::default()), - ]), - Row::new(vec![ - Cell::new(&"body", Default::default()), - Cell::new(&rls.body, Default::default()), - ]), - ], - Default::default(), - )?; - table.print_stdout()?; - } - } - None => { - if json { - println!("{}", serde_json::to_string_pretty(&releases)?); - } else { - let mut rows: Vec = vec![Row::new(vec![ - Cell::new(&"id", Default::default()), - Cell::new(&"tag", Default::default()), - Cell::new(&"created at", Default::default()), - Cell::new(&"commit", Default::default()), - Cell::new(&"author", Default::default()), - Cell::new(&"name", Default::default()), - ])]; - for release in releases { - rows.push(release.row()) - } - - let table = Table::new(rows, Default::default())?; - table.print_stdout()?; - } - } - } - - Ok(()) -} diff --git a/src/cmd/upload.rs b/src/cmd/upload.rs deleted file mode 100644 index bd84273..0000000 --- a/src/cmd/upload.rs +++ /dev/null @@ -1,32 +0,0 @@ -use crate::{gitea::*, *}; -use anyhow::Result; -use reqwest::multipart; -use std::fs::File; -use std::io::Read; - -pub(crate) async fn run(common: Common, fname: PathBuf, tag: String) -> Result<()> { - let cli = client(&common)?; - let bytes = { - let mut fin = File::open(&fname)?; - let mut buffer = Vec::new(); - fin.read_to_end(&mut buffer)?; - buffer - }; - let form = multipart::Form::new().part("attachment", multipart::Part::bytes(bytes)); - let release = - get_release_by_tag(&cli, &common.server, &common.owner, &common.repo, &tag).await?; - - cli.post( - format!( - "{}/api/v1/repos/{}/{}/releases/{}", - &common.server, &common.owner, &common.repo, release.id, - ) - .as_str(), - ) - .query(&[("name", fname)]) - .multipart(form) - .send() - .await?; - - Ok(()) -} diff --git a/src/gitea.rs b/src/gitea.rs deleted file mode 100644 index 12ab662..0000000 --- a/src/gitea.rs +++ /dev/null @@ -1,212 +0,0 @@ -use anyhow::{anyhow, Result}; -use serde::{Deserialize, Serialize}; - -#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct Author { - pub id: i64, - pub login: String, - pub full_name: String, - pub email: String, - pub avatar_url: String, - pub language: String, - pub is_admin: bool, - pub last_login: String, - pub created: String, - pub username: String, -} - -#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct Release { - pub id: i64, - pub tag_name: String, - pub target_commitish: String, - pub name: String, - pub body: String, - pub url: String, - pub tarball_url: String, - pub zipball_url: String, - pub draft: bool, - pub prerelease: bool, - pub created_at: String, - pub published_at: String, - pub author: Author, - pub assets: Vec, -} - -use cli_table::{Cell, Row}; -impl Release { - pub fn row(&self) -> Row { - Row::new(vec![ - Cell::new(&format!("{}", self.id), Default::default()), - Cell::new(&self.tag_name, Default::default()), - Cell::new(&self.created_at, Default::default()), - Cell::new(&self.target_commitish, Default::default()), - Cell::new(&self.author.username, Default::default()), - Cell::new(&self.name, Default::default()), - ]) - } -} - -#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct CreateRelease { - pub body: String, - pub draft: bool, - pub name: String, - pub prerelease: bool, - pub tag_name: String, - pub target_commitish: String, -} - -pub(crate) async fn get_release_by_tag( - cli: &reqwest::Client, - server: &String, - owner: &String, - repo: &String, - tag: &String, -) -> Result { - let releases: Vec = cli - .get(&format!( - "{}/api/v1/repos/{}/{}/releases", - server, owner, repo - )) - .send() - .await? - .json() - .await?; - - let mut release: Option = None; - - for rls in releases { - if *tag == rls.tag_name { - release = Some(rls); - } - } - - if release.is_none() { - return Err(anyhow!("tag {} not found", tag)); - } - - Ok(release.unwrap()) -} - -#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct Attachment { - pub id: i64, - pub name: String, - pub size: i64, - pub download_count: i64, - pub created_at: String, - pub uuid: String, - pub browser_download_url: String, -} - -impl Attachment { - pub fn row(&self) -> Row { - let size = { - let bytes = byte_unit::Byte::from_bytes(self.size as u128); - let unit = bytes.get_appropriate_unit(false); - unit.to_string() - }; - - Row::new(vec![ - Cell::new(&self.name, Default::default()), - Cell::new(&size, Default::default()), - Cell::new(&self.browser_download_url, Default::default()), - ]) - } -} - -#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct Repo { - pub allow_merge_commits: bool, - pub allow_rebase: bool, - pub allow_rebase_explicit: bool, - pub allow_squash_merge: bool, - pub archived: bool, - pub avatar_url: String, - pub clone_url: String, - pub created_at: String, - pub default_branch: String, - pub description: String, - pub empty: bool, - pub fork: bool, - pub forks_count: i64, - pub full_name: String, - pub has_issues: bool, - pub has_pull_requests: bool, - pub has_wiki: bool, - pub html_url: String, - pub id: i64, - pub ignore_whitespace_conflicts: bool, - pub mirror: bool, - pub name: String, - pub open_issues_count: i64, - pub open_pr_counter: i64, - pub original_url: String, - pub owner: Owner, - pub permissions: Permissions, - pub private: bool, - pub release_counter: i64, - pub size: i64, - pub ssh_url: String, - pub stars_count: i64, - pub template: bool, - pub updated_at: String, - pub watchers_count: i64, - pub website: String, -} - -pub(crate) async fn get_repo( - cli: &reqwest::Client, - server: &String, - owner: &String, - repo: &String, -) -> Result { - Ok(cli - .get(&format!("{}/api/v1/repos/{}/{}", server, owner, repo)) - .send() - .await? - .error_for_status()? - .json() - .await?) -} - -#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct Owner { - pub avatar_url: String, - pub created: String, - pub email: String, - pub full_name: String, - pub id: i64, - pub is_admin: bool, - pub language: String, - pub last_login: String, - pub login: String, -} - -#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct Permissions { - pub admin: bool, - pub pull: bool, - pub push: bool, -} - -pub(crate) async fn get_attachments_for_release( - cli: &reqwest::Client, - server: &String, - owner: &String, - repo: &String, - id: &i64, -) -> Result> { - let attachments: Vec = cli - .get(&format!( - "{}/api/v1/repos/{}/{}/releases/{}/assets", - server, owner, repo, id - )) - .send() - .await? - .json() - .await?; - - Ok(attachments) -} -- 2.44.0 From 9e2347d1f8b661cc16fad6e4b94d5512bde0937f Mon Sep 17 00:00:00 2001 From: Christine Dodrill Date: Wed, 8 Jul 2020 17:36:53 -0400 Subject: [PATCH 2/8] remove all functionality but release creation --- Cargo.lock | 67 +++++++++++++++++++---------------------- Cargo.toml | 9 ++++-- README.md | 6 ++-- docker.nix | 2 +- src/cmd/drone_plugin.rs | 17 ++++++----- src/cmd/mod.rs | 55 --------------------------------- src/cmd/release.rs | 21 ++++--------- src/main.rs | 29 ++---------------- 8 files changed, 62 insertions(+), 144 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 351c247..3ac0f05 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -86,12 +86,6 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3b5ca7a04898ad4bcd41c90c5285445ff5b791899bb1b0abdd2a2aa791211d7" -[[package]] -name = "byte-unit" -version = "3.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55390dbbf21ce70683f3e926dace00a21da373e35e44a60cafd232e3e9bf2041" - [[package]] name = "byteorder" version = "1.3.4" @@ -134,16 +128,6 @@ dependencies = [ "vec_map", ] -[[package]] -name = "cli-table" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd782cbfda62468ed8f94f2c00496ff909ad4916f4411ab9ec7bdced5414a699" -dependencies = [ - "termcolor", - "unicode-width", -] - [[package]] name = "comrak" version = "0.7.0" @@ -324,15 +308,24 @@ dependencies = [ "url", ] +[[package]] +name = "gitea" +version = "0.1.0" +dependencies = [ + "reqwest", + "serde", + "serde_json", + "thiserror", +] + [[package]] name = "gitea-release" version = "0.3.2" dependencies = [ "anyhow", - "byte-unit", - "cli-table", "comrak", "git2", + "gitea", "http", "kankyo", "reqwest", @@ -1138,15 +1131,6 @@ dependencies = [ "winapi 0.3.8", ] -[[package]] -name = "termcolor" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb6bfa289a4d7c5766392812c0a1f4c1ba45afa1ad47803c11e1f407d846d75f" -dependencies = [ - "winapi-util", -] - [[package]] name = "textwrap" version = "0.11.0" @@ -1156,6 +1140,26 @@ dependencies = [ "unicode-width", ] +[[package]] +name = "thiserror" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dfdd070ccd8ccb78f4ad66bf1982dc37f620ef696c6b5028fe2ed83dd3d0d08" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd80fc12f73063ac132ac92aceea36734f04a1d93c1240c6944e23a3b8841793" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "thread_local" version = "1.0.1" @@ -1476,15 +1480,6 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" -[[package]] -name = "winapi-util" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" -dependencies = [ - "winapi 0.3.8", -] - [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" diff --git a/Cargo.toml b/Cargo.toml index f8c9744..ddb3eef 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,8 +8,6 @@ edition = "2018" [dependencies] anyhow = "1.0" -byte-unit = "3" -cli-table = "0.3" comrak = "0.7" git2 = "0.13" http = "0.2" @@ -21,8 +19,15 @@ structopt = { version = "0.3", default-features = false } tokio = { version = "0.2", features = ["macros"] } url = "2" +gitea = { path = "./gitea" } + [dev-dependencies] tempfile = "3" [profile.release] lto = true + +[workspace] +members = [ + "./gitea" +] diff --git a/README.md b/README.md index 681c5ee..4826720 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,8 @@ To use this as a drone plugin, add the following to your `.drone.yml` under the ```yaml - name: auto-release - image: xena/gitea-release:0.3.2 + image: xena/gitea-release:latest + pull: always settings: auth_username: cadey changelog_path: ./CHANGELOG.md @@ -53,7 +54,8 @@ setting like this: ```yaml - name: auto-release - image: xena/gitea-release:0.3.2 + image: xena/gitea-release:latest + pull: always settings: auth_username: cadey default_branch: trunk diff --git a/docker.nix b/docker.nix index b4e47d0..2070e42 100644 --- a/docker.nix +++ b/docker.nix @@ -8,7 +8,7 @@ let dockerImage = pkg: pkgs.dockerTools.buildLayeredImage { name = "xena/gitea-release"; - tag = "${gitea-release.version}"; + tag = "latest"; contents = [ pkgs.cacert pkg ]; diff --git a/src/cmd/drone_plugin.rs b/src/cmd/drone_plugin.rs index 71b2152..a0dd6af 100644 --- a/src/cmd/drone_plugin.rs +++ b/src/cmd/drone_plugin.rs @@ -6,14 +6,17 @@ use url::Url; pub(crate) async fn run(env: DroneEnv) -> Result<()> { let common: Common = env.clone().into(); - let default_branch = match &env.default_branch { - None => { - let cli = crate::client(&common)?; - let repo = - crate::gitea::get_repo(&cli, &common.server, &common.owner, &common.repo).await?; - repo.default_branch + let default_branch = { + let common = common.clone(); + match &env.default_branch { + None => { + let cli = + gitea::Client::new(common.server, common.token, crate::APP_USER_AGENT.into())?; + let repo = cli.get_repo(common.owner, common.repo).await?; + repo.default_branch + } + Some(branch) => branch.to_string(), } - Some(branch) => branch.to_string(), }; if env.branch != default_branch { diff --git a/src/cmd/mod.rs b/src/cmd/mod.rs index 131c02f..e518fa4 100644 --- a/src/cmd/mod.rs +++ b/src/cmd/mod.rs @@ -1,13 +1,8 @@ use std::path::PathBuf; use structopt::StructOpt; -pub(crate) mod delete; -pub(crate) mod download; pub(crate) mod drone_plugin; -pub(crate) mod edit; -pub(crate) mod info; pub(crate) mod release; -pub(crate) mod upload; #[derive(StructOpt, Debug, Clone)] pub(crate) struct Common { @@ -90,51 +85,11 @@ pub(crate) struct ReleaseMeta { #[derive(StructOpt, Debug)] #[structopt(about = "Gitea release assistant")] pub(crate) enum Cmd { - /// Delete a given release from Gitea - Delete { - #[structopt(flatten)] - common: Common, - /// The version tag to operate on - #[structopt(short, long)] - tag: String, - }, - /// Downloads release artifacts - Download { - #[structopt(flatten)] - common: Common, - /// File to download - fname: Option, - /// The version tag to operate on - #[structopt(short, long)] - tag: String, - }, /// Runs the release process as a drone plugin DronePlugin { #[structopt(flatten)] env: DroneEnv, }, - /// Edits a release's description, name and other flags - Edit { - #[structopt(flatten)] - common: Common, - /// Release description - #[structopt(short, long)] - description: Option, - #[structopt(flatten)] - release_meta: ReleaseMeta, - /// The version tag to operate on - tag: String, - }, - /// Gets release info - Info { - #[structopt(flatten)] - common: Common, - #[structopt(long, short)] - json: bool, - /// The version tag to operate on - #[structopt(short, long)] - tag: Option, - }, /// Create a new tag and release on Gitea Release { #[structopt(flatten)] @@ -147,14 +102,4 @@ pub(crate) enum Cmd { #[structopt(flatten)] release_meta: ReleaseMeta, }, - /// Uploads release artifacts to Gitea - Upload { - #[structopt(flatten)] - common: Common, - /// The version tag to operate on - #[structopt(short, long)] - tag: String, - /// The location of the file on the disk - fname: PathBuf, - }, } diff --git a/src/cmd/release.rs b/src/cmd/release.rs index 05d20bf..332d09b 100644 --- a/src/cmd/release.rs +++ b/src/cmd/release.rs @@ -1,4 +1,4 @@ -use crate::{gitea::*, *}; +use crate::{changelog, cmd::*, git, version}; use anyhow::Result; use std::path::PathBuf; @@ -22,8 +22,10 @@ pub(crate) async fn run( } let desc = changelog::read(fname, tag.clone())?; - let cli = client(&common)?; - let cr = CreateRelease { + + let cli = gitea::Client::new(common.server, common.token, crate::APP_USER_AGENT.into())?; + + let cr = gitea::CreateRelease { body: desc, draft: rm.draft, name: rm.name.or(Some(format!("Version {}", tag))).unwrap(), @@ -32,18 +34,7 @@ pub(crate) async fn run( target_commitish: "HEAD".into(), }; - let resp = cli - .post(&format!( - "{}/api/v1/repos/{}/{}/releases", - common.server, common.owner, common.repo - )) - .json(&cr) - .send() - .await?; - - if !resp.status().is_success() { - return Err(anyhow!("{:?} -> {}", resp.status(), resp.text().await?)); - } + let _ = cli.create_release(common.owner, common.repo, cr).await?; println!("Created release {}", tag); diff --git a/src/main.rs b/src/main.rs index d7bdaaa..26093d8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,29 +1,16 @@ -use anyhow::{anyhow, Result}; -use reqwest::{header, Client}; -use std::path::PathBuf; +use anyhow::Result; use structopt::StructOpt; mod changelog; mod cmd; mod git; -mod gitea; mod version; pub(crate) use cmd::*; // Name your user agent after your app? -static APP_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")); - -pub(crate) fn client(c: &cmd::Common) -> Result { - let mut headers = header::HeaderMap::new(); - let auth = format!("token {}", &c.token); - let auth = auth.as_str(); - headers.insert(header::AUTHORIZATION, header::HeaderValue::from_str(auth)?); - Ok(Client::builder() - .user_agent(APP_USER_AGENT) - .default_headers(headers) - .build()?) -} +pub(crate) static APP_USER_AGENT: &str = + concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")); #[tokio::main] async fn main() -> Result<()> { @@ -31,22 +18,12 @@ async fn main() -> Result<()> { let cmd = cmd::Cmd::from_args(); match cmd { - Cmd::Delete { common, tag } => cmd::delete::run(common, tag).await, - Cmd::Download { common, fname, tag } => cmd::download::run(common, fname, tag).await, Cmd::DronePlugin { env } => cmd::drone_plugin::run(env).await, - Cmd::Edit { - common, - description, - release_meta, - tag, - } => cmd::edit::run(common, description, release_meta, tag).await, - Cmd::Info { common, json, tag } => cmd::info::run(common, json, tag).await, Cmd::Release { common, changelog, tag, release_meta, } => cmd::release::run(common, changelog, tag, release_meta).await, - Cmd::Upload { common, fname, tag } => cmd::upload::run(common, fname, tag).await, } } -- 2.44.0 From a45e4ab8df50a3d8b639fe8fdeec88e729886b26 Mon Sep 17 00:00:00 2001 From: Christine Dodrill Date: Wed, 8 Jul 2020 18:24:59 -0400 Subject: [PATCH 3/8] documentation, tests, elfs crate --- CHANGELOG.md | 17 ++++- Cargo.lock | 80 ++++++++++++++++++++-- Cargo.toml | 2 + elfs/Cargo.toml | 10 +++ elfs/src/lib.rs | 75 ++++++++++++++++++++ gitea/Cargo.toml | 4 ++ gitea/src/lib.rs | 151 ++++++++++++++++++++++++++++++++++++----- gitea/tests/version.rs | 16 +++++ 8 files changed, 333 insertions(+), 22 deletions(-) create mode 100644 elfs/Cargo.toml create mode 100644 elfs/src/lib.rs create mode 100644 gitea/tests/version.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 8cf9bff..a620b64 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,22 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## Unreleased +## 0.4.0 + +This is a functionality-breaking release that removes untested/extraneous parts +of this project. + +### ADDED + +- The gitea client embedded into this repo is now a more generic crate that can + be reused across other projects. +- Gitea types have been simplified and redundant types have been removed. +- Simple tests for the gitea crate. +- A name generator `elfs` was created for future use in integration testing. + +### REMOVED + +- All functionality but the drone plugin and release commands ## 0.3.2 diff --git a/Cargo.lock b/Cargo.lock index 3ac0f05..dc72d90 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -176,6 +176,13 @@ version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4358a9e11b9a09cf52383b451b49a169e8d797b68aa02301ff586d70d9661ea3" +[[package]] +name = "elfs" +version = "0.1.0" +dependencies = [ + "names", +] + [[package]] name = "encoding_rs" version = "0.8.23" @@ -218,6 +225,12 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" +[[package]] +name = "fuchsia-cprng" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" + [[package]] name = "fuchsia-zircon" version = "0.3.3" @@ -312,10 +325,12 @@ dependencies = [ name = "gitea" version = "0.1.0" dependencies = [ + "anyhow", "reqwest", "serde", "serde_json", "thiserror", + "tokio", ] [[package]] @@ -324,6 +339,7 @@ version = "0.3.2" dependencies = [ "anyhow", "comrak", + "elfs", "git2", "gitea", "http", @@ -633,6 +649,15 @@ dependencies = [ "ws2_32-sys", ] +[[package]] +name = "names" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef320dab323286b50fb5cdda23f61c796a72a89998ab565ca32525c5c556f2da" +dependencies = [ + "rand 0.3.23", +] + [[package]] name = "native-tls" version = "0.2.4" @@ -838,6 +863,29 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "rand" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64ac302d8f83c0c1974bf758f6b041c6c8ada916fbb44a609158ca8b064cc76c" +dependencies = [ + "libc", + "rand 0.4.6", +] + +[[package]] +name = "rand" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "552840b97013b1a26992c11eac34bdd778e464601a4c2054b5f0bff7c6761293" +dependencies = [ + "fuchsia-cprng", + "libc", + "rand_core 0.3.1", + "rdrand", + "winapi 0.3.8", +] + [[package]] name = "rand" version = "0.7.3" @@ -847,7 +895,7 @@ dependencies = [ "getrandom", "libc", "rand_chacha", - "rand_core", + "rand_core 0.5.1", "rand_hc", ] @@ -858,9 +906,24 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402" dependencies = [ "ppv-lite86", - "rand_core", + "rand_core 0.5.1", ] +[[package]] +name = "rand_core" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" +dependencies = [ + "rand_core 0.4.2", +] + +[[package]] +name = "rand_core" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c33a3c44ca05fa6f1807d8e6743f3824e8509beca625669633be0acbdf509dc" + [[package]] name = "rand_core" version = "0.5.1" @@ -876,7 +939,16 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c" dependencies = [ - "rand_core", + "rand_core 0.5.1", +] + +[[package]] +name = "rdrand" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "678054eb77286b51581ba43620cc911abf02758c91f93f479767aed0f90458b2" +dependencies = [ + "rand_core 0.3.1", ] [[package]] @@ -1125,7 +1197,7 @@ checksum = "7a6e24d9338a0a5be79593e2fa15a648add6138caa803e2d5bc782c371732ca9" dependencies = [ "cfg-if", "libc", - "rand", + "rand 0.7.3", "redox_syscall", "remove_dir_all", "winapi 0.3.8", diff --git a/Cargo.toml b/Cargo.toml index ddb3eef..8b39d15 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,11 +23,13 @@ gitea = { path = "./gitea" } [dev-dependencies] tempfile = "3" +elfs = { path = "./elfs" } [profile.release] lto = true [workspace] members = [ + "./elfs", "./gitea" ] diff --git a/elfs/Cargo.toml b/elfs/Cargo.toml new file mode 100644 index 0000000..6783c44 --- /dev/null +++ b/elfs/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "elfs" +version = "0.1.0" +authors = ["Christine Dodrill "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +names = "0" diff --git a/elfs/src/lib.rs b/elfs/src/lib.rs new file mode 100644 index 0000000..4615cff --- /dev/null +++ b/elfs/src/lib.rs @@ -0,0 +1,75 @@ +/// This one-function crate generates names based on [Pokemon Vietnamese Crystal](https://tvtropes.org/pmwiki/pmwiki.php/VideoGame/PokemonVietnameseCrystal). + +use names::{Generator, Name}; + +fn moves() -> &'static [&'static str] { + &[ + "ABLE", "ABNORMA", "AGAIN", "AIREXPL", "ANG", "ANGER", "ASAIL", "ATTACK", "AURORA", "AWL", + "BAN", "BAND", "BARE", "BEAT", "BEATED", "BELLY", "BIND", "BITE", "BLOC", "BLOOD", "BODY", + "BOOK", "BREATH", "BUMP", "CAST", "CHAM", "CLAMP", "CLAP", "CLAW", "CLEAR", "CLI", "CLIP", + "CLOUD", "CONTRO", "CONVY", "COOLHIT", "CRASH", "CRY", "CUT", "DESCRI", "D-FIGHT", "DIG", + "DITCH", "DIV", "DOZ", "DRE", "DUL", "DU-PIN", "DYE", "EARTH", "EDU", "EG-BOMB", "EGG", + "ELEGY", "ELE-HIT", "EMBODY", "EMPLI", "ENGL", "ERUPT", "EVENS", "EXPLOR", "EYES", "FALL", + "FAST", "F-CAR", "F-DANCE", "FEARS", "F-FIGHT", "FIGHT", "FIR", "FIRE", "FIREHIT", "FLAME", + "FLAP", "FLASH", "FLEW", "FORCE", "FRA", "FREEZE", "FROG", "G-BIRD", "GENKISS", "GIFT", + "G-KISS", "G-MOUSE", "GRADE", "GROW", "HAMMER", "HARD", "HAT", "HATE", "H-BOMB", "HELL-R", + "HEMP", "HINT", "HIT", "HU", "HUNT", "HYPNOSI", "INHA", "IRO", "IRONBAR", "IR-WING", + "J-GUN", "KEE", "KICK", "KNIF", "KNIFE", "KNOCK", "LEVEL", "LIGH", "LIGHHIT", "LIGHT", + "LIVE", "L-WALL", "MAD", "MAJUS", "MEL", "MELO", "MESS", "MILK", "MIMI", "MISS", "MIXING", + "MOVE", "MUD", "NI-BED", "NOISY", "NOONLI", "NULL", "N-WAVE", "PAT", "PEACE", "PIN", + "PLAN", "PLANE", "POIS", "POL", "POWDE", "POWE", "POWER", "PRIZE", "PROTECT", "PROUD", + "RAGE", "RECOR", "REFLAC", "REFREC", "REGR", "RELIV", "RENEW", "R-FIGHT", "RING", "RKICK", + "ROCK", "ROUND", "RUS", "RUSH", "SAND", "SAW", "SCISSOR", "SCRA", "SCRIPT", "SEEN", + "SERVER", "SHADOW", "SHELL", "SHINE", "SHO", "SIGHT", "SIN", "SMALL", "SMELT", "SMOK", + "SNAKE", "SNO", "SNOW", "SOU", "SO-WAVE", "SPAR", "SPEC", "SPID", "S-PIN", "SPRA", "STAM", + "STARE", "STEA", "STONE", "STORM", "STRU", "STRUG", "STUDEN", "SUBS", "SUCID", "SUN-LIG", + "SUNRIS", "SUPLY", "S-WAVE", "TAILS", "TANGL", "TASTE", "TELLI", "THANK", "TONKICK", + "TOOTH", "TORL", "TRAIN", "TRIKICK", "TUNGE", "VOLT", "WA-GUN", "WATCH", "WAVE", "W-BOMB", + "WFALL", "WFING", "WHIP", "WHIRL", "WIND", "WOLF", "WOOD", "WOR", "YUJA", + ] +} + +fn names() -> &'static [&'static str] { + &[ + "SEED", "GRASS", "FLOWE", "SHAD", "CABR", "SNAKE", "GOLD", "COW", "GUIKI", "PEDAL", + "DELAN", "B-FLY", "BIDE", "KEYU", "FORK", "LAP", "PIGE", "PIJIA", "CAML", "LAT", "BIRD", + "BABOO", "VIV", "ABOKE", "PIKAQ", "RYE", "SAN", "BREAD", "LIDEL", "LIDE", "PIP", "PIKEX", + "ROK", "JUGEN", "PUD", "BUDE", "ZHIB", "GELU", "GRAS", "FLOW", "LAFUL", "ATH", "BALA", + "CORN", "MOLUF", "DESP", "DAKED", "MIMI", "BOLUX", "KODA", "GELUD", "MONK", "SUMOY", + "GEDI", "WENDI", "NILEM", "NILE", "NILEC", "KEZI", "YONGL", "HUDE", "WANLI", "GELI", + "GUAIL", "MADAQ", "WUCI", "WUCI", "MUJEF", "JELLY", "SICIB", "GELU", "NELUO", "BOLI", + "JIALE", "YED", "YEDE", "CLO", "SCARE", "AOCO", "DEDE", "DEDEI", "BAWU", "JIUG", "BADEB", + "BADEB", "HOLE", "BALUX", "GES", "FANT", "QUAR", "YIHE", "SWAB", "SLIPP", "CLU", "DEPOS", + "BILIY", "YUANO", "SOME", "NO", "YELA", "EMPT", "ZECUN", "XIAHE", "BOLEL", "DEJI", "MACID", + "XIHON", "XITO", "LUCK", "MENJI", "GELU", "DECI", "XIDE", "DASAJ", "DONGN", "RICUL", + "MINXI", "BALIY", "ZENDA", "LUZEL", "HELE5", "0FENB", "KAIL", "JIAND", "CARP", "JINDE", + "LAPU", "MUDE", "YIFU", "LINLI", "SANDI", "HUSI", "JINC", "OUMU", "OUMUX", "CAP", "KUIZA", + "PUD", "TIAO", "FRMAN", "CLAU", "SPARK", "DRAGO", "BOLIU", "GUAIL", "MIYOU", "MIY", + "QIAOK", "BEIL", "MUKEI", "RIDED", "MADAM", "BAGEP", "CROC", "ALIGE", "OUDAL", "OUD", + "DADA", "HEHE", "YEDEA", "NUXI", "NUXIN", "ROUY", "ALIAD", "STICK", "QIANG", "LAAND", + "PIQI", "PI", "PUPI", "DEKE", "DEKEJ", "NADI", "NADIO", "MALI", "PEA", "ELECT", "FLOWE", + "MAL", "MALI", "HUSHU", "NILEE", "YUZI", "POPOZ", "DUZI", "HEBA", "XIAN", "SHAN", "YEYEA", + "WUY", "LUO", "KEFE", "HULA", "CROW", "YADEH", "MOW", "ANNAN", "SUONI", "KYLI", "HULU", + "HUDEL", "YEHE", "GULAE", "YEHE", "BLU", "GELAN", "BOAT", "NIP", "POIT", "HELAK", "XINL", + "BEAR", "LINB", "MAGEH", "MAGEJ", "WULI", "YIDE", "RIVE", "FISH", "AOGU", "DELIE", "MANTE", + "KONMU", "DELU", "HELU", "HUAN", "HUMA", "DONGF", "JINCA", "HEDE", "DEFU", "LIBY", "JIAPA", + "MEJI", "HELE", "BUHU", "MILK", "HABI", "THUN", "GARD", "DON", "YANGQ", "SANAQ", "BANQ", + "LUJ", "PHIX", "SIEI", "EGG", + ] +} + +/// Generate a new name based on [Pokemon Vietnamese Crystal](https://tvtropes.org/pmwiki/pmwiki.php/VideoGame/PokemonVietnameseCrystal) +/// +/// ```rust +/// let name = elfs::next(); +/// ``` +pub fn next() -> String { + let mut generator = Generator::new(moves(), names(), Name::Numbered); + generator.next().unwrap() +} + +#[cfg(test)] +#[test] +fn name() { + assert_ne!(next(), "".to_string()); +} diff --git a/gitea/Cargo.toml b/gitea/Cargo.toml index 33b2d21..cfdd770 100644 --- a/gitea/Cargo.toml +++ b/gitea/Cargo.toml @@ -11,3 +11,7 @@ thiserror = "1" reqwest = { version = "0.10", features = ["json"] } serde_json = "1.0" serde = { version = "1.0", features = ["derive"] } + +[dev-dependencies] +anyhow = "1" +tokio = { version = "0.2", features = ["macros"] } diff --git a/gitea/src/lib.rs b/gitea/src/lib.rs index 4b4a739..e08c6fb 100644 --- a/gitea/src/lib.rs +++ b/gitea/src/lib.rs @@ -3,6 +3,8 @@ use serde::{Deserialize, Serialize}; use std::result::Result as StdResult; use thiserror::Error; +/// Error represents all of the possible errors that can happen with the Gitea +/// API. Most of these errors boil down to user error. #[derive(Error, Debug)] pub enum Error { #[error("error from reqwest: {0:#?}")] @@ -18,22 +20,11 @@ pub enum Error { TagNotFound(String), } +/// A handy alias for Result like `anyhow::Result`. pub type Result = StdResult; -#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct Author { - pub id: i64, - pub login: String, - pub full_name: String, - pub email: String, - pub avatar_url: String, - pub language: String, - pub is_admin: bool, - pub last_login: String, - pub created: String, - pub username: String, -} - +/// A repository release. +/// https://try.gitea.io/api/swagger#model-Release #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Release { pub id: i64, @@ -48,10 +39,12 @@ pub struct Release { pub prerelease: bool, pub created_at: String, pub published_at: String, - pub author: Author, + pub author: User, pub assets: Vec, } +/// The inputs to create a repository release. +/// https://try.gitea.io/api/swagger#model-CreateReleaseOption #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct CreateRelease { pub body: String, @@ -62,6 +55,8 @@ pub struct CreateRelease { pub target_commitish: String, } +/// An attachment to a release, such as a pre-built package. +/// https://try.gitea.io/api/swagger#model-Attachment #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Attachment { pub id: i64, @@ -73,6 +68,8 @@ pub struct Attachment { pub browser_download_url: String, } +/// A git repository. +/// https://try.gitea.io/api/swagger#model-Repository #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Repo { pub allow_merge_commits: bool, @@ -113,6 +110,8 @@ pub struct Repo { pub website: String, } +/// A user. +/// https://try.gitea.io/api/swagger#model-User #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct User { pub avatar_url: String, @@ -126,6 +125,8 @@ pub struct User { pub login: String, } +/// The permission set that a given user has on a Repo. +/// https://try.gitea.io/api/swagger#model-Permission #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Permissions { pub admin: bool, @@ -133,24 +134,40 @@ pub struct Permissions { pub push: bool, } +/// The version of Gitea. +/// https://try.gitea.io/api/swagger#model-ServerVersion #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Version { pub version: String, } +/// The gitea client that all gitea calls will go through. This wraps +/// [reqwest::Client](https://docs.rs/reqwest/0.10.6/reqwest/struct.Client.html) +/// and operates asyncronously. pub struct Client { cli: reqwest::Client, base_url: String, } impl Client { - pub fn new(base_url: String, token: String, user_agent: String) -> Result { + /// Create a new API client with the given base URL, token and user agent. + /// If you need inspiration for a user agent, try this: + /// + /// ```rust + /// const APP_USER_AGENT: &'static str = + /// concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")); + /// gitea::Client::new("https://tulpa.dev".into(), "ayylmao".into(), APP_USER_AGENT).unwrap(); + /// ``` + pub fn new(base_url: String, token: String, user_agent: T) -> Result + where + T: Into, + { let mut headers = header::HeaderMap::new(); let auth = format!("token {}", token); let auth = auth.as_str(); headers.insert(header::AUTHORIZATION, header::HeaderValue::from_str(auth)?); let cli = reqwest::Client::builder() - .user_agent(user_agent) + .user_agent(user_agent.into()) .default_headers(headers) .build()?; Ok(Self { @@ -159,6 +176,18 @@ impl Client { }) } + /// Gets the current version of gitea. + /// + /// ```rust + /// use gitea::Result; + /// + /// #[tokio::main] + /// async fn main() -> Result<()> { + /// let cli = gitea::Client::new("https://tulpa.dev".into(), "ayylmao".into(), "test/test")?; + /// println!("{:?}", cli.version().await?); + /// Ok(()) + /// } + /// ``` pub async fn version(&self) -> Result { Ok(self .cli @@ -170,6 +199,18 @@ impl Client { .await?) } + /// Gets a release of a repo by its tag name. + /// + /// ```rust + /// use gitea::Result; + /// + /// #[tokio::main] + /// async fn main() -> Result<()> { + /// let cli = gitea::Client::new("https://tulpa.dev".into(), "ayylmao".into(), "test/test")?; + /// let release = cli.get_release_by_tag("cadey".into(), "gitea-release".into(), "0.3.2".into()).await; + /// Ok(()) + /// } + /// ``` pub async fn get_release_by_tag( &self, owner: String, @@ -191,6 +232,18 @@ impl Client { } } + /// Gets a gitea repo by name. + /// + /// ```rust + /// use gitea::Result; + /// + /// #[tokio::main] + /// async fn main() -> Result<()> { + /// let cli = gitea::Client::new("https://tulpa.dev".into(), "ayylmao".into(), "test/test")?; + /// let repo = cli.get_repo("cadey".into(), "gitea-release".into()).await; + /// Ok(()) + /// } + /// ``` pub async fn get_repo(&self, owner: String, repo: String) -> Result { Ok(self .cli @@ -205,6 +258,18 @@ impl Client { .await?) } + /// Gets all of the releases for a given gitea repo. + /// + /// ```rust + /// use gitea::Result; + /// + /// #[tokio::main] + /// async fn main() -> Result<()> { + /// let cli = gitea::Client::new("https://tulpa.dev".into(), "ayylmao".into(), "test/test")?; + /// let repo = cli.get_releases("cadey".into(), "gitea-release".into()).await; + /// Ok(()) + /// } + /// ``` pub async fn get_releases(&self, owner: String, repo: String) -> Result> { Ok(self .cli @@ -219,6 +284,29 @@ impl Client { .await?) } + /// Creates a new gitea release. + /// + /// ```rust + /// use gitea::{CreateRelease, Result}; + /// + /// #[tokio::main] + /// async fn main() -> Result<()> { + /// let cli = gitea::Client::new("https://tulpa.dev".into(), "ayylmao".into(), "test/test")?; + /// let repo = cli.create_release( + /// "cadey".into(), + /// "gitea-release".into(), + /// CreateRelease{ + /// body: "This is a cool release".into(), + /// draft: false, + /// name: "test".into(), + /// prerelease: false, + /// tag_name: "v4.2.0".into(), + /// target_commitish: "HEAD".into(), + /// }, + /// ).await; + /// Ok(()) + /// } + /// ``` pub async fn create_release( &self, owner: String, @@ -238,4 +326,33 @@ impl Client { .json() .await?) } + + /// Deletes a given release by tag name. + /// + /// ```rust + /// use gitea::Result; + /// + /// #[tokio::main] + /// async fn main() -> Result<()> { + /// let cli = gitea::Client::new("https://tulpa.dev".into(), "ayylmao".into(), "test/test")?; + /// let _ = cli.delete_release("cadey".into(), "gitea-release".into(), "4.2.0".into()).await; + /// Ok(()) + /// } + /// ``` + pub async fn delete_release(&self, owner: String, repo: String, tag: String) -> Result<()> { + let release = self + .get_release_by_tag(owner.clone(), repo.clone(), tag) + .await?; + + self.cli + .delete(&format!( + "{}/api/v1/repos/{}/{}/releases/{}", + self.base_url, owner, repo, release.id + )) + .send() + .await? + .error_for_status()?; + + Ok(()) + } } diff --git a/gitea/tests/version.rs b/gitea/tests/version.rs new file mode 100644 index 0000000..f4536c1 --- /dev/null +++ b/gitea/tests/version.rs @@ -0,0 +1,16 @@ +use anyhow::Result; +use gitea::Client; + +#[tokio::test] +async fn version() -> Result<()> { + let cli = Client::new( + std::env::var("GITEA_SERVER")?, + std::env::var("DOMO_GITEA_TOKEN")?, + "gitea/tests", + )?; + + let vers = cli.version().await?; + println!("gitea version {}", vers.version); + + Ok(()) +} -- 2.44.0 From f186ff7ae56458a2e1f60554873329fe813a1e8b Mon Sep 17 00:00:00 2001 From: Christine Dodrill Date: Wed, 8 Jul 2020 18:26:23 -0400 Subject: [PATCH 4/8] domo gitea token --- .drone.yml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.drone.yml b/.drone.yml index 6f0b602..05a54ab 100644 --- a/.drone.yml +++ b/.drone.yml @@ -6,7 +6,11 @@ steps: image: "rust:1" pull: always commands: - - cargo test + - cargo test --all + environment: + GITEA_SERVER: https://tulpa.dev + DOMO_GITEA_TOKEN: + from_secret: DOMO_GITEA_TOKEN when: event: - push -- 2.44.0 From 8ef626cbd2c8f0414f1c6c807e2a0aa815008bb9 Mon Sep 17 00:00:00 2001 From: Christine Dodrill Date: Wed, 8 Jul 2020 18:32:59 -0400 Subject: [PATCH 5/8] fix --- src/cmd/drone_plugin.rs | 2 +- src/cmd/release.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cmd/drone_plugin.rs b/src/cmd/drone_plugin.rs index a0dd6af..775192e 100644 --- a/src/cmd/drone_plugin.rs +++ b/src/cmd/drone_plugin.rs @@ -11,7 +11,7 @@ pub(crate) async fn run(env: DroneEnv) -> Result<()> { match &env.default_branch { None => { let cli = - gitea::Client::new(common.server, common.token, crate::APP_USER_AGENT.into())?; + gitea::Client::new(common.server, common.token, crate::APP_USER_AGENT)?; let repo = cli.get_repo(common.owner, common.repo).await?; repo.default_branch } diff --git a/src/cmd/release.rs b/src/cmd/release.rs index 332d09b..981778c 100644 --- a/src/cmd/release.rs +++ b/src/cmd/release.rs @@ -23,7 +23,7 @@ pub(crate) async fn run( let desc = changelog::read(fname, tag.clone())?; - let cli = gitea::Client::new(common.server, common.token, crate::APP_USER_AGENT.into())?; + let cli = gitea::Client::new(common.server, common.token, crate::APP_USER_AGENT)?; let cr = gitea::CreateRelease { body: desc, -- 2.44.0 From 4397f691c9bbf8f6c59127976ed0f821690bc8c4 Mon Sep 17 00:00:00 2001 From: Christine Dodrill Date: Wed, 8 Jul 2020 18:54:43 -0400 Subject: [PATCH 6/8] vtag --- src/cmd/release.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cmd/release.rs b/src/cmd/release.rs index 981778c..2324ab3 100644 --- a/src/cmd/release.rs +++ b/src/cmd/release.rs @@ -22,15 +22,15 @@ pub(crate) async fn run( } let desc = changelog::read(fname, tag.clone())?; - let cli = gitea::Client::new(common.server, common.token, crate::APP_USER_AGENT)?; + let vtag = format!("v{}", tag); let cr = gitea::CreateRelease { body: desc, draft: rm.draft, name: rm.name.or(Some(format!("Version {}", tag))).unwrap(), prerelease: rm.pre_release, - tag_name: tag.clone(), + tag_name: vtag, target_commitish: "HEAD".into(), }; -- 2.44.0 From 03004b31e755441373a1158823e2f722e728ea19 Mon Sep 17 00:00:00 2001 From: Christine Dodrill Date: Wed, 8 Jul 2020 19:02:31 -0400 Subject: [PATCH 7/8] rename release to cut --- CHANGELOG.md | 9 ++++++++- VERSION | 2 +- src/cmd/{release.rs => cut.rs} | 0 src/cmd/drone_plugin.rs | 2 +- src/cmd/mod.rs | 16 +++++++++------- src/main.rs | 6 +++--- 6 files changed, 22 insertions(+), 13 deletions(-) rename src/cmd/{release.rs => cut.rs} (100%) diff --git a/CHANGELOG.md b/CHANGELOG.md index a620b64..9a98ab1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## Unreleased + ## 0.4.0 This is a functionality-breaking release that removes untested/extraneous parts @@ -17,9 +19,14 @@ of this project. - Simple tests for the gitea crate. - A name generator `elfs` was created for future use in integration testing. +### CHANGED + +- `release` is renamed to `cut`, but there is an alias for the old `release` + subcommand name. + ### REMOVED -- All functionality but the drone plugin and release commands +- All functionality but the drone plugin and release commands. ## 0.3.2 diff --git a/VERSION b/VERSION index d15723f..1d0ba9e 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.3.2 +0.4.0 diff --git a/src/cmd/release.rs b/src/cmd/cut.rs similarity index 100% rename from src/cmd/release.rs rename to src/cmd/cut.rs diff --git a/src/cmd/drone_plugin.rs b/src/cmd/drone_plugin.rs index 775192e..57e1b06 100644 --- a/src/cmd/drone_plugin.rs +++ b/src/cmd/drone_plugin.rs @@ -32,7 +32,7 @@ pub(crate) async fn run(env: DroneEnv) -> Result<()> { origin.connect(git2::Direction::Fetch)?; origin.fetch(&["refs/tags/*:refs/tags/*"], None, None)?; - release::run( + cut::run( common, env.changelog_path, None, diff --git a/src/cmd/mod.rs b/src/cmd/mod.rs index e518fa4..d94fab6 100644 --- a/src/cmd/mod.rs +++ b/src/cmd/mod.rs @@ -1,8 +1,8 @@ use std::path::PathBuf; use structopt::StructOpt; +pub(crate) mod cut; pub(crate) mod drone_plugin; -pub(crate) mod release; #[derive(StructOpt, Debug, Clone)] pub(crate) struct Common { @@ -85,13 +85,9 @@ pub(crate) struct ReleaseMeta { #[derive(StructOpt, Debug)] #[structopt(about = "Gitea release assistant")] pub(crate) enum Cmd { - /// Runs the release process as a drone plugin - DronePlugin { - #[structopt(flatten)] - env: DroneEnv, - }, /// Create a new tag and release on Gitea - Release { + #[structopt(alias = "release")] + Cut { #[structopt(flatten)] common: Common, /// Changelog file to read from to create the release description @@ -102,4 +98,10 @@ pub(crate) enum Cmd { #[structopt(flatten)] release_meta: ReleaseMeta, }, + + /// Runs the release process as a drone plugin + DronePlugin { + #[structopt(flatten)] + env: DroneEnv, + }, } diff --git a/src/main.rs b/src/main.rs index 26093d8..dae376e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -18,12 +18,12 @@ async fn main() -> Result<()> { let cmd = cmd::Cmd::from_args(); match cmd { - Cmd::DronePlugin { env } => cmd::drone_plugin::run(env).await, - Cmd::Release { + Cmd::Cut { common, changelog, tag, release_meta, - } => cmd::release::run(common, changelog, tag, release_meta).await, + } => cmd::cut::run(common, changelog, tag, release_meta).await, + Cmd::DronePlugin { env } => cmd::drone_plugin::run(env).await, } } -- 2.44.0 From 524a12305c35878efb82d890f7f2279a9614c238 Mon Sep 17 00:00:00 2001 From: Christine Dodrill Date: Wed, 8 Jul 2020 19:16:09 -0400 Subject: [PATCH 8/8] prepare crates for publishing --- .drone.yml | 31 +++++++++++++++++++++++++++++++ elfs/Cargo.toml | 8 +++++++- elfs/README.md | 16 ++++++++++++++++ gitea/Cargo.toml | 6 ++++++ gitea/README.md | 8 ++++++++ gitea/src/lib.rs | 2 ++ 6 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 elfs/README.md create mode 100644 gitea/README.md diff --git a/.drone.yml b/.drone.yml index 05a54ab..9863d83 100644 --- a/.drone.yml +++ b/.drone.yml @@ -30,6 +30,37 @@ steps: --- +kind: pipeline +name: cargo publish +steps: + - name: publish elfs + image: rust:1 + commands: + - cd elfs + - cargo login $CARGO_TOKEN + - cargo publish + environment: + CARGO_TOKEN: + from_secret: CARGO_TOKEN + when: + event: + - tag + + - name: publish gitea + image: rust:1 + commands: + - cd gitea + - cargo login $CARGO_TOKEN + - cargo publish + environment: + CARGO_TOKEN: + from_secret: CARGO_TOKEN + when: + event: + - tag + +--- + kind: pipeline name: docker steps: diff --git a/elfs/Cargo.toml b/elfs/Cargo.toml index 6783c44..d13f441 100644 --- a/elfs/Cargo.toml +++ b/elfs/Cargo.toml @@ -3,8 +3,14 @@ name = "elfs" version = "0.1.0" authors = ["Christine Dodrill "] edition = "2018" +homepage = "https://tulpa.dev/cadey/gitea-release/src/branch/main/elfs" +repository = "https://tulpa.dev/cadey/gitea-release" +keywords = ["namegen"] +license = "MIT" +readme = "README.md" +description = "A simple name generator for Rust programs." # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -names = "0" +names = "0.11" diff --git a/elfs/README.md b/elfs/README.md new file mode 100644 index 0000000..7f31fc6 --- /dev/null +++ b/elfs/README.md @@ -0,0 +1,16 @@ +# elfs + +A simple name generator based on [Pokemon Vietnamese Crystal](https://tvtropes.org/pmwiki/pmwiki.php/VideoGame/PokemonVietnameseCrystal). + +## Usage + +Add the following to your `Cargo.toml`: + +```toml +[dependencies] +elfs = "0.1" +``` + +```rust +let name = elfs::next(); +``` diff --git a/gitea/Cargo.toml b/gitea/Cargo.toml index cfdd770..e43d767 100644 --- a/gitea/Cargo.toml +++ b/gitea/Cargo.toml @@ -3,6 +3,12 @@ name = "gitea" version = "0.1.0" authors = ["Christine Dodrill "] edition = "2018" +homepage = "https://tulpa.dev/cadey/gitea-release/src/branch/main/gitea" +repository = "https://tulpa.dev/cadey/gitea-release" +keywords = ["gitea", "api", "http"] +license = "MIT" +readme = "README.md" +description = "A Gitea client for Rust programs." # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/gitea/README.md b/gitea/README.md new file mode 100644 index 0000000..d0a076f --- /dev/null +++ b/gitea/README.md @@ -0,0 +1,8 @@ +# gitea + +A simple Gitea client for Rust programs. You will need an API token as described +[here](https://docs.gitea.io/en-us/api-usage/). + +```toml +gitea = "0.1.0" +``` diff --git a/gitea/src/lib.rs b/gitea/src/lib.rs index e08c6fb..ce9d964 100644 --- a/gitea/src/lib.rs +++ b/gitea/src/lib.rs @@ -1,3 +1,5 @@ +/// The main Gitea client. You will need an API token as described [here](https://docs.gitea.io/en-us/api-usage/). + use reqwest::header; use serde::{Deserialize, Serialize}; use std::result::Result as StdResult; -- 2.44.0