From bc608f7ddc1cce0e44e735737b4c6b4d6bd5d19b Mon Sep 17 00:00:00 2001 From: Christine Dodrill Date: Thu, 9 Jul 2020 11:31:09 -0400 Subject: [PATCH 1/5] support pulling, refactor git module --- src/cmd/cut.rs | 5 +-- src/cmd/mod.rs | 29 +++++++++++++++++ src/git.rs | 84 ++++++++++++++++++++++++++++++++++++++------------ 3 files changed, 96 insertions(+), 22 deletions(-) diff --git a/src/cmd/cut.rs b/src/cmd/cut.rs index 2324ab3..819dbcd 100644 --- a/src/cmd/cut.rs +++ b/src/cmd/cut.rs @@ -11,10 +11,11 @@ pub(crate) async fn run( let repo = git2::Repository::open(".")?; let tag = tag.unwrap_or(version::read_version("VERSION".into())?); let desc = changelog::read(fname.clone(), tag.clone())?; + let sig = git2::Signature::now(&common.username, &common.email)?; if !git::has_tag(&repo, tag.clone())? { - git::tag_version(&repo, tag.clone(), desc.clone())?; - let _ = git::push_tags(&repo); + git::tag_version(&repo, tag.clone(), desc.clone(), &sig)?; + let _ = git::push(&repo, common.token.clone(), git::TAGS); } else /* The tag already exists */ { diff --git a/src/cmd/mod.rs b/src/cmd/mod.rs index d94fab6..7b58015 100644 --- a/src/cmd/mod.rs +++ b/src/cmd/mod.rs @@ -9,18 +9,30 @@ pub(crate) struct Common { /// The gitea server to connect to #[structopt(short, long, env = "GITEA_SERVER")] pub server: String, + /// The gitea token to authenticate with #[structopt(long, env = "GITEA_TOKEN")] pub token: String, + /// The gitea user to authenticate as #[structopt(short, long, env = "GITEA_AUTH_USER")] pub auth_user: String, + /// The owner of the gitea repo #[structopt(short, long, env = "GITEA_OWNER")] pub owner: String, + /// The gitea repo to operate on #[structopt(short, long, env = "GITEA_REPO")] pub repo: String, + + /// Git signature email + #[structopt(long, short = "E", env = "SIGNATURE_EMAIL", default_value = "domo@tulpa.dev")] + pub email: String, + + /// Git signature username + #[structopt(long, short = "U", env = "SIGNATURE_NAME", default_value = "Domo Arigato")] + pub username: String, } #[derive(StructOpt, Debug, Clone)] @@ -29,12 +41,15 @@ pub(crate) struct DroneEnv { /// push URL #[structopt(long, env = "DRONE_GIT_HTTP_URL")] pub push_url: String, + /// repo owner #[structopt(long, env = "DRONE_REPO_OWNER")] pub owner: String, + /// repo name #[structopt(long, env = "DRONE_REPO_NAME")] pub repo: String, + /// branch #[structopt(long, env = "DRONE_REPO_BRANCH")] pub branch: String, @@ -43,18 +58,30 @@ pub(crate) struct DroneEnv { /// auth username #[structopt(long, env = "PLUGIN_AUTH_USERNAME")] pub auth_user: String, + /// Gitea server #[structopt(long, env = "PLUGIN_GITEA_SERVER")] pub server: String, + /// Gitea token #[structopt(long, env = "PLUGIN_GITEA_TOKEN")] pub token: String, + /// CHANGELOG path #[structopt(long, env = "PLUGIN_CHANGELOG_PATH", default_value = "./CHANGELOG.md")] pub changelog_path: PathBuf, + /// Default branch name #[structopt(long, env = "PLUGIN_DEFAULT_BRANCH")] pub default_branch: Option, + + /// Git signature email + #[structopt(long, short = "E", env = "PLUGIN_SIGNATURE_EMAIL", default_value = "domo@tulpa.dev")] + pub email: String, + + /// Git signature username + #[structopt(long, short = "U", env = "PLUGIN_SIGNATURE_NAME", default_value = "Domo Arigato")] + pub username: String, } impl Into for DroneEnv { @@ -65,6 +92,8 @@ impl Into for DroneEnv { auth_user: self.auth_user, owner: self.owner, repo: self.repo, + email: self.email, + username: self.username, } } } diff --git a/src/git.rs b/src/git.rs index de7447b..dabd4a3 100644 --- a/src/git.rs +++ b/src/git.rs @@ -1,22 +1,77 @@ use anyhow::Result; use git2::{Repository, Signature}; +use std::path::Path; -pub(crate) fn push_tags(repo: &Repository) -> Result<()> { +pub const TAGS: &'static [&'static str] = &["refs/tags/*:refs/tags/*"]; + +pub fn pull(repo: &Repository, token: String, what: &[&str]) -> Result<()> { let mut remote = repo.find_remote("origin")?; - remote.connect(git2::Direction::Push)?; - remote.push(&["refs/tags/*:refs/tags/*"], None)?; + let mut fo = git2::FetchOptions::new(); + + let mut callbacks = git2::RemoteCallbacks::new(); + callbacks.credentials(|_u, _username, allowed_types| { + if allowed_types.contains(git2::CredentialType::SSH_KEY) { + let user = "git"; + git2::Cred::ssh_key_from_agent(user) + } else { + git2::Cred::userpass_plaintext(&token, "") + } + }); + + fo.remote_callbacks(callbacks); + + remote.connect(git2::Direction::Fetch)?; + remote.fetch(what, Some(&mut fo), None)?; Ok(()) } -pub(crate) fn tag_version(repo: &Repository, tag: String, desc: String) -> Result<()> { - let sig = &Signature::now("Gitea Release Tool", "gitea-release@tulpa.dev")?; +pub fn push(repo: &Repository, token: String, what: &[&str]) -> Result<()> { + let mut remote = repo.find_remote("origin")?; + let mut po = git2::PushOptions::new(); + + let mut callbacks = git2::RemoteCallbacks::new(); + callbacks.credentials(|_u, _username, allowed_types| { + if allowed_types.contains(git2::CredentialType::SSH_KEY) { + let user = "git"; + git2::Cred::ssh_key_from_agent(user) + } else { + git2::Cred::userpass_plaintext(&token, "") + } + }); + + po.remote_callbacks(callbacks); + + remote.connect(git2::Direction::Push)?; + remote.push(what, Some(&mut po))?; + Ok(()) +} + +pub fn commit( + repo: &Repository, + sig: &git2::Signature, + msg: &str, + files: &[&str], +) -> Result<()> { + let mut index = repo.index()?; + for file in files { + index.add_path(Path::new(file))?; + } + + let oid = index.write_tree()?; + let tree = repo.find_tree(oid)?; + repo.commit(Some("HEAD"), &sig, &sig, &msg, &tree, &[])?; + + Ok(()) +} + +pub fn tag_version(repo: &Repository, tag: String, desc: String, sig: &git2::Signature) -> Result<()> { let obj = repo.revparse_single("HEAD")?; repo.tag(&tag, &obj, &sig, &desc, false)?; Ok(()) } -pub(crate) fn has_tag(repo: &Repository, tag: String) -> Result { +pub fn has_tag(repo: &Repository, tag: String) -> Result { let tags = repo.tag_names(Some(&tag))?; for tag_obj in tags.iter() { @@ -37,7 +92,7 @@ pub(crate) fn has_tag(repo: &Repository, tag: String) -> Result { mod tests { use anyhow::Result; use git2::*; - use std::{fs::File, io::Write, path::Path}; + use std::{fs::File, io::Write}; use tempfile::tempdir; #[test] @@ -48,22 +103,11 @@ mod tests { let mut fout = File::create(&dir.path().join("VERSION"))?; write!(fout, "{}", TAG)?; drop(fout); - let mut index = repo.index()?; - index.add_path(Path::new("VERSION"))?; - let oid = index.write_tree()?; - let tree = repo.find_tree(oid)?; let sig = &Signature::now("Gitea Release Tool", "gitea-release@tulpa.dev")?; - repo.commit( - Some("HEAD"), - &sig, - &sig, - "test commit please ignore", - &tree, - &[], - )?; + super::commit(&repo, &sig, "test commit please ignore", &["VERSION"])?; - super::tag_version(&repo, TAG.into(), format!("version {}", TAG))?; + super::tag_version(&repo, TAG.into(), format!("version {}", TAG), &sig)?; assert!(super::has_tag(&repo, TAG.into())?); Ok(()) From 2cc49b86db7a35b1b8b26969bad2729b31ce7621 Mon Sep 17 00:00:00 2001 From: Christine Dodrill Date: Thu, 9 Jul 2020 11:35:49 -0400 Subject: [PATCH 2/5] more refactoring --- src/cmd/cut.rs | 2 +- src/git.rs | 38 ++++++++++++++++++-------------------- 2 files changed, 19 insertions(+), 21 deletions(-) diff --git a/src/cmd/cut.rs b/src/cmd/cut.rs index 819dbcd..450f838 100644 --- a/src/cmd/cut.rs +++ b/src/cmd/cut.rs @@ -14,7 +14,7 @@ pub(crate) async fn run( let sig = git2::Signature::now(&common.username, &common.email)?; if !git::has_tag(&repo, tag.clone())? { - git::tag_version(&repo, tag.clone(), desc.clone(), &sig)?; + git::tag_version(&repo, &sig, tag.clone(), desc.clone())?; let _ = git::push(&repo, common.token.clone(), git::TAGS); } else /* The tag already exists */ diff --git a/src/git.rs b/src/git.rs index dabd4a3..2578d97 100644 --- a/src/git.rs +++ b/src/git.rs @@ -1,57 +1,55 @@ use anyhow::Result; -use git2::{Repository, Signature}; +use git2::{ + Cred, CredentialType, Direction, FetchOptions, PushOptions, RemoteCallbacks, Repository, + Signature, +}; use std::path::Path; pub const TAGS: &'static [&'static str] = &["refs/tags/*:refs/tags/*"]; pub fn pull(repo: &Repository, token: String, what: &[&str]) -> Result<()> { let mut remote = repo.find_remote("origin")?; - let mut fo = git2::FetchOptions::new(); + let mut fo = FetchOptions::new(); - let mut callbacks = git2::RemoteCallbacks::new(); + let mut callbacks = RemoteCallbacks::new(); callbacks.credentials(|_u, _username, allowed_types| { - if allowed_types.contains(git2::CredentialType::SSH_KEY) { + if allowed_types.contains(CredentialType::SSH_KEY) { let user = "git"; - git2::Cred::ssh_key_from_agent(user) + Cred::ssh_key_from_agent(user) } else { - git2::Cred::userpass_plaintext(&token, "") + Cred::userpass_plaintext(&token, "") } }); fo.remote_callbacks(callbacks); - remote.connect(git2::Direction::Fetch)?; + remote.connect(Direction::Fetch)?; remote.fetch(what, Some(&mut fo), None)?; Ok(()) } pub fn push(repo: &Repository, token: String, what: &[&str]) -> Result<()> { let mut remote = repo.find_remote("origin")?; - let mut po = git2::PushOptions::new(); + let mut po = PushOptions::new(); - let mut callbacks = git2::RemoteCallbacks::new(); + let mut callbacks = RemoteCallbacks::new(); callbacks.credentials(|_u, _username, allowed_types| { - if allowed_types.contains(git2::CredentialType::SSH_KEY) { + if allowed_types.contains(CredentialType::SSH_KEY) { let user = "git"; - git2::Cred::ssh_key_from_agent(user) + Cred::ssh_key_from_agent(user) } else { - git2::Cred::userpass_plaintext(&token, "") + Cred::userpass_plaintext(&token, "") } }); po.remote_callbacks(callbacks); - remote.connect(git2::Direction::Push)?; + remote.connect(Direction::Push)?; remote.push(what, Some(&mut po))?; Ok(()) } -pub fn commit( - repo: &Repository, - sig: &git2::Signature, - msg: &str, - files: &[&str], -) -> Result<()> { +pub fn commit(repo: &Repository, sig: &Signature, msg: &str, files: &[&str]) -> Result<()> { let mut index = repo.index()?; for file in files { index.add_path(Path::new(file))?; @@ -64,7 +62,7 @@ pub fn commit( Ok(()) } -pub fn tag_version(repo: &Repository, tag: String, desc: String, sig: &git2::Signature) -> Result<()> { +pub fn tag_version(repo: &Repository, sig: &Signature, tag: String, desc: String) -> Result<()> { let obj = repo.revparse_single("HEAD")?; repo.tag(&tag, &obj, &sig, &desc, false)?; From d5b7b59e3ee8b40406505d7aada592ad220a9a81 Mon Sep 17 00:00:00 2001 From: Christine Dodrill Date: Thu, 9 Jul 2020 11:46:13 -0400 Subject: [PATCH 3/5] expose functionality as a crate for testing --- src/cmd/cut.rs | 2 +- src/cmd/drone_plugin.rs | 2 +- src/cmd/mod.rs | 12 ++++++------ src/lib.rs | 8 ++++++++ src/main.rs | 11 +---------- 5 files changed, 17 insertions(+), 18 deletions(-) create mode 100644 src/lib.rs diff --git a/src/cmd/cut.rs b/src/cmd/cut.rs index 450f838..9cfe7e3 100644 --- a/src/cmd/cut.rs +++ b/src/cmd/cut.rs @@ -2,7 +2,7 @@ use crate::{changelog, cmd::*, git, version}; use anyhow::Result; use std::path::PathBuf; -pub(crate) async fn run( +pub async fn run( common: Common, fname: PathBuf, tag: Option, diff --git a/src/cmd/drone_plugin.rs b/src/cmd/drone_plugin.rs index 57e1b06..706cf16 100644 --- a/src/cmd/drone_plugin.rs +++ b/src/cmd/drone_plugin.rs @@ -3,7 +3,7 @@ use anyhow::Result; use git2::Repository; use url::Url; -pub(crate) async fn run(env: DroneEnv) -> Result<()> { +pub async fn run(env: DroneEnv) -> Result<()> { let common: Common = env.clone().into(); let default_branch = { diff --git a/src/cmd/mod.rs b/src/cmd/mod.rs index 7b58015..20cdfcc 100644 --- a/src/cmd/mod.rs +++ b/src/cmd/mod.rs @@ -1,11 +1,11 @@ use std::path::PathBuf; use structopt::StructOpt; -pub(crate) mod cut; -pub(crate) mod drone_plugin; +pub mod cut; +pub mod drone_plugin; #[derive(StructOpt, Debug, Clone)] -pub(crate) struct Common { +pub struct Common { /// The gitea server to connect to #[structopt(short, long, env = "GITEA_SERVER")] pub server: String, @@ -36,7 +36,7 @@ pub(crate) struct Common { } #[derive(StructOpt, Debug, Clone)] -pub(crate) struct DroneEnv { +pub struct DroneEnv { // Given by drone /// push URL #[structopt(long, env = "DRONE_GIT_HTTP_URL")] @@ -99,7 +99,7 @@ impl Into for DroneEnv { } #[derive(StructOpt, Debug)] -pub(crate) struct ReleaseMeta { +pub struct ReleaseMeta { /// Release name #[structopt(short, long)] pub name: Option, @@ -113,7 +113,7 @@ pub(crate) struct ReleaseMeta { #[derive(StructOpt, Debug)] #[structopt(about = "Gitea release assistant")] -pub(crate) enum Cmd { +pub enum Cmd { /// Create a new tag and release on Gitea #[structopt(alias = "release")] Cut { diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..356cc3b --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,8 @@ +pub mod changelog; +pub mod cmd; +pub mod git; +pub mod version; + +// Name your user agent after your app? +pub static APP_USER_AGENT: &str = + concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")); diff --git a/src/main.rs b/src/main.rs index dae376e..271bb06 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,16 +1,7 @@ use anyhow::Result; use structopt::StructOpt; -mod changelog; -mod cmd; -mod git; -mod version; - -pub(crate) use cmd::*; - -// Name your user agent after your app? -pub(crate) static APP_USER_AGENT: &str = - concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")); +use ::gitea_release::{cmd::{self, Cmd}}; #[tokio::main] async fn main() -> Result<()> { From cbf0e9d308fc7ace9788fa18ecbc19b0499909dc Mon Sep 17 00:00:00 2001 From: Christine Dodrill Date: Thu, 9 Jul 2020 13:06:07 -0400 Subject: [PATCH 4/5] end to end test --- Cargo.lock | 58 +++++++++++++++++++++++++++++ Cargo.toml | 2 + gitea/src/lib.rs | 67 ++++++++++++++++++++++++++++++++- src/cmd/cut.rs | 14 ++----- src/git.rs | 38 ++++++++----------- src/main.rs | 2 +- tests/cut.rs | 96 ++++++++++++++++++++++++++++++++++++++++++++++++ 7 files changed, 242 insertions(+), 35 deletions(-) create mode 100644 tests/cut.rs diff --git a/Cargo.lock b/Cargo.lock index dc72d90..956e74c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -198,6 +198,19 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b5320ae4c3782150d900b79807611a59a99fc9a1d61d686faafc24b93fc8d7ca" +[[package]] +name = "env_logger" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44533bbbb3bb3c1fa17d9f2e4e38bbbaf8396ba82193c4cb1b6445d711445d36" +dependencies = [ + "atty", + "humantime", + "log", + "regex", + "termcolor", +] + [[package]] name = "fake-simd" version = "0.1.2" @@ -344,6 +357,8 @@ dependencies = [ "gitea", "http", "kankyo", + "log", + "pretty_env_logger", "reqwest", "serde", "serde_json", @@ -417,6 +432,15 @@ version = "1.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cd179ae861f0c2e53da70d892f5f3029f9594be0c41dc5269cd371691b1dc2f9" +[[package]] +name = "humantime" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df004cfca50ef23c36850aaaa59ad52cc70d0e90243c3c7737a4dd32dc7a3c4f" +dependencies = [ + "quick-error", +] + [[package]] name = "hyper" version = "0.13.6" @@ -819,6 +843,16 @@ version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "237a5ed80e274dbc66f86bd59c1e25edc039660be53194b5fe0a482e0f2612ea" +[[package]] +name = "pretty_env_logger" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "926d36b9553851b8b0005f1275891b392ee4d2d833852c417ed025477350fb9d" +dependencies = [ + "env_logger", + "log", +] + [[package]] name = "proc-macro-error" version = "1.0.2" @@ -854,6 +888,12 @@ dependencies = [ "unicode-xid", ] +[[package]] +name = "quick-error" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" + [[package]] name = "quote" version = "1.0.6" @@ -1203,6 +1243,15 @@ 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" @@ -1552,6 +1601,15 @@ 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 8b39d15..d3d1ce8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,7 @@ comrak = "0.7" git2 = "0.13" http = "0.2" kankyo = "0.3" +log = "0.4" reqwest = { version = "0.10", features = ["json"] } serde_json = "1.0" serde = { version = "1.0", features = ["derive"] } @@ -24,6 +25,7 @@ gitea = { path = "./gitea" } [dev-dependencies] tempfile = "3" elfs = { path = "./elfs" } +pretty_env_logger = "0.4" [profile.release] lto = true diff --git a/gitea/src/lib.rs b/gitea/src/lib.rs index ce9d964..eeac0fc 100644 --- a/gitea/src/lib.rs +++ b/gitea/src/lib.rs @@ -1,5 +1,4 @@ /// 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; @@ -70,6 +69,20 @@ pub struct Attachment { pub browser_download_url: String, } +/// Inputs to create a gitea repo. +/// https://try.gitea.io/api/swagger#model-CreateRepoOption +#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct CreateRepo { + pub auto_init: bool, + pub description: String, + pub gitignores: String, + pub issue_labels: String, + pub license: String, + pub name: String, + pub private: bool, + pub readme: String, +} + /// A git repository. /// https://try.gitea.io/api/swagger#model-Repository #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -234,6 +247,46 @@ impl Client { } } + /// Creates a new gitea repo for the currently authenticated user with given details. + pub async fn create_user_repo(&self, cr: CreateRepo) -> Result { + Ok(self + .cli + .post(&format!("{}/api/v1/user/repos", self.base_url)) + .json(&cr) + .send() + .await? + .error_for_status()? + .json() + .await?) + } + + /// Creates a new gitea repo for a given organization with given details. + pub async fn create_org_repo(&self, org: String, cr: CreateRepo) -> Result { + Ok(self + .cli + .post(&format!("{}/api/v1/org/{}/repos", self.base_url, org)) + .json(&cr) + .send() + .await? + .error_for_status()? + .json() + .await?) + } + + /// Deletes a gitea repo by owner and name. + pub async fn delete_repo(&self, owner: String, repo: String) -> Result<()> { + self.cli + .delete(&format!( + "{}/api/v1/repos/{}/{}", + self.base_url, owner, repo + )) + .send() + .await? + .error_for_status()?; + + Ok(()) + } + /// Gets a gitea repo by name. /// /// ```rust @@ -357,4 +410,16 @@ impl Client { Ok(()) } + + /// Returns information about the currently authenticated user. + pub async fn whoami(&self) -> Result { + Ok(self + .cli + .get(&format!("{}/api/v1/user", self.base_url)) + .send() + .await? + .error_for_status()? + .json() + .await?) + } } diff --git a/src/cmd/cut.rs b/src/cmd/cut.rs index 9cfe7e3..636857d 100644 --- a/src/cmd/cut.rs +++ b/src/cmd/cut.rs @@ -10,21 +10,15 @@ pub async fn run( ) -> Result<()> { let repo = git2::Repository::open(".")?; let tag = tag.unwrap_or(version::read_version("VERSION".into())?); - let desc = changelog::read(fname.clone(), tag.clone())?; - let sig = git2::Signature::now(&common.username, &common.email)?; - if !git::has_tag(&repo, tag.clone())? { - git::tag_version(&repo, &sig, tag.clone(), desc.clone())?; - let _ = git::push(&repo, common.token.clone(), git::TAGS); - } else - /* The tag already exists */ - { - return Ok(()); + if git::has_tag(&repo, tag.clone())? { + return Err(anyhow::anyhow!("what")); } 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 repo = cli.get_repo(common.owner.clone(), common.repo.clone()).await?; let cr = gitea::CreateRelease { body: desc, @@ -32,7 +26,7 @@ pub async fn run( name: rm.name.or(Some(format!("Version {}", tag))).unwrap(), prerelease: rm.pre_release, tag_name: vtag, - target_commitish: "HEAD".into(), + target_commitish: repo.default_branch, }; let _ = cli.create_release(common.owner, common.repo, cr).await?; diff --git a/src/git.rs b/src/git.rs index 2578d97..d56676e 100644 --- a/src/git.rs +++ b/src/git.rs @@ -11,40 +11,32 @@ pub fn pull(repo: &Repository, token: String, what: &[&str]) -> Result<()> { let mut remote = repo.find_remote("origin")?; let mut fo = FetchOptions::new(); - let mut callbacks = RemoteCallbacks::new(); - callbacks.credentials(|_u, _username, allowed_types| { - if allowed_types.contains(CredentialType::SSH_KEY) { - let user = "git"; - Cred::ssh_key_from_agent(user) - } else { - Cred::userpass_plaintext(&token, "") - } - }); - - fo.remote_callbacks(callbacks); - - remote.connect(Direction::Fetch)?; + remote.connect_auth(Direction::Fetch, Some(callbacks(token.clone())), None)?; + fo.remote_callbacks(callbacks(token)); remote.fetch(what, Some(&mut fo), None)?; Ok(()) } -pub fn push(repo: &Repository, token: String, what: &[&str]) -> Result<()> { - let mut remote = repo.find_remote("origin")?; - let mut po = PushOptions::new(); - +fn callbacks<'a>(token: String) -> RemoteCallbacks<'a> { let mut callbacks = RemoteCallbacks::new(); - callbacks.credentials(|_u, _username, allowed_types| { + callbacks.credentials(move |_u, _username, allowed_types| { if allowed_types.contains(CredentialType::SSH_KEY) { let user = "git"; Cred::ssh_key_from_agent(user) } else { - Cred::userpass_plaintext(&token, "") + Cred::userpass_plaintext(&token, "x-oauth-basic") } }); + callbacks +} - po.remote_callbacks(callbacks); +pub fn push(repo: &Repository, token: String, what: &[&str]) -> Result<()> { + let mut remote = repo.find_remote("origin")?; - remote.connect(Direction::Push)?; + remote.connect_auth(Direction::Push, Some(callbacks(token.clone())), None)?; + + let mut po = PushOptions::new(); + po.remote_callbacks(callbacks(token)); remote.push(what, Some(&mut po))?; Ok(()) } @@ -78,6 +70,7 @@ pub fn has_tag(repo: &Repository, tag: String) -> Result { } let tag_name = tag_obj.unwrap(); + log::debug!("tag: {}", tag_name.to_string()); if tag == tag_name.to_string() { return Ok(true); } @@ -104,8 +97,7 @@ mod tests { let sig = &Signature::now("Gitea Release Tool", "gitea-release@tulpa.dev")?; super::commit(&repo, &sig, "test commit please ignore", &["VERSION"])?; - - super::tag_version(&repo, TAG.into(), format!("version {}", TAG), &sig)?; + super::tag_version(&repo, &sig, TAG.into(), format!("version {}", TAG))?; assert!(super::has_tag(&repo, TAG.into())?); Ok(()) diff --git a/src/main.rs b/src/main.rs index 271bb06..8330fab 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,7 +6,7 @@ use ::gitea_release::{cmd::{self, Cmd}}; #[tokio::main] async fn main() -> Result<()> { let _ = kankyo::init(); - let cmd = cmd::Cmd::from_args(); + let cmd = Cmd::from_args(); match cmd { Cmd::Cut { diff --git a/tests/cut.rs b/tests/cut.rs new file mode 100644 index 0000000..7ed6008 --- /dev/null +++ b/tests/cut.rs @@ -0,0 +1,96 @@ +use ::gitea_release::{cmd, git, APP_USER_AGENT}; +use anyhow::Result; +use git2::{Repository, Signature}; +use log::debug; +use std::{fs::File, io::Write}; + +const TAG: &'static str = "0.1.0"; + +#[tokio::test] +async fn cut() -> Result<()> { + let _ = pretty_env_logger::try_init(); + let name = elfs::next(); + let token = std::env::var("DOMO_GITEA_TOKEN")?; + + let cli = gitea::Client::new("https://tulpa.dev".into(), token.clone(), APP_USER_AGENT)?; + debug!("created gitea client"); + + let gitea_repo = cli + .create_user_repo(gitea::CreateRepo { + auto_init: false, + description: format!("https://tulpa.dev/cadey/gitea-release test repo"), + gitignores: "".into(), + issue_labels: "".into(), + license: "".into(), + name: name.clone(), + private: true, + readme: "".into(), + }) + .await?; + debug!("created repo domo/{}", name); + + let dir = tempfile::tempdir()?; + let repo = Repository::init(&dir)?; + let sig = &Signature::now("Domo Arigato", "domo@tulpa.dev")?; + debug!("initialized repo in {:?}", dir.path()); + + let mut fout = File::create(&dir.path().join("VERSION"))?; + write!(fout, "{}", TAG)?; + drop(fout); + + let mut fout = File::create(&dir.path().join("CHANGELOG.md"))?; + fout.write_all(include_bytes!("../testdata/basic.md"))?; + drop(fout); + + git::commit(&repo, &sig, TAG.into(), &["VERSION", "CHANGELOG.md"])?; + debug!("committed files"); + + repo.remote("origin", &gitea_repo.clone_url)?; + debug!("set up origin remote to {}", gitea_repo.clone_url); + + git::push( + &repo, + token.clone(), + &["refs/heads/master:refs/heads/master"], + )?; + debug!("pushed to {} with token {}", gitea_repo.clone_url, token); + + std::env::set_current_dir(dir.path())?; + cmd::cut::run( + cmd::Common { + server: "https://tulpa.dev".into(), + token: token, + auth_user: gitea_repo.owner.login.clone(), + owner: gitea_repo.owner.login.clone(), + repo: gitea_repo.name, + email: "domo@tulpa.dev".into(), + username: "Domo Arigato".into(), + }, + "CHANGELOG.md".into(), + None, + cmd::ReleaseMeta { + name: None, + draft: false, + pre_release: false, + }, + ) + .await?; + + let rls = cli + .get_release_by_tag( + gitea_repo.owner.login.clone(), + name.clone(), + format!("v{}", TAG), + ) + .await?; + + assert_eq!( + rls.body, + "Hi there this is a test\\!\n### ADDED\n - something\n" + ); + + cli.delete_repo(gitea_repo.owner.login, name).await?; + debug!("deleted repo {}", gitea_repo.clone_url); + + Ok(()) +} From 3846c349c46abed9dadad69bba2ce3923e72236f Mon Sep 17 00:00:00 2001 From: Christine Dodrill Date: Thu, 9 Jul 2020 13:09:30 -0400 Subject: [PATCH 5/5] prepare release --- CHANGELOG.md | 20 ++++++++++++++++++++ Cargo.lock | 4 ++-- Cargo.toml | 2 +- VERSION | 2 +- gitea/Cargo.toml | 2 +- 5 files changed, 25 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9a98ab1..65e44a9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## Unreleased +## 0.5.0 + +A lot of internals to this program were exposed to external consumers. This was +used to provide an integration test. + +Support for bracketed versions was added, a-la: + +```markdown +## [0.1.0] + +Hi there this is a test! + +### ADDED + +- something +``` + +The gitea crate was brought up to version `0.2.0` and includes a lot more +functionality. + ## 0.4.0 This is a functionality-breaking release that removes untested/extraneous parts diff --git a/Cargo.lock b/Cargo.lock index 956e74c..276a6d1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -336,7 +336,7 @@ dependencies = [ [[package]] name = "gitea" -version = "0.1.0" +version = "0.2.0" dependencies = [ "anyhow", "reqwest", @@ -348,7 +348,7 @@ dependencies = [ [[package]] name = "gitea-release" -version = "0.3.2" +version = "0.5.0" dependencies = [ "anyhow", "comrak", diff --git a/Cargo.toml b/Cargo.toml index d3d1ce8..b3380c5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "gitea-release" -version = "0.3.2" +version = "0.5.0" authors = ["Christine Dodrill "] edition = "2018" diff --git a/VERSION b/VERSION index 1d0ba9e..8f0916f 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.4.0 +0.5.0 diff --git a/gitea/Cargo.toml b/gitea/Cargo.toml index e43d767..13a69e4 100644 --- a/gitea/Cargo.toml +++ b/gitea/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "gitea" -version = "0.1.0" +version = "0.2.0" authors = ["Christine Dodrill "] edition = "2018" homepage = "https://tulpa.dev/cadey/gitea-release/src/branch/main/gitea"