summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorCyborus <cyborus@noreply.codeberg.org>2023-12-12 03:33:02 +0100
committerCyborus <cyborus@noreply.codeberg.org>2023-12-12 03:33:02 +0100
commiteeb0b421b19ad3ce97929519218cd22340b6907c (patch)
tree0a4978927e507bdff7355bb5891fee7b49d68a82
parentMerge pull request 'add CI' (#23) from testing into main (diff)
parentcheck release list before creating release (diff)
downloadforgejo-api-eeb0b421b19ad3ce97929519218cd22340b6907c.tar.xz
forgejo-api-eeb0b421b19ad3ce97929519218cd22340b6907c.zip
Merge pull request 'test repository methods' (#24) from repo-tests into main
Reviewed-on: https://codeberg.org/Cyborus/forgejo-api/pulls/24
-rw-r--r--.woodpecker/integration.yml4
-rw-r--r--Cargo.lock93
-rw-r--r--Cargo.toml4
-rw-r--r--src/lib.rs92
-rw-r--r--src/repository.rs21
-rw-r--r--tests/ci_test.rs121
6 files changed, 185 insertions, 150 deletions
diff --git a/.woodpecker/integration.yml b/.woodpecker/integration.yml
index f6df423..025fa7d 100644
--- a/.woodpecker/integration.yml
+++ b/.woodpecker/integration.yml
@@ -5,10 +5,10 @@ steps:
image: rust
environment:
- "FORGEJO_API_CI_INSTANCE_URL=http://forgejo-testing:3000/"
- - FORGEJO_API_CI_TOKEN=0889eabbb0006f15be4af017c4e0d3f51df78f98
+ - FORGEJO_API_CI_TOKEN=3226a46b52e29804bfb9b8ba21a5f91291fb86eb
commands:
- cargo test
services:
forgejo-testing:
- image: code.cartoon-aa.xyz/cyborus/ci-forgejo
+ image: code.cartoon-aa.xyz/cyborus/ci-forgejo:1.21.2-0
diff --git a/Cargo.lock b/Cargo.lock
index 436e2be..61464a5 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -74,7 +74,6 @@ version = "1.0.83"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1174fb0b6ec23863f8b971027804a42614e347eafb0a95bf0b12cdae21fc4d0"
dependencies = [
- "jobserver",
"libc",
]
@@ -171,9 +170,9 @@ name = "forgejo-api"
version = "0.1.0"
dependencies = [
"eyre",
- "git2",
"reqwest",
"serde",
+ "serde_json",
"soft_assert",
"thiserror",
"time",
@@ -236,21 +235,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6fb8d784f27acf97159b40fc4db5ecd8aa23b9ad5ef69cdd136d3bc80665f0c0"
[[package]]
-name = "git2"
-version = "0.18.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fbf97ba92db08df386e10c8ede66a2a0369bd277090afd8710e19e38de9ec0cd"
-dependencies = [
- "bitflags 2.4.1",
- "libc",
- "libgit2-sys",
- "log",
- "openssl-probe",
- "openssl-sys",
- "url",
-]
-
-[[package]]
name = "h2"
version = "0.3.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -385,15 +369,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38"
[[package]]
-name = "jobserver"
-version = "0.1.27"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8c37f63953c4c63420ed5fd3d6d398c719489b9f872b9fa683262f8edd363c7d"
-dependencies = [
- "libc",
-]
-
-[[package]]
name = "js-sys"
version = "0.3.65"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -415,46 +390,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "89d92a4743f9a61002fae18374ed11e7973f530cb3a3255fb354818118b2203c"
[[package]]
-name = "libgit2-sys"
-version = "0.16.1+1.7.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f2a2bb3680b094add03bb3732ec520ece34da31a8cd2d633d1389d0f0fb60d0c"
-dependencies = [
- "cc",
- "libc",
- "libssh2-sys",
- "libz-sys",
- "openssl-sys",
- "pkg-config",
-]
-
-[[package]]
-name = "libssh2-sys"
-version = "0.3.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2dc8a030b787e2119a731f1951d6a773e2280c660f8ec4b0f5e1505a386e71ee"
-dependencies = [
- "cc",
- "libc",
- "libz-sys",
- "openssl-sys",
- "pkg-config",
- "vcpkg",
-]
-
-[[package]]
-name = "libz-sys"
-version = "1.1.12"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d97137b25e321a73eef1418d1d5d2eda4d77e12813f8e6dead84bc52c5870a7b"
-dependencies = [
- "cc",
- "libc",
- "pkg-config",
- "vcpkg",
-]
-
-[[package]]
name = "linux-raw-sys"
version = "0.4.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -479,6 +414,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
[[package]]
+name = "mime_guess"
+version = "2.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4192263c238a5f0d0c6bfd21f336a313a4ce1c450542449ca191bb657b4642ef"
+dependencies = [
+ "mime",
+ "unicase",
+]
+
+[[package]]
name = "miniz_oxide"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -652,6 +597,7 @@ dependencies = [
"js-sys",
"log",
"mime",
+ "mime_guess",
"native-tls",
"once_cell",
"percent-encoding",
@@ -997,6 +943,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3528ecfd12c466c6f163363caf2d02a71161dd5e1cc6ae7b34207ea2d42d81ed"
[[package]]
+name = "unicase"
+version = "2.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f7d2d4dafb69621809a81864c9c1b864479e1235c0dd4e199924b9742439ed89"
+dependencies = [
+ "version_check",
+]
+
+[[package]]
name = "unicode-bidi"
version = "0.3.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -1036,6 +991,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
[[package]]
+name = "version_check"
+version = "0.9.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
+
+[[package]]
name = "want"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
diff --git a/Cargo.toml b/Cargo.toml
index 6989702..eb21559 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -6,15 +6,15 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
-reqwest = { version = "0.11.18", features = ["json"] }
+reqwest = { version = "0.11.18", features = ["json", "multipart"] }
soft_assert = "0.1.1"
thiserror = "1.0.43"
tokio = { version = "1.29.1", features = ["net"] }
url = { version = "2.4.0", features = ["serde"] }
serde = { version = "1.0.168", features = ["derive"] }
time = { version = "0.3.22", features = ["parsing", "serde", "formatting"] }
+serde_json = "1.0.108"
[dev-dependencies]
eyre = "0.6.9"
tokio = { version = "1.29.1", features = ["net", "fs", "rt", "macros"] }
-git2 = "0.18.1"
diff --git a/src/lib.rs b/src/lib.rs
index a6a7daf..bb0bd74 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -30,28 +30,18 @@ pub enum ForgejoError {
HostRequired,
#[error("scheme must be http or https")]
HttpRequired,
- #[error("{0}")] // for some reason, you can't use `source` and `transparent` together
- ReqwestError(#[source] reqwest::Error),
+ #[error(transparent)]
+ ReqwestError(#[from] reqwest::Error),
#[error("API key should be ascii")]
KeyNotAscii,
#[error("the response from forgejo was not properly structured")]
- BadStructure(#[source] reqwest::Error),
+ BadStructure(#[source] serde_json::Error, String),
#[error("unexpected status code {} {}", .0.as_u16(), .0.canonical_reason().unwrap_or(""))]
UnexpectedStatusCode(StatusCode),
#[error("{} {}: {}", .0.as_u16(), .0.canonical_reason().unwrap_or(""), .1)]
ApiError(StatusCode, String),
}
-impl From<reqwest::Error> for ForgejoError {
- fn from(e: reqwest::Error) -> Self {
- if e.is_decode() {
- ForgejoError::BadStructure(e)
- } else {
- ForgejoError::ReqwestError(e)
- }
- }
-}
-
impl Forgejo {
pub fn new(api_key: &str, url: Url) -> Result<Self, ForgejoError> {
Self::with_user_agent(api_key, url, "forgejo-api-rs")
@@ -98,6 +88,12 @@ impl Forgejo {
self.execute_str(request).await
}
+ async fn get_exists(&self, path: &str) -> Result<bool, ForgejoError> {
+ let url = self.url.join("api/v1/").unwrap().join(path).unwrap();
+ let request = self.client.get(url).build()?;
+ self.execute_exists(request).await
+ }
+
async fn post<T: Serialize, U: DeserializeOwned>(
&self,
path: &str,
@@ -108,13 +104,13 @@ impl Forgejo {
self.execute(request).await
}
- async fn post_form<T: Serialize, U: DeserializeOwned>(
+ async fn post_multipart<T: DeserializeOwned>(
&self,
path: &str,
- body: &T,
- ) -> Result<U, ForgejoError> {
+ body: reqwest::multipart::Form,
+ ) -> Result<T, ForgejoError> {
let url = self.url.join("api/v1/").unwrap().join(path).unwrap();
- let request = self.client.post(url).form(body).build()?;
+ let request = self.client.post(url).multipart(body).build()?;
self.execute(request).await
}
@@ -128,6 +124,16 @@ impl Forgejo {
self.execute_str(request).await
}
+ async fn post_unit<T: Serialize>(
+ &self,
+ path: &str,
+ body: &T,
+ ) -> Result<(), ForgejoError> {
+ let url = self.url.join("api/v1/").unwrap().join(path).unwrap();
+ let request = self.client.post(url).json(body).build()?;
+ self.execute_unit(request).await
+ }
+
async fn post_raw(
&self,
path: &str,
@@ -141,7 +147,7 @@ impl Forgejo {
async fn delete(&self, path: &str) -> Result<(), ForgejoError> {
let url = self.url.join("api/v1/").unwrap().join(path).unwrap();
let request = self.client.delete(url).build()?;
- self.execute(request).await
+ self.execute_unit(request).await
}
async fn patch<T: Serialize, U: DeserializeOwned>(
@@ -163,10 +169,14 @@ impl Forgejo {
async fn execute<T: DeserializeOwned>(&self, request: Request) -> Result<T, ForgejoError> {
let response = self.client.execute(request).await?;
match response.status() {
- status if status.is_success() => Ok(response.json::<T>().await?),
+ status if status.is_success() => {
+ let body = response.text().await?;
+ let out = serde_json::from_str(&body).map_err(|e| ForgejoError::BadStructure(e, body))?;
+ Ok(out)
+ },
status if status.is_client_error() => Err(ForgejoError::ApiError(
status,
- response.json::<ErrorMessage>().await?.message,
+ response.json::<ErrorMessage>().await?.message.unwrap_or_else(|| String::from("[no message]")),
)),
status => Err(ForgejoError::UnexpectedStatusCode(status)),
}
@@ -179,7 +189,20 @@ impl Forgejo {
status if status.is_success() => Ok(response.text().await?),
status if status.is_client_error() => Err(ForgejoError::ApiError(
status,
- response.json::<ErrorMessage>().await?.message,
+ response.json::<ErrorMessage>().await?.message.unwrap_or_else(|| String::from("[no message]")),
+ )),
+ status => Err(ForgejoError::UnexpectedStatusCode(status)),
+ }
+ }
+
+ /// Like `execute`, but returns unit.
+ async fn execute_unit(&self, request: Request) -> Result<(), ForgejoError> {
+ let response = self.client.execute(request).await?;
+ match response.status() {
+ status if status.is_success() => Ok(()),
+ status if status.is_client_error() => Err(ForgejoError::ApiError(
+ status,
+ response.json::<ErrorMessage>().await?.message.unwrap_or_else(|| String::from("[no message]")),
)),
status => Err(ForgejoError::UnexpectedStatusCode(status)),
}
@@ -192,11 +215,32 @@ impl Forgejo {
) -> Result<Option<T>, ForgejoError> {
let response = self.client.execute(request).await?;
match response.status() {
- status if status.is_success() => Ok(Some(response.json::<T>().await?)),
+ status if status.is_success() => {
+ let body = response.text().await?;
+ let out = serde_json::from_str(&body).map_err(|e| ForgejoError::BadStructure(e, body))?;
+ Ok(out)
+ },
StatusCode::NOT_FOUND => Ok(None),
status if status.is_client_error() => Err(ForgejoError::ApiError(
status,
- response.json::<ErrorMessage>().await?.message,
+ response.json::<ErrorMessage>().await?.message.unwrap_or_else(|| String::from("[no message]")),
+ )),
+ status => Err(ForgejoError::UnexpectedStatusCode(status)),
+ }
+ }
+
+ /// Like `execute`, but returns `false` on 404.
+ async fn execute_exists(
+ &self,
+ request: Request,
+ ) -> Result<bool, ForgejoError> {
+ let response = self.client.execute(request).await?;
+ match response.status() {
+ status if status.is_success() => Ok(true),
+ StatusCode::NOT_FOUND => Ok(false),
+ status if status.is_client_error() => Err(ForgejoError::ApiError(
+ status,
+ response.json::<ErrorMessage>().await?.message.unwrap_or_else(|| String::from("[no message]")),
)),
status => Err(ForgejoError::UnexpectedStatusCode(status)),
}
@@ -205,7 +249,7 @@ impl Forgejo {
#[derive(serde::Deserialize)]
struct ErrorMessage {
- message: String,
+ message: Option<String>,
// intentionally ignored, no need for now
// url: Url
}
diff --git a/src/repository.rs b/src/repository.rs
index 0564f5d..8b063a0 100644
--- a/src/repository.rs
+++ b/src/repository.rs
@@ -32,9 +32,7 @@ impl Forgejo {
}
pub async fn is_merged(&self, owner: &str, repo: &str, pr: u64) -> Result<bool, ForgejoError> {
- self.get_opt::<()>(&format!("repos/{owner}/{repo}/pulls/{pr}/merge"))
- .await
- .map(|o| o.is_some())
+ self.get_exists(&format!("repos/{owner}/{repo}/pulls/{pr}/merge")).await
}
pub async fn merge_pr(
@@ -44,7 +42,7 @@ impl Forgejo {
pr: u64,
opts: MergePullRequestOption,
) -> Result<(), ForgejoError> {
- self.post(&format!("repos/{owner}/{repo}/pulls/{pr}/merge"), &opts)
+ self.post_unit(&format!("repos/{owner}/{repo}/pulls/{pr}/merge"), &opts)
.await
}
@@ -142,11 +140,12 @@ impl Forgejo {
repo: &str,
id: u64,
name: &str,
- file: &[u8],
+ file: Vec<u8>,
) -> Result<Attachment, ForgejoError> {
- self.post_form(
+ self.post_multipart(
&format!("repos/{owner}/{repo}/releases/{id}/assets?name={name}"),
- &file,
+ reqwest::multipart::Form::new()
+ .part("attachment", reqwest::multipart::Part::bytes(file).file_name("file").mime_str("*/*").unwrap()),
)
.await
}
@@ -352,17 +351,17 @@ pub struct PullRequest {
pub is_locked: bool,
pub labels: Vec<Label>,
pub merge_base: String,
- pub merge_commit_sha: String,
+ pub merge_commit_sha: Option<String>,
pub mergeable: bool,
pub merged: bool,
#[serde(with = "time::serde::rfc3339::option")]
pub merged_at: Option<time::OffsetDateTime>,
- pub merged_by: User,
- pub milestone: Milestone,
+ pub merged_by: Option<User>,
+ pub milestone: Option<Milestone>,
pub number: u64,
pub patch_url: Url,
pub pin_order: u64,
- pub requested_reviewers: Vec<User>,
+ pub requested_reviewers: Option<Vec<User>>,
pub state: State,
pub title: String,
#[serde(with = "time::serde::rfc3339")]
diff --git a/tests/ci_test.rs b/tests/ci_test.rs
index 08ee904..52e5efe 100644
--- a/tests/ci_test.rs
+++ b/tests/ci_test.rs
@@ -1,5 +1,5 @@
use forgejo_api::Forgejo;
-use eyre::{eyre, ensure};
+use eyre::{eyre, ensure, WrapErr};
#[tokio::test]
async fn ci() -> eyre::Result<()> {
@@ -9,13 +9,20 @@ async fn ci() -> eyre::Result<()> {
let mut results = Vec::new();
- results.push(user(&api).await.map_err(|e| eyre!("user error: {e}")));
- results.push(repo(&api).await.map_err(|e| eyre!("repo error: {e}")));
+ results.push(user(&api).await.wrap_err("user error"));
+ results.push(repo(&api).await.wrap_err("repo error"));
let mut errors = 0;
- for res in results.into_iter().filter_map(Result::err) {
+ for report in results.into_iter().filter_map(Result::err) {
errors += 1;
- println!("{res}");
+ for (i, err) in report.chain().enumerate() {
+ println!("{i}. {err}");
+ if let Some(err) = err.downcast_ref::<forgejo_api::ForgejoError>() {
+ if let forgejo_api::ForgejoError::BadStructure(_, body) = err {
+ println!("BODY: {body}");
+ }
+ }
+ }
}
if errors > 0 {
eyre::bail!("test failed");
@@ -45,19 +52,19 @@ async fn user(api: &forgejo_api::Forgejo) -> eyre::Result<()> {
async fn repo(api: &forgejo_api::Forgejo) -> eyre::Result<()> {
tokio::fs::create_dir("/test_repo").await?;
- let local_repo = git2::Repository::init("/test_repo")?;
+ let git = || {
+ let mut cmd = std::process::Command::new("git");
+ cmd.current_dir("/test_repo");
+ cmd
+ };
+ let _ = git().args(["config", "--global", "init.defaultBranch", "main"]).status()?;
+ let _ = git().args(["init"]).status()?;
+ let _ = git().args(["config", "user.name", "TestingAdmin"]).status()?;
+ let _ = git().args(["config", "user.email", "admin@noreply.example.org"]).status()?;
tokio::fs::write("/test_repo/README.md", "# Test\nThis is a test repo").await?;
+ let _ = git().args(["add", "."]).status()?;
+ let _ = git().args(["commit", "-m", "initial commit"]).status()?;
- let mut index = local_repo.index()?;
- index.add_all(["."], git2::IndexAddOption::DEFAULT, None)?;
- index.write()?;
- let tree = local_repo.find_tree(index.write_tree().unwrap())?;
- let author = git2::Signature::now("TestingAdmin", "admin@noreply.example.org").unwrap();
- let commit_oid = local_repo.commit(None, &author, &author, "bibblybeebly", &tree, &[])?;
- let branch = local_repo.branch("main", &local_repo.find_commit(commit_oid).unwrap(), true)?;
- let branch_ref = branch.into_reference();
- let branch_ref_name = branch_ref.name().ok_or_else(|| eyre!("branch name not found"))?;
- local_repo.set_head(branch_ref_name)?;
let repo_opt = forgejo_api::CreateRepoOption {
auto_init: false,
@@ -73,36 +80,22 @@ async fn repo(api: &forgejo_api::Forgejo) -> eyre::Result<()> {
trust_model: forgejo_api::TrustModel::Default,
};
let remote_repo = api.create_repo(repo_opt).await?;
+ ensure!(remote_repo.has_pull_requests, "repo does not accept pull requests");
ensure!(remote_repo.owner.login == "TestingAdmin", "repo owner is not \"TestingAdmin\"");
ensure!(remote_repo.name == "test", "repo owner is not \"test\"");
+ tokio::time::sleep(std::time::Duration::from_secs(3)).await;
- let mut callbacks = git2::RemoteCallbacks::new();
- callbacks.credentials(|_url, _username_from_url, _allowed_types| {
- git2::Cred::userpass_plaintext("TestingAdmin", "password")
- });
- let mut push_options = git2::PushOptions::new();
- push_options.remote_callbacks(callbacks);
- let mut origin = local_repo.remote("origin", remote_repo.clone_url.as_str())?;
- origin.push(&[branch_ref_name], Some(&mut push_options))?;
+ let mut remote_url = remote_repo.clone_url.clone();
+ remote_url.set_username("TestingAdmin").unwrap();
+ remote_url.set_password(Some("password")).unwrap();
+ let _ = git().args(["remote", "add", "origin", remote_url.as_str()]).status()?;
+ let _ = git().args(["push", "-u", "origin", "main"]).status()?;
+ let _ = git().args(["switch", "-c", "test"]).status()?;
tokio::fs::write("/test_repo/example.rs", "fn add_one(x: u32) -> u32 { x + 1 }").await?;
- let mut index = local_repo.index()?;
- index.add_all(["."], git2::IndexAddOption::DEFAULT, None)?;
- index.write()?;
- let tree = local_repo.find_tree(index.write_tree().unwrap())?;
- let commit_oid = local_repo.commit(None, &author, &author, "egg", &tree, &[])?;
- let branch = local_repo.branch("test", &local_repo.find_commit(commit_oid).unwrap(), true)?;
- let branch_ref = branch.into_reference();
- let branch_ref_name = branch_ref.name().ok_or_else(|| eyre!("branch name not found"))?;
- local_repo.set_head(branch_ref_name)?;
-
- let mut callbacks = git2::RemoteCallbacks::new();
- callbacks.credentials(|_url, _username_from_url, _allowed_types| {
- git2::Cred::userpass_plaintext("TestingAdmin", "password")
- });
- let mut push_options = git2::PushOptions::new();
- push_options.remote_callbacks(callbacks);
- origin.push(&[branch_ref_name], Some(&mut push_options)).map_err(|e| eyre!("failed to push branch, {e}"))?;
+ let _ = git().args(["add", "."]).status()?;
+ let _ = git().args(["commit", "-m", "egg"]).status()?;
+ let _ = git().args(["push", "-u", "origin", "test"]).status()?;
let pr_opt = forgejo_api::CreatePullRequestOption {
assignee: None,
@@ -115,8 +108,9 @@ async fn repo(api: &forgejo_api::Forgejo) -> eyre::Result<()> {
milestone: None,
title: "test pr".into(),
};
- let pr = api.create_pr("TestingAdmin", "test", pr_opt).await.map_err(|e| eyre!("couldn't create pr, {e}"))?;
- let is_merged = api.is_merged("TestingAdmin", "test", pr.number).await.map_err(|e| eyre!("couldn't find unmerged pr {}, {}", pr.number, e))?;
+ let pr = api.create_pr("TestingAdmin", "test", pr_opt).await.wrap_err("couldn't create pr")?;
+ tokio::time::sleep(std::time::Duration::from_secs(3)).await;
+ let is_merged = api.is_merged("TestingAdmin", "test", pr.number).await.wrap_err_with(|| eyre!("couldn't find unmerged pr {}", pr.number))?;
ensure!(!is_merged, "pr should not yet be merged");
let merge_opt = forgejo_api::MergePullRequestOption {
act: forgejo_api::MergePrAction::Merge,
@@ -128,9 +122,46 @@ async fn repo(api: &forgejo_api::Forgejo) -> eyre::Result<()> {
head_commit_id: None,
merge_when_checks_succeed: None,
};
- api.merge_pr("TestingAdmin", "test", pr.number, merge_opt).await.map_err(|e| eyre!("couldn't merge pr {}, {}", pr.number, e))?;
- let is_merged = api.is_merged("TestingAdmin", "test", pr.number).await.map_err(|e| eyre!("couldn't find merged pr {}, {}", pr.number, e))?;
+ api.merge_pr("TestingAdmin", "test", pr.number, merge_opt).await.wrap_err_with(|| eyre!("couldn't merge pr {}", pr.number))?;
+ let is_merged = api.is_merged("TestingAdmin", "test", pr.number).await.wrap_err_with(|| eyre!("couldn't find merged pr {}", pr.number))?;
ensure!(is_merged, "pr should be merged");
+ let _ = git().args(["fetch"]).status()?;
+ let _ = git().args(["pull"]).status()?;
+
+ ensure!(api.get_releases("TestingAdmin", "test", forgejo_api::ReleaseQuery::default()).await.wrap_err("releases list not found")?.is_empty(), "there should be no releases yet");
+
+ let tag_opt = forgejo_api::CreateTagOption {
+ message: Some("This is a tag!".into()),
+ tag_name: "v1.0".into(),
+ target: None,
+ };
+ api.create_tag("TestingAdmin", "test", tag_opt).await.wrap_err("failed to create tag")?;
+
+ let release_opt = forgejo_api::CreateReleaseOption {
+ body: "This is a release!".into(),
+ draft: true,
+ name: "v1.0".into(),
+ prerelease: false,
+ tag_name: "v1.0".into(),
+ target_commitish: None,
+ };
+ let release = api.create_release("TestingAdmin", "test", release_opt).await.wrap_err("failed to create release")?;
+ let edit_release = forgejo_api::EditReleaseOption {
+ draft: Some(false),
+ ..Default::default()
+ };
+ api.edit_release("TestingAdmin", "test", release.id, edit_release).await.wrap_err("failed to edit release")?;
+
+ let release_by_tag = api.get_release_by_tag("TestingAdmin", "test", "v1.0").await.wrap_err("failed to find release")?;
+ let release_latest = api.latest_release("TestingAdmin", "test").await.wrap_err("failed to find latest release")?;
+ ensure!(release_by_tag == release_latest, "releases not equal");
+
+ let attachment = api.create_release_attachment("TestingAdmin", "test", release.id, "test.txt", b"This is a file!".to_vec()).await.wrap_err("failed to create release attachment")?;
+ api.delete_release_attachment("TestingAdmin", "test", release.id, attachment.id).await.wrap_err("failed to deleted attachment")?;
+
+ api.delete_release("TestingAdmin", "test", release.id).await.wrap_err("failed to delete release")?;
+
+ api.delete_tag("TestingAdmin", "test", "v1.0").await.wrap_err("failed to delete release")?;
Ok(())
}