1
0
Fork 0

Adding upstream version 0.4.1.

Signed-off-by: Daniel Baumann <daniel@debian.org>
This commit is contained in:
Daniel Baumann 2025-02-05 05:23:13 +01:00
parent bc9f87646a
commit f4a13f7987
Signed by: daniel
GPG key ID: FBB4F0E80A80222F
19 changed files with 41510 additions and 0 deletions

6
.cargo_vcs_info.json Normal file
View file

@ -0,0 +1,6 @@
{
"git": {
"sha1": "ecbc505270cabdbd34402c0c118cb35df53ff257"
},
"path_in_vcs": ""
}

2
.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
/target
/test_repos

13
.woodpecker/check.yml Normal file
View file

@ -0,0 +1,13 @@
when:
- event: manual
- event: pull_request
steps:
check:
image: rust
commands:
- cargo check
check-fmt:
image: rust
commands:
- rustup component add rustfmt
- cargo fmt --check

View file

@ -0,0 +1,15 @@
when:
- event: manual
steps:
test:
image: rust
environment:
- "FORGEJO_API_CI_INSTANCE_URL=http://forgejo-testing:3000/"
- FORGEJO_API_CI_TOKEN=e4f301dffd4993a3389f601761c0103291e58d85
commands:
- cargo test
services:
forgejo-testing:
pull: true
image: code.cartoon-aa.xyz/cyborus/ci-forgejo:8.0.0

105
Cargo.toml Normal file
View file

@ -0,0 +1,105 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2021"
name = "forgejo-api"
version = "0.4.1"
build = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "Interface to Forgejo's Web API"
readme = "README.md"
license = "Apache-2.0 OR MIT"
repository = "https://codeberg.org/Cyborus/forgejo-api"
[lib]
name = "forgejo_api"
path = "src/lib.rs"
[[test]]
name = "admin"
path = "tests/admin.rs"
[[test]]
name = "organization"
path = "tests/organization.rs"
[[test]]
name = "repo"
path = "tests/repo.rs"
[[test]]
name = "user"
path = "tests/user.rs"
[dependencies.base64ct]
version = "1.6.0"
[dependencies.bytes]
version = "1.5.0"
[dependencies.reqwest]
version = "0.11.18"
features = [
"json",
"multipart",
]
[dependencies.serde]
version = "1.0.168"
features = ["derive"]
[dependencies.serde_json]
version = "1.0.108"
[dependencies.soft_assert]
version = "0.1.1"
[dependencies.thiserror]
version = "1.0.43"
[dependencies.time]
version = "0.3.26"
features = [
"parsing",
"serde",
"formatting",
]
[dependencies.tokio]
version = "1.29.1"
features = ["net"]
[dependencies.url]
version = "2.4.0"
features = ["serde"]
[dependencies.zeroize]
version = "1.7.0"
[dev-dependencies.eyre]
version = "0.6.9"
[dev-dependencies.reqwest]
version = "0.11.18"
features = ["cookies"]
[dev-dependencies.tokio]
version = "1.29.1"
features = [
"net",
"fs",
"rt",
"macros",
]

28
Cargo.toml.orig generated Normal file
View file

@ -0,0 +1,28 @@
workspace = { members = ["generator"] }
[package]
name = "forgejo-api"
version = "0.4.1"
edition = "2021"
license = "Apache-2.0 OR MIT"
repository = "https://codeberg.org/Cyborus/forgejo-api"
description = "Interface to Forgejo's Web API"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
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.26", features = ["parsing", "serde", "formatting"] }
serde_json = "1.0.108"
bytes = "1.5.0"
base64ct = "1.6.0"
zeroize = "1.7.0"
[dev-dependencies]
eyre = "0.6.9"
reqwest = { version = "0.11.18", features = ["cookies"] }
tokio = { version = "1.29.1", features = ["net", "fs", "rt", "macros"] }

201
LICENSE-APACHE Normal file
View file

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

21
LICENSE-MIT Normal file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) [year] [fullname]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

13
README.md Normal file
View file

@ -0,0 +1,13 @@
# forgejo-api
Rust interface to Forgejo's Web API.
# Licensing
This project is licensed under either
[Apache License Version 2.0](LICENSE-APACHE) or [MIT License](LICENSE-MIT)
at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
dual licensed as above, without any additional terms or conditions.

8078
src/generated/methods.rs Normal file

File diff suppressed because it is too large Load diff

2
src/generated/mod.rs Normal file
View file

@ -0,0 +1,2 @@
pub mod methods;
pub mod structs;

6487
src/generated/structs.rs Normal file

File diff suppressed because it is too large Load diff

437
src/lib.rs Normal file
View file

@ -0,0 +1,437 @@
use reqwest::{Client, Request, StatusCode};
use serde::{Deserialize, Deserializer};
use soft_assert::*;
use url::Url;
use zeroize::Zeroize;
pub struct Forgejo {
url: Url,
client: Client,
}
mod generated;
#[derive(thiserror::Error, Debug)]
pub enum ForgejoError {
#[error("url must have a host")]
HostRequired,
#[error("scheme must be http or https")]
HttpRequired,
#[error(transparent)]
ReqwestError(#[from] reqwest::Error),
#[error("API key should be ascii")]
KeyNotAscii,
#[error("the response from forgejo was not properly structured")]
BadStructure(#[from] StructureError),
#[error("unexpected status code {} {}", .0.as_u16(), .0.canonical_reason().unwrap_or(""))]
UnexpectedStatusCode(StatusCode),
#[error("{} {}{}", .0.as_u16(), .0.canonical_reason().unwrap_or(""), .1.as_ref().map(|s| format!(": {s}")).unwrap_or_default())]
ApiError(StatusCode, Option<String>),
#[error("the provided authorization was too long to accept")]
AuthTooLong,
}
#[derive(thiserror::Error, Debug)]
pub enum StructureError {
#[error("{contents}")]
Serde {
e: serde_json::Error,
contents: String,
},
#[error("failed to find header `{0}`")]
HeaderMissing(&'static str),
#[error("header was not ascii")]
HeaderNotAscii,
#[error("failed to parse header")]
HeaderParseFailed,
}
/// Method of authentication to connect to the Forgejo host with.
pub enum Auth<'a> {
/// Application Access Token. Grants access to scope enabled for the
/// provided token, which may include full access.
///
/// To learn how to create a token, see
/// [the Codeberg docs on the subject](https://docs.codeberg.org/advanced/access-token/).
///
/// To learn about token scope, see
/// [the official Forgejo docs](https://forgejo.org/docs/latest/user/token-scope/).
Token(&'a str),
/// OAuth2 Token. Grants full access to the user's account, except for
/// creating application access tokens.
///
/// To learn how to create an OAuth2 token, see
/// [the official Forgejo docs on the subject](https://forgejo.org/docs/latest/user/oauth2-provider).
OAuth2(&'a str),
/// Username, password, and 2-factor auth code (if enabled). Grants full
/// access to the user's account.
Password {
username: &'a str,
password: &'a str,
mfa: Option<&'a str>,
},
/// No authentication. Only grants access to access public endpoints.
None,
}
impl Forgejo {
pub fn new(auth: Auth, url: Url) -> Result<Self, ForgejoError> {
Self::with_user_agent(auth, url, "forgejo-api-rs")
}
pub fn with_user_agent(auth: Auth, url: Url, user_agent: &str) -> Result<Self, ForgejoError> {
soft_assert!(
matches!(url.scheme(), "http" | "https"),
Err(ForgejoError::HttpRequired)
);
let mut headers = reqwest::header::HeaderMap::new();
match auth {
Auth::Token(token) => {
let mut header: reqwest::header::HeaderValue = format!("token {token}")
.try_into()
.map_err(|_| ForgejoError::KeyNotAscii)?;
header.set_sensitive(true);
headers.insert("Authorization", header);
}
Auth::Password {
username,
password,
mfa,
} => {
let unencoded_len = username.len() + password.len() + 1;
let unpadded_len = unencoded_len
.checked_mul(4)
.ok_or(ForgejoError::AuthTooLong)?
.div_ceil(3);
// round up to next multiple of 4, to account for padding
let len = unpadded_len.div_ceil(4) * 4;
let mut bytes = vec![0; len];
// panic safety: len cannot be zero
let mut encoder = base64ct::Encoder::<base64ct::Base64>::new(&mut bytes).unwrap();
// panic safety: len will always be enough
encoder.encode(username.as_bytes()).unwrap();
encoder.encode(b":").unwrap();
encoder.encode(password.as_bytes()).unwrap();
let b64 = encoder.finish().unwrap();
let mut header: reqwest::header::HeaderValue =
format!("Basic {b64}").try_into().unwrap(); // panic safety: base64 is always ascii
header.set_sensitive(true);
headers.insert("Authorization", header);
bytes.zeroize();
if let Some(mfa) = mfa {
let mut key_header: reqwest::header::HeaderValue =
mfa.try_into().map_err(|_| ForgejoError::KeyNotAscii)?;
key_header.set_sensitive(true);
headers.insert("X-FORGEJO-OTP", key_header);
}
}
Auth::OAuth2(token) => {
let mut header: reqwest::header::HeaderValue = format!("Bearer {token}")
.try_into()
.map_err(|_| ForgejoError::KeyNotAscii)?;
header.set_sensitive(true);
headers.insert("Authorization", header);
}
Auth::None => (),
}
let client = Client::builder()
.user_agent(user_agent)
.default_headers(headers)
.build()?;
Ok(Self { url, client })
}
pub async fn download_release_attachment(
&self,
owner: &str,
repo: &str,
release: u64,
attach: u64,
) -> Result<bytes::Bytes, ForgejoError> {
let release = self
.repo_get_release_attachment(owner, repo, release, attach)
.await?;
let mut url = self.url.clone();
url.path_segments_mut()
.unwrap()
.pop_if_empty()
.extend(["attachments", &release.uuid.unwrap().to_string()]);
let request = self.client.get(url).build()?;
Ok(self.execute(request).await?.bytes().await?)
}
/// Requests a new OAuth2 access token
///
/// More info at [Forgejo's docs](https://forgejo.org/docs/latest/user/oauth2-provider).
pub async fn oauth_get_access_token(
&self,
body: structs::OAuthTokenRequest<'_>,
) -> Result<structs::OAuthToken, ForgejoError> {
let url = self.url.join("login/oauth/access_token").unwrap();
let request = self.client.post(url).json(&body).build()?;
let response = self.execute(request).await?;
match response.status().as_u16() {
200 => Ok(response.json().await?),
_ => Err(ForgejoError::UnexpectedStatusCode(response.status())),
}
}
fn get(&self, path: &str) -> reqwest::RequestBuilder {
let url = self.url.join("api/v1/").unwrap().join(path).unwrap();
self.client.get(url)
}
fn put(&self, path: &str) -> reqwest::RequestBuilder {
let url = self.url.join("api/v1/").unwrap().join(path).unwrap();
self.client.put(url)
}
fn post(&self, path: &str) -> reqwest::RequestBuilder {
let url = self.url.join("api/v1/").unwrap().join(path).unwrap();
self.client.post(url)
}
fn delete(&self, path: &str) -> reqwest::RequestBuilder {
let url = self.url.join("api/v1/").unwrap().join(path).unwrap();
self.client.delete(url)
}
fn patch(&self, path: &str) -> reqwest::RequestBuilder {
let url = self.url.join("api/v1/").unwrap().join(path).unwrap();
self.client.patch(url)
}
async fn execute(&self, request: Request) -> Result<reqwest::Response, ForgejoError> {
let response = self.client.execute(request).await?;
match response.status() {
status if status.is_success() => Ok(response),
status if status.is_client_error() => {
Err(ForgejoError::ApiError(status, maybe_err(response).await))
}
status => Err(ForgejoError::UnexpectedStatusCode(status)),
}
}
}
async fn maybe_err(res: reqwest::Response) -> Option<String> {
res.json::<ErrorMessage>().await.ok().map(|e| e.message)
}
#[derive(serde::Deserialize)]
struct ErrorMessage {
message: String,
// intentionally ignored, no need for now
// url: Url
}
pub mod structs {
pub use crate::generated::structs::*;
/// A Request for a new OAuth2 access token
///
/// More info at [Forgejo's docs](https://forgejo.org/docs/latest/user/oauth2-provider).
#[derive(serde::Serialize)]
#[serde(tag = "grant_type")]
pub enum OAuthTokenRequest<'a> {
/// Request for getting an access code for a confidential app
///
/// The `code` field must have come from sending the user to
/// `/login/oauth/authorize` in their browser
#[serde(rename = "authorization_code")]
Confidential {
client_id: &'a str,
client_secret: &'a str,
code: &'a str,
redirect_uri: url::Url,
},
/// Request for getting an access code for a public app
///
/// The `code` field must have come from sending the user to
/// `/login/oauth/authorize` in their browser
#[serde(rename = "authorization_code")]
Public {
client_id: &'a str,
code_verifier: &'a str,
code: &'a str,
redirect_uri: url::Url,
},
/// Request for refreshing an access code
#[serde(rename = "refresh_token")]
Refresh {
refresh_token: &'a str,
client_id: &'a str,
client_secret: &'a str,
},
}
#[derive(serde::Deserialize)]
pub struct OAuthToken {
pub access_token: String,
pub refresh_token: String,
pub token_type: String,
/// Number of seconds until the access token expires.
pub expires_in: u32,
}
}
// Forgejo can return blank strings for URLs. This handles that by deserializing
// that as `None`
fn none_if_blank_url<'de, D: serde::Deserializer<'de>>(
deserializer: D,
) -> Result<Option<Url>, D::Error> {
use serde::de::{Error, Unexpected, Visitor};
use std::fmt;
struct EmptyUrlVisitor;
impl<'de> Visitor<'de> for EmptyUrlVisitor {
type Value = Option<Url>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("option")
}
#[inline]
fn visit_unit<E>(self) -> Result<Self::Value, E>
where
E: Error,
{
Ok(None)
}
#[inline]
fn visit_none<E>(self) -> Result<Self::Value, E>
where
E: Error,
{
Ok(None)
}
#[inline]
fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
where
E: Error,
{
if s.is_empty() {
return Ok(None);
}
Url::parse(s)
.map_err(|err| {
let err_s = format!("{}", err);
Error::invalid_value(Unexpected::Str(s), &err_s.as_str())
})
.map(Some)
}
}
deserializer.deserialize_str(EmptyUrlVisitor)
}
#[allow(dead_code)] // not used yet, but it might appear in the future
fn deserialize_ssh_url<'de, D, DE>(deserializer: D) -> Result<Url, DE>
where
D: Deserializer<'de>,
DE: serde::de::Error,
{
let raw_url: String = String::deserialize(deserializer).map_err(DE::custom)?;
parse_ssh_url(&raw_url).map_err(DE::custom)
}
fn deserialize_optional_ssh_url<'de, D, DE>(deserializer: D) -> Result<Option<Url>, DE>
where
D: Deserializer<'de>,
DE: serde::de::Error,
{
let raw_url: Option<String> = Option::deserialize(deserializer).map_err(DE::custom)?;
raw_url
.as_ref()
.map(parse_ssh_url)
.map(|res| res.map_err(DE::custom))
.transpose()
.or(Ok(None))
}
fn requested_reviewers_ignore_null<'de, D, DE>(
deserializer: D,
) -> Result<Option<Vec<structs::User>>, DE>
where
D: Deserializer<'de>,
DE: serde::de::Error,
{
let list: Option<Vec<Option<structs::User>>> =
Option::deserialize(deserializer).map_err(DE::custom)?;
Ok(list.map(|list| list.into_iter().filter_map(|x| x).collect::<Vec<_>>()))
}
fn parse_ssh_url(raw_url: &String) -> Result<Url, url::ParseError> {
// in case of a non-standard ssh-port (not 22), the ssh url coming from the forgejo API
// is actually parseable by the url crate, so try to do that first
Url::parse(raw_url).or_else(|_| {
// otherwise the ssh url is not parseable by the url crate and we try again after some
// pre-processing
let url = format!("ssh://{url}", url = raw_url.replace(":", "/"));
Url::parse(url.as_str())
})
}
#[test]
fn ssh_url_deserialization() {
#[derive(serde::Deserialize)]
struct SshUrl {
#[serde(deserialize_with = "deserialize_ssh_url")]
url: url::Url,
}
let full_url = r#"{ "url": "ssh://git@codeberg.org/Cyborus/forgejo-api" }"#;
let ssh_url = r#"{ "url": "git@codeberg.org:Cyborus/forgejo-api" }"#;
let full_url_de =
serde_json::from_str::<SshUrl>(full_url).expect("failed to deserialize full url");
let ssh_url_de =
serde_json::from_str::<SshUrl>(ssh_url).expect("failed to deserialize ssh url");
let expected = "ssh://git@codeberg.org/Cyborus/forgejo-api";
assert_eq!(full_url_de.url.as_str(), expected);
assert_eq!(ssh_url_de.url.as_str(), expected);
#[derive(serde::Deserialize)]
struct OptSshUrl {
#[serde(deserialize_with = "deserialize_optional_ssh_url")]
url: Option<url::Url>,
}
let null_url = r#"{ "url": null }"#;
let full_url_de = serde_json::from_str::<OptSshUrl>(full_url)
.expect("failed to deserialize optional full url");
let ssh_url_de =
serde_json::from_str::<OptSshUrl>(ssh_url).expect("failed to deserialize optional ssh url");
let null_url_de =
serde_json::from_str::<OptSshUrl>(null_url).expect("failed to deserialize null url");
let expected = Some("ssh://git@codeberg.org/Cyborus/forgejo-api");
assert_eq!(full_url_de.url.as_ref().map(|u| u.as_ref()), expected);
assert_eq!(ssh_url_de.url.as_ref().map(|u| u.as_ref()), expected);
assert!(null_url_de.url.is_none());
}
impl From<structs::DefaultMergeStyle> for structs::MergePullRequestOptionDo {
fn from(value: structs::DefaultMergeStyle) -> Self {
match value {
structs::DefaultMergeStyle::Merge => structs::MergePullRequestOptionDo::Merge,
structs::DefaultMergeStyle::Rebase => structs::MergePullRequestOptionDo::Rebase,
structs::DefaultMergeStyle::RebaseMerge => {
structs::MergePullRequestOptionDo::RebaseMerge
}
structs::DefaultMergeStyle::Squash => structs::MergePullRequestOptionDo::Squash,
structs::DefaultMergeStyle::FastForwardOnly => {
structs::MergePullRequestOptionDo::FastForwardOnly
}
}
}
}

25101
swagger.v1.json Normal file

File diff suppressed because it is too large Load diff

194
tests/admin.rs Normal file
View file

@ -0,0 +1,194 @@
use forgejo_api::structs::*;
mod common;
#[tokio::test]
async fn user() {
let api = common::login();
let user_opt = CreateUserOption {
created_at: None,
email: "pipis@noreply.example.org".into(),
full_name: None,
login_name: None,
must_change_password: None,
password: Some("userpass".into()),
restricted: Some(false),
send_notify: Some(true),
source_id: None,
username: "Pipis".into(),
visibility: Some("public".into()),
};
let _ = api
.admin_create_user(user_opt)
.await
.expect("failed to create user");
let query = AdminSearchUsersQuery::default();
let users = api
.admin_search_users(query)
.await
.expect("failed to search users");
assert!(
users
.iter()
.find(|u| u.login.as_ref().unwrap() == "Pipis")
.is_some(),
"could not find new user"
);
let query = AdminGetAllEmailsQuery::default();
let users = api
.admin_get_all_emails(query)
.await
.expect("failed to search emails");
assert!(
users
.iter()
.find(|u| u.email.as_ref().unwrap() == "pipis@noreply.example.org")
.is_some(),
"could not find new user"
);
}
#[tokio::test]
async fn org() {
let api = common::login();
let user_opt = CreateUserOption {
created_at: None,
email: "org-owner@noreply.example.org".into(),
full_name: None,
login_name: None,
must_change_password: None,
password: Some("userpass".into()),
restricted: Some(false),
send_notify: Some(true),
source_id: None,
username: "OrgOwner".into(),
visibility: Some("public".into()),
};
let _ = api
.admin_create_user(user_opt)
.await
.expect("failed to create user");
let org_opt = CreateOrgOption {
description: None,
email: None,
full_name: None,
location: None,
repo_admin_change_team_access: None,
username: "test-org".into(),
visibility: Some(CreateOrgOptionVisibility::Public),
website: None,
};
let _ = api
.admin_create_org("OrgOwner", org_opt)
.await
.expect("failed to create org");
let query = AdminGetAllOrgsQuery::default();
assert!(
!api.admin_get_all_orgs(query).await.unwrap().is_empty(),
"org list empty"
);
let rename_opt = RenameUserOption {
new_username: "Bepis".into(),
};
api.admin_rename_user("Pipis", rename_opt)
.await
.expect("failed to rename user");
let query = AdminDeleteUserQuery { purge: Some(true) };
api.admin_delete_user("Bepis", query)
.await
.expect("failed to delete user");
let query = AdminDeleteUserQuery { purge: Some(true) };
assert!(
api.admin_delete_user("Ghost", query).await.is_err(),
"deleting fake user should fail"
);
}
#[tokio::test]
async fn key() {
let api = common::login();
let user_opt = CreateUserOption {
created_at: None,
email: "key-holder@noreply.example.org".into(),
full_name: None,
login_name: None,
must_change_password: None,
password: Some("userpass".into()),
restricted: Some(false),
send_notify: Some(true),
source_id: None,
username: "KeyHolder".into(),
visibility: Some("public".into()),
};
let _ = api
.admin_create_user(user_opt)
.await
.expect("failed to create user");
let key_opt = CreateKeyOption {
key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIN68ehQAsbGEwlXPa2AxbAh1QxFQrtRel2jeC0hRlPc1 user@noreply.example.org".into(),
read_only: None,
title: "Example Key".into(),
};
let key = api
.admin_create_public_key("KeyHolder", key_opt)
.await
.expect("failed to create key");
api.admin_delete_user_public_key("KeyHolder", key.id.unwrap() as u64)
.await
.expect("failed to delete key");
}
#[tokio::test]
async fn cron() {
let api = common::login();
let query = AdminCronListQuery::default();
let crons = api
.admin_cron_list(query)
.await
.expect("failed to get crons list");
api.admin_cron_run(&crons.get(0).expect("no crons").name.as_ref().unwrap())
.await
.expect("failed to run cron");
}
#[tokio::test]
async fn hook() {
let api = common::login();
let hook_opt = CreateHookOption {
active: None,
authorization_header: None,
branch_filter: None,
config: CreateHookOptionConfig {
content_type: "json".into(),
url: url::Url::parse("http://test.local/").unwrap(),
additional: Default::default(),
},
events: Some(Vec::new()),
r#type: CreateHookOptionType::Gitea,
};
// yarr har har me matey this is me hook
let hook = api
.admin_create_hook(hook_opt)
.await
.expect("failed to create hook");
let edit_hook = EditHookOption {
active: Some(true),
authorization_header: None,
branch_filter: None,
config: None,
events: None,
};
api.admin_edit_hook(hook.id.unwrap() as u64, edit_hook)
.await
.expect("failed to edit hook");
api.admin_delete_hook(hook.id.unwrap() as u64)
.await
.expect("failed to delete hook");
}

17
tests/common/mod.rs Normal file
View file

@ -0,0 +1,17 @@
use forgejo_api::Forgejo;
pub fn login() -> Forgejo {
let url = url::Url::parse(&std::env::var("FORGEJO_API_CI_INSTANCE_URL").unwrap()).unwrap();
let token = std::env::var("FORGEJO_API_CI_TOKEN").unwrap();
Forgejo::new(forgejo_api::Auth::Token(&token), url).unwrap()
}
pub fn login_pass(username: &str, password: &str) -> Forgejo {
let url = url::Url::parse(&std::env::var("FORGEJO_API_CI_INSTANCE_URL").unwrap()).unwrap();
let auth = forgejo_api::Auth::Password {
username,
password,
mfa: None,
};
Forgejo::new(auth, url).unwrap()
}

58
tests/organization.rs Normal file
View file

@ -0,0 +1,58 @@
use forgejo_api::structs::*;
mod common;
#[tokio::test]
async fn org_vars() {
let api = common::login();
let org_opt = CreateOrgOption {
description: Some("Testing organization variables".into()),
email: None,
full_name: Some("Org Variables".into()),
location: Some("The Lab".into()),
repo_admin_change_team_access: None,
username: "org-vars".into(),
visibility: None,
website: None,
};
api.org_create(org_opt).await.expect("failed to create org");
let query = GetOrgVariablesListQuery::default();
let var_list = api
.get_org_variables_list("org-vars", query)
.await
.expect("failed to list org vars");
assert!(var_list.is_empty());
let opt = CreateVariableOption {
value: "false".into(),
};
api.create_org_variable("org-vars", "want_pizza", opt)
.await
.expect("failed to create org var");
let new_var = api
.get_org_variable("org-vars", "want_pizza")
.await
.expect("failed to get org var");
assert_eq!(new_var.data.as_deref(), Some("false"));
// no no no we definitely do want pizza
let opt = UpdateVariableOption {
name: Some("really_want_pizza".into()),
value: "true".into(),
};
api.update_org_variable("org-vars", "want_pizza", opt)
.await
.expect("failed to update org variable");
let new_var = api
.get_org_variable("org-vars", "really_want_pizza")
.await
.expect("failed to get org var");
assert_eq!(new_var.data.as_deref(), Some("true"));
api.delete_org_variable("org-vars", "really_want_pizza")
.await
.expect("failed to delete org var");
}

495
tests/repo.rs Normal file
View file

@ -0,0 +1,495 @@
use forgejo_api::structs::*;
mod common;
struct Git {
dir: &'static std::path::Path,
}
impl Git {
fn new<T: AsRef<std::path::Path> + ?Sized>(path: &'static T) -> Self {
let dir = path.as_ref();
std::fs::create_dir_all(dir).unwrap();
Self { dir }
}
fn run(&self, args: &[impl AsRef<std::ffi::OsStr>]) {
let mut cmd = std::process::Command::new("git");
cmd.current_dir(self.dir);
let _ = cmd.args(args).status().unwrap();
}
}
async fn setup_local_repo(git: &Git) {
git.run(&["config", "--global", "init.defaultBranch", "main"]);
git.run(&["init"]);
git.run(&["config", "user.name", "TestingAdmin"]);
git.run(&["config", "user.email", "admin@noreply.example.org"]);
tokio::fs::write(&git.dir.join("README.md"), "# Test\nThis is a test repo")
.await
.unwrap();
git.run(&["add", "."]);
git.run(&["commit", "-m", "initial commit"]);
}
async fn basic_repo(api: &forgejo_api::Forgejo, git: &Git, name: &str) -> Repository {
setup_local_repo(git).await;
let repo_opt = CreateRepoOption {
auto_init: Some(false),
default_branch: Some("main".into()),
description: Some("Test Repo".into()),
gitignores: Some("".into()),
issue_labels: Some("".into()),
license: Some("".into()),
name: name.into(),
object_format_name: None,
private: Some(false),
readme: None,
template: Some(false),
trust_model: Some(CreateRepoOptionTrustModel::Default),
};
let remote_repo = api.create_current_user_repo(repo_opt).await.unwrap();
assert!(
remote_repo.has_pull_requests.unwrap(),
"repo does not accept pull requests"
);
assert!(
remote_repo.owner.as_ref().unwrap().login.as_ref().unwrap() == "TestingAdmin",
"repo owner is not \"TestingAdmin\""
);
assert!(
remote_repo.name.as_ref().unwrap() == name,
"repo name is not \"{name}\""
);
let mut remote_url = remote_repo.clone_url.clone().unwrap();
remote_url.set_username("TestingAdmin").unwrap();
remote_url.set_password(Some("password")).unwrap();
git.run(&["remote", "add", "origin", remote_url.as_str()]);
git.run(&["push", "-u", "origin", "main"]);
remote_repo
}
async fn basic_org_repo(
api: &forgejo_api::Forgejo,
git: &Git,
org: &str,
name: &str,
) -> Repository {
setup_local_repo(git).await;
let repo_opt = CreateRepoOption {
auto_init: Some(false),
default_branch: Some("main".into()),
description: Some("Test Repo".into()),
gitignores: Some("".into()),
issue_labels: Some("".into()),
license: Some("".into()),
name: name.into(),
object_format_name: None,
private: Some(false),
readme: None,
template: Some(false),
trust_model: Some(CreateRepoOptionTrustModel::Default),
};
let remote_repo = api.create_org_repo(org, repo_opt).await.unwrap();
assert!(
remote_repo.has_pull_requests.unwrap(),
"repo does not accept pull requests"
);
assert!(
remote_repo.owner.as_ref().unwrap().login.as_ref().unwrap() == org,
"repo owner is not \"TestingAdmin\""
);
assert!(
remote_repo.name.as_ref().unwrap() == name,
"repo name is not \"{name}\""
);
let mut remote_url = remote_repo.clone_url.clone().unwrap();
remote_url.set_username("TestingAdmin").unwrap();
remote_url.set_password(Some("password")).unwrap();
git.run(&["remote", "add", "origin", remote_url.as_str()]);
git.run(&["push", "-u", "origin", "main"]);
remote_repo
}
#[tokio::test]
async fn pull_request() {
let api = common::login();
let git = Git::new("./test_repos/pr");
let _ = basic_repo(&api, &git, "pr-test").await;
git.run(&["switch", "-c", "test"]);
tokio::fs::write(
"./test_repos/pr/example.rs",
"fn add_one(x: u32) -> u32 { x + 1 }",
)
.await
.unwrap();
git.run(&["add", "."]);
git.run(&["commit", "-m", "egg"]);
git.run(&["push", "-u", "origin", "test"]);
let pr_opt = CreatePullRequestOption {
assignee: None,
assignees: Some(vec!["TestingAdmin".into()]),
base: Some("main".into()),
body: Some("This is a test PR".into()),
due_date: None,
head: Some("test".into()),
labels: None,
milestone: None,
title: Some("test pr".into()),
};
// Wait for... something to happen, or else creating a PR will return 404
tokio::time::sleep(std::time::Duration::from_secs(3)).await;
let pr = api
.repo_create_pull_request("TestingAdmin", "pr-test", pr_opt)
.await
.expect("couldn't create pr");
let is_merged = api
.repo_pull_request_is_merged("TestingAdmin", "pr-test", pr.number.unwrap() as u64)
.await
.is_ok();
assert!(!is_merged, "pr should not yet be merged");
let pr_files_query = RepoGetPullRequestFilesQuery::default();
let (_, _) = api
.repo_get_pull_request_files(
"TestingAdmin",
"pr-test",
pr.number.unwrap() as u64,
pr_files_query,
)
.await
.unwrap();
let merge_opt = MergePullRequestOption {
r#do: MergePullRequestOptionDo::Merge,
merge_commit_id: None,
merge_message_field: None,
merge_title_field: None,
delete_branch_after_merge: Some(true),
force_merge: None,
head_commit_id: None,
merge_when_checks_succeed: None,
};
api.repo_merge_pull_request(
"TestingAdmin",
"pr-test",
pr.number.unwrap() as u64,
merge_opt,
)
.await
.expect("couldn't merge pr");
let is_merged = api
.repo_pull_request_is_merged("TestingAdmin", "pr-test", pr.number.unwrap() as u64)
.await
.is_ok();
assert!(is_merged, "pr should be merged");
}
#[tokio::test]
async fn release() {
let api = common::login();
let git = Git::new("./test_repos/release");
let _ = basic_repo(&api, &git, "release-test").await;
// Wait for the repo to be finished being populated, or else creating a
// release will return "422 repo is empty"
tokio::time::sleep(std::time::Duration::from_secs(3)).await;
let query = RepoListReleasesQuery::default();
assert!(
api.repo_list_releases("TestingAdmin", "release-test", query)
.await
.unwrap()
.is_empty(),
"there should be no releases yet"
);
let tag_opt = CreateTagOption {
message: Some("This is a tag!".into()),
tag_name: "v1.0".into(),
target: None,
};
api.repo_create_tag("TestingAdmin", "release-test", tag_opt)
.await
.expect("failed to create tag");
let release_opt = CreateReleaseOption {
body: Some("This is a release!".into()),
draft: Some(true),
name: Some("v1.0".into()),
prerelease: Some(false),
tag_name: "v1.0".into(),
target_commitish: None,
hide_archive_links: None,
};
let release = api
.repo_create_release("TestingAdmin", "release-test", release_opt)
.await
.expect("failed to create release");
let edit_release = EditReleaseOption {
body: None,
draft: Some(false),
name: None,
prerelease: None,
tag_name: None,
target_commitish: None,
hide_archive_links: None,
};
api.repo_edit_release(
"TestingAdmin",
"release-test",
release.id.unwrap() as u64,
edit_release,
)
.await
.expect("failed to edit release");
let release_by_tag = api
.repo_get_release_by_tag("TestingAdmin", "release-test", "v1.0")
.await
.expect("failed to find release");
let release_latest = api
.repo_get_latest_release("TestingAdmin", "release-test")
.await
.expect("failed to find latest release");
assert!(release_by_tag == release_latest, "releases not equal");
let attachment = api
.repo_create_release_attachment(
"TestingAdmin",
"release-test",
release.id.unwrap() as u64,
b"This is a file!".to_vec(),
RepoCreateReleaseAttachmentQuery {
name: Some("test.txt".into()),
},
)
.await
.expect("failed to create release attachment");
assert!(
&*api
.download_release_attachment(
"TestingAdmin",
"release-test",
release.id.unwrap() as u64,
attachment.id.unwrap() as u64
)
.await
.unwrap()
== b"This is a file!",
"couldn't download attachment"
);
let _zip_archive = api
.repo_get_archive("TestingAdmin", "release-test", "v1.0.zip")
.await
.unwrap();
let _tar_archive = api
.repo_get_archive("TestingAdmin", "release-test", "v1.0.tar.gz")
.await
.unwrap();
// check these contents when their return value is fixed
api.repo_delete_release_attachment(
"TestingAdmin",
"release-test",
release.id.unwrap() as u64,
attachment.id.unwrap() as u64,
)
.await
.expect("failed to deleted attachment");
api.repo_delete_release("TestingAdmin", "release-test", release.id.unwrap() as u64)
.await
.expect("failed to delete release");
api.repo_delete_tag("TestingAdmin", "release-test", "v1.0")
.await
.expect("failed to delete release");
}
#[tokio::test]
async fn delete_repo() {
let api = common::login();
let git = Git::new("./test_repos/delete");
let _ = basic_repo(&api, &git, "delete-test").await;
api.repo_delete("TestingAdmin", "delete-test")
.await
.expect("failed to delete repo");
}
#[tokio::test]
async fn team_pr_review_request() {
let api = common::login();
let org_opt = CreateOrgOption {
description: Some("Testing team review requests".into()),
email: None,
full_name: None,
location: None,
repo_admin_change_team_access: None,
username: "team-review-org".into(),
visibility: None,
website: None,
};
api.org_create(org_opt).await.unwrap();
let git = Git::new("./test_repos/team-pr-review");
let _ = basic_org_repo(&api, &git, "team-review-org", "team-pr-review").await;
git.run(&["switch", "-c", "test"]);
tokio::fs::write(
"./test_repos/team-pr-review/example.rs",
"fn add_one(x: u32) -> u32 { x + 1 }",
)
.await
.unwrap();
git.run(&["add", "."]);
git.run(&["commit", "-m", "egg"]);
git.run(&["push", "-u", "origin", "test"]);
let pr_opt = CreatePullRequestOption {
assignee: None,
assignees: Some(vec!["TestingAdmin".into()]),
base: Some("main".into()),
body: Some("This is a test PR".into()),
due_date: None,
head: Some("test".into()),
labels: None,
milestone: None,
title: Some("test pr".into()),
};
// Wait for... something to happen, or else creating a PR will return 404
tokio::time::sleep(std::time::Duration::from_secs(3)).await;
api.repo_create_pull_request("team-review-org", "team-pr-review", pr_opt)
.await
.expect("couldn't create pr");
let review_opt = PullReviewRequestOptions {
reviewers: None,
team_reviewers: Some(vec!["Owners".into()]),
};
api.repo_create_pull_review_requests("team-review-org", "team-pr-review", 1, review_opt)
.await
.expect("couldn't request review");
let pr = api
.repo_get_pull_request("team-review-org", "team-pr-review", 1)
.await
.expect("couldn't get pr");
assert_eq!(pr.requested_reviewers, Some(Vec::new()));
}
#[tokio::test]
async fn tag_protection() {
let api = common::login();
let git = Git::new("./test_repos/tag-protect");
let _ = basic_repo(&api, &git, "tag-protect").await;
let tag_protections = api
.repo_list_tag_protection("TestingAdmin", "tag-protect")
.await
.expect("failed to list tag protections");
assert!(tag_protections.is_empty());
let protection_opt = CreateTagProtectionOption {
name_pattern: Some("v*".into()),
whitelist_teams: None,
whitelist_usernames: Some(vec!["TestingAdmin".into()]),
};
let new_protection = api
.repo_create_tag_protection("TestingAdmin", "tag-protect", protection_opt)
.await
.expect("failed to create tag protection");
let pattern = new_protection
.name_pattern
.as_deref()
.expect("protection does not have pattern");
assert_eq!(pattern, "v*");
let id = new_protection.id.expect("protection does not have id") as u32;
let protection_get = api
.repo_get_tag_protection("TestingAdmin", "tag-protect", id)
.await
.expect("failed to get tag protection");
assert_eq!(new_protection, protection_get);
let edit_opt = EditTagProtectionOption {
name_pattern: Some("v*.*.*".into()),
whitelist_teams: None,
whitelist_usernames: Some(vec![]),
};
let edited = api
.repo_edit_tag_protection("TestingAdmin", "tag-protect", id, edit_opt)
.await
.expect("failed to edit tag protection");
let pattern = edited
.name_pattern
.as_deref()
.expect("protection does not have pattern");
assert_eq!(pattern, "v*.*.*");
api.repo_delete_tag_protection("TestingAdmin", "tag-protect", id)
.await
.expect("failed to delete tag protection");
}
#[tokio::test]
async fn repo_vars() {
let api = common::login();
let git = Git::new("./test_repos/repo-vars");
let _ = basic_repo(&api, &git, "repo-vars").await;
let query = GetRepoVariablesListQuery::default();
let var_list = api
.get_repo_variables_list("TestingAdmin", "repo-vars", query)
.await
.expect("failed to list repo vars");
assert!(var_list.is_empty());
let opt = CreateVariableOption {
value: "false".into(),
};
api.create_repo_variable("TestingAdmin", "repo-vars", "very_cool", opt)
.await
.expect("failed to create repo var");
let new_var = api
.get_repo_variable("TestingAdmin", "repo-vars", "very_cool")
.await
.expect("failed to get repo var");
assert_eq!(new_var.data.as_deref(), Some("false"));
// wait, that's not right. you ARE very cool!
// gotta fix that
let opt = UpdateVariableOption {
name: Some("extremely_cool".into()),
value: "true".into(),
};
api.update_repo_variable("TestingAdmin", "repo-vars", "very_cool", opt)
.await
.expect("failed to update repo variable");
let new_var = api
.get_repo_variable("TestingAdmin", "repo-vars", "extremely_cool")
.await
.expect("failed to get repo var");
assert_eq!(new_var.data.as_deref(), Some("true"));
api.delete_repo_variable("TestingAdmin", "repo-vars", "extremely_cool")
.await
.expect("failed to delete repo var");
}

237
tests/user.rs Normal file
View file

@ -0,0 +1,237 @@
use forgejo_api::structs::*;
mod common;
#[tokio::test]
async fn myself() {
let api = common::login();
let myself = api.user_get_current().await.unwrap();
assert!(myself.is_admin.unwrap(), "user should be admin");
assert_eq!(
myself.login.as_ref().unwrap(),
"TestingAdmin",
"user should be named \"TestingAdmin\""
);
let myself_indirect = api.user_get("TestingAdmin").await.unwrap();
assert_eq!(
myself, myself_indirect,
"result of `myself` does not match result of `get_user`"
);
}
#[tokio::test]
async fn follow() {
let api = common::login();
let query = UserListFollowingQuery::default();
let following = api
.user_list_following("TestingAdmin", query)
.await
.unwrap();
assert!(following.is_empty(), "following list not empty");
let query = UserListFollowersQuery::default();
let followers = api
.user_list_followers("TestingAdmin", query)
.await
.unwrap();
assert!(followers.is_empty(), "follower list not empty");
let option = CreateUserOption {
created_at: None,
email: "follower@no-reply.example.org".into(),
full_name: None,
login_name: None,
must_change_password: Some(false),
password: Some("password".into()),
restricted: None,
send_notify: None,
source_id: None,
username: "Follower".into(),
visibility: None,
};
let _ = api.admin_create_user(option).await.unwrap();
let new_user = common::login_pass("Follower", "password");
new_user
.user_current_put_follow("TestingAdmin")
.await
.unwrap();
api.user_current_put_follow("Follower").await.unwrap();
let query = UserListFollowingQuery::default();
let following = api
.user_list_following("TestingAdmin", query)
.await
.unwrap();
assert!(!following.is_empty(), "following list empty");
let query = UserListFollowersQuery::default();
let followers = api
.user_list_followers("TestingAdmin", query)
.await
.unwrap();
assert!(!followers.is_empty(), "follower list empty");
}
#[tokio::test]
async fn password_login() {
let api = common::login();
let password_api = common::login_pass("TestingAdmin", "password");
assert!(
api.user_get_current().await.unwrap() == password_api.user_get_current().await.unwrap(),
"users not equal comparing token-auth and pass-auth"
);
}
#[tokio::test]
async fn oauth2_login() {
let api = common::login();
let opt = forgejo_api::structs::CreateOAuth2ApplicationOptions {
confidential_client: Some(true),
name: Some("Test Application".into()),
redirect_uris: Some(vec!["http://127.0.0.1:48879/".into()]),
};
let app = api.user_create_oauth2_application(opt).await.unwrap();
let client_id = app.client_id.unwrap();
let client_secret = app.client_secret.unwrap();
let base_url = &std::env::var("FORGEJO_API_CI_INSTANCE_URL").unwrap();
let client = reqwest::Client::builder()
.cookie_store(true)
.redirect(reqwest::redirect::Policy::none())
.build()
.unwrap();
// Log in via the web interface
let _ = client
.post(&format!("{base_url}user/login"))
.form(&[("user_name", "TestingAdmin"), ("password", "password")])
.send()
.await
.unwrap()
.error_for_status()
.unwrap();
// Load the authorization page
let response = client
.get(&format!(
"{base_url}login/oauth/authorize\
?client_id={client_id}\
&redirect_uri=http%3A%2F%2F127.0.0.1%3A48879%2F\
&response_type=code\
&state=theyve"
))
.send()
.await
.unwrap()
.error_for_status()
.unwrap();
let csrf = response.cookies().find(|x| x.name() == "_csrf").unwrap();
// Authorize the new application via the web interface
let response = client
.post(&format!("{base_url}login/oauth/grant"))
.form(&[
("_csrf", csrf.value()),
("client_id", &client_id),
("state", "theyve"),
("scope", ""),
("nonce", ""),
("redirect_uri", "http://127.0.0.1:48879/"),
])
.send()
.await
.unwrap()
.error_for_status()
.unwrap();
// Extract the code from the redirect url
let location = response.headers().get(reqwest::header::LOCATION).unwrap();
let location = url::Url::parse(dbg!(location.to_str().unwrap())).unwrap();
let mut code = None;
for (key, value) in location.query_pairs() {
if key == "code" {
code = Some(value.into_owned());
} else if key == "error_description" {
panic!("{value}");
}
}
let code = code.unwrap();
// Redeem the code and check it works
let url = url::Url::parse(&base_url).unwrap();
let api = forgejo_api::Forgejo::new(forgejo_api::Auth::None, url.clone()).unwrap();
let request = forgejo_api::structs::OAuthTokenRequest::Confidential {
client_id: &client_id,
client_secret: &client_secret,
code: &code,
redirect_uri: url::Url::parse("http://127.0.0.1:48879/").unwrap(),
};
let token = api.oauth_get_access_token(request).await.unwrap();
let token_api =
forgejo_api::Forgejo::new(forgejo_api::Auth::OAuth2(&token.access_token), url.clone())
.unwrap();
let myself = token_api.user_get_current().await.unwrap();
assert_eq!(myself.login.as_deref(), Some("TestingAdmin"));
let request = forgejo_api::structs::OAuthTokenRequest::Refresh {
refresh_token: &token.refresh_token,
client_id: &client_id,
client_secret: &client_secret,
};
let token = token_api.oauth_get_access_token(request).await.unwrap();
let token_api =
forgejo_api::Forgejo::new(forgejo_api::Auth::OAuth2(&token.access_token), url).unwrap();
let myself = token_api.user_get_current().await.unwrap();
assert_eq!(myself.login.as_deref(), Some("TestingAdmin"));
}
#[tokio::test]
async fn user_vars() {
let api = common::login();
let query = GetUserVariablesListQuery::default();
let var_list = api
.get_user_variables_list(query)
.await
.expect("failed to list user vars");
assert!(var_list.is_empty());
let opt = CreateVariableOption {
value: "false".into(),
};
api.create_user_variable("likes_dogs", opt)
.await
.expect("failed to create user var");
let new_var = api
.get_user_variable("likes_dogs")
.await
.expect("failed to get user var");
assert_eq!(new_var.data.as_deref(), Some("false"));
// what??? totally wrong. I love dogs!
let opt = UpdateVariableOption {
name: Some("loves_dogs".into()),
value: "true".into(),
};
api.update_user_variable("likes_dogs", opt)
.await
.expect("failed to update user variable");
let new_var = api
.get_user_variable("loves_dogs")
.await
.expect("failed to get user var");
assert_eq!(new_var.data.as_deref(), Some("true"));
api.delete_user_variable("loves_dogs")
.await
.expect("failed to delete user var");
}