Skip to content

Commit

Permalink
master: improve code style
Browse files Browse the repository at this point in the history
  • Loading branch information
lowitea committed Dec 7, 2024
1 parent 2cc5838 commit a0cae8f
Show file tree
Hide file tree
Showing 6 changed files with 84 additions and 91 deletions.
2 changes: 2 additions & 0 deletions rust-toolchain.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[toolchain]
channel = "1.82"
20 changes: 8 additions & 12 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use anyhow::{bail, Result};
#[command(author, version, about)]
/// A tool for cloning all available repositories in a GitLab instance
struct Cli {
/// The GitLab instance URL for fetch repositories (example: https://gitlab.local/)
/// The GitLab instance URL for fetch repositories (example: <https://gitlab.local>)
#[arg(
long,
value_parser,
Expand All @@ -27,7 +27,7 @@ struct Cli {
)]
ft: String,

/// The GitLab instance URL for backup repositories (example: https://backup-gitlab.local/)
/// The GitLab instance URL for backup repositories (example: <https://backup-gitlab.local>)
#[arg(
long,
value_parser,
Expand Down Expand Up @@ -123,19 +123,19 @@ struct Cli {
#[arg(long, env = "GTLBSTR_UPLOAD_SSH")]
upload_ssh: bool,

/// Force download repositories by insecure protocol. Does not work with the download_ssh flag
/// Force download repositories by insecure protocol. Does not work with the `download_ssh` flag
#[arg(long, env = "GTLBSTR_DOWNLOAD_FORCE_HTTP")]
download_force_http: bool,

/// Force download repositories by secure protocol. Does not work with the download_ssh flag
/// Force download repositories by secure protocol. Does not work with the `download_ssh` flag
#[arg(long, env = "GTLBSTR_DOWNLOAD_FORCE_HTTPS")]
download_force_https: bool,

/// Force upload repositories by insecure protocol. Does not work with the upload_ssh flag
/// Force upload repositories by insecure protocol. Does not work with the `upload_ssh` flag
#[arg(long, env = "GTLBSTR_UPLOAD_FORCE_HTTP")]
upload_force_http: bool,

/// Force upload repositories by secure protocol. Does not work with the upload_ssh flag
/// Force upload repositories by secure protocol. Does not work with the `upload_ssh` flag
#[arg(long, env = "GTLBSTR_UPLOAD_FORCE_HTTPS")]
upload_force_https: bool,

Expand Down Expand Up @@ -172,7 +172,7 @@ pub fn run() -> Result<()> {
};
tracing_subscriber::fmt().with_max_level(log_level).init();

let fetch_gl = FetchGitlabOptions::new(cli.fu, cli.ft)?;
let fetch_gl = FetchGitlabOptions::new(&cli.fu, &cli.ft)?;

let patterns = if cli.exclude.is_some() && cli.include.is_some() {
bail!("You cannot use the --include and --exclude flag together");
Expand All @@ -184,11 +184,7 @@ pub fn run() -> Result<()> {

let upl_err = "For upload to another gitlab, you must specify both the --bt and --bu flags";
let backup_gl = if let (Some(url), Some(token)) = (&cli.bu, &cli.bt) {
Some(BackupGitlabOptions::new(
url.clone(),
token.clone(),
cli.bg.clone(),
)?)
Some(BackupGitlabOptions::new(url, token, cli.bg.clone())?)
} else {
if cli.bu.is_some() || cli.bt.is_some() {
bail!(upl_err);
Expand Down
33 changes: 19 additions & 14 deletions src/cloner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,12 @@ pub struct FetchGitlabOptions {
}

impl FetchGitlabOptions {
pub fn new(url: String, token: String) -> Result<Self> {
let url = Url::parse(&url)?;
Ok(Self { url, token })
pub fn new(url: &str, token: &str) -> Result<Self> {
let url = Url::parse(url)?;
Ok(Self {
url,
token: token.to_string(),
})
}
}

Expand All @@ -33,9 +36,13 @@ pub struct BackupGitlabOptions {
}

impl BackupGitlabOptions {
pub fn new(url: String, token: String, group: Option<String>) -> Result<Self> {
let url = Url::parse(&url)?;
Ok(Self { url, token, group })
pub fn new(url: &str, token: &str, group: Option<String>) -> Result<Self> {
let url = Url::parse(url)?;
Ok(Self {
url,
token: token.to_string(),
group,
})
}
}

Expand Down Expand Up @@ -99,9 +106,7 @@ fn make_git_path(
) -> String {
if let Some(auth) = git_http_auth {
let parts: Vec<&str> = project.http_url_to_repo.split("://").collect();
if parts.len() != 2 {
panic!("project with incorrect http path")
}
assert!(parts.len() == 2, "project with incorrect http path");
let protocol = match force_protocol {
ForceProtocol::No => parts[0],
ForceProtocol::Http => "http",
Expand Down Expand Up @@ -165,7 +170,7 @@ async fn clone_project(
let mut project_groups: Vec<types::Group> = Vec::new();

for group in &path[..path.len() - 1] {
last_group = last_group + &group;
last_group += group;
let g_info = {
let mut groups_info = groups_info.lock().await;

Expand All @@ -186,7 +191,7 @@ async fn clone_project(
.await?;

let remote = make_git_path(&backup_project, backup_git_http_auth, backup_force_protocol);
git::push_backup(format!("{}/{}", dst, p_path), remote).await?;
git::push_backup(format!("{dst}/{p_path}"), remote).await?;
Ok(())
}

Expand Down Expand Up @@ -240,7 +245,7 @@ pub async fn clone(p: CloneParams) -> Result<()> {
}

if let Some(patterns) = p.patterns {
projects = filter_projects(projects, patterns, p.limit)?
projects = filter_projects(projects, patterns, p.limit)?;
}

if projects.is_empty() {
Expand All @@ -254,7 +259,7 @@ pub async fn clone(p: CloneParams) -> Result<()> {
};

if p.clear_dst {
clear_dst(&dst)
clear_dst(&dst);
}

let backup_data = if let Some(backup) = p.backup {
Expand Down Expand Up @@ -298,7 +303,7 @@ pub async fn clone(p: CloneParams) -> Result<()> {
println!(
"Backup group: {} (id: {}, path: {})",
g.name, g.id, g.full_path
)
);
};
}
println!("Local out dir: {}", &dst);
Expand Down
8 changes: 4 additions & 4 deletions src/git.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ async fn update(path: &String, only_master: bool) -> Result<()> {
let branches_out = git(vec!["-C", path, "branch", "-la"]).await?;
let branches = branches_out
.split('\n')
.map(|v| v.trim())
.map(str::trim)
.filter(|v| !v.is_empty())
.filter(|v| !v.starts_with("remotes/origin/HEAD"))
.filter(|v| !v.starts_with("remotes/backup"));
Expand Down Expand Up @@ -104,17 +104,17 @@ async fn add_remote_backup(path: &String, remote: String) -> Result<()> {

async fn push_all_remote_backup(path: String) -> Result<()> {
if let Err(e) = git(vec!["-C", &path, "push", "-u", "backup", "--all"]).await {
error!("{}", e)
error!("{}", e);
};
if let Err(e) = git(vec!["-C", &path, "push", "-u", "backup", "--tags"]).await {
error!("{}", e)
error!("{}", e);
};
Ok(())
}

pub async fn fetch(src: String, dst: String, only_master: bool) -> Result<()> {
match check_status(&dst).await {
Ok(_) => (),
Ok(()) => (),
Err(_) => clone(&src, &dst).await?,
};
update(&dst, only_master).await
Expand Down
48 changes: 21 additions & 27 deletions src/gitlab/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,10 @@ impl Client {
http = http.timeout(Duration::from_secs(timeout.into()));
}
let http = http.build()?;
let limit = if let Some(opp) = opp { opp } else { 100 };
let limit = opp.unwrap_or(100);
let token = token.to_string();

url.set_path(&format!("api/{}", API_VERSION));
url.set_path(&format!("api/{API_VERSION}"));

Ok(Client {
url,
Expand Down Expand Up @@ -68,7 +68,7 @@ impl Client {
.header("PRIVATE-TOKEN", &self.token);

if let Some(json) = json {
req = req.json(&json)
req = req.json(&json);
}

req
Expand All @@ -89,13 +89,13 @@ impl Client {

pub async fn get_project(&self, path: String) -> reqwest::Result<types::Project> {
let path = urlencoding::encode(&path);
self.request(Method::GET, format!("projects/{}", path), None, None::<()>)
self.request(Method::GET, format!("projects/{path}"), None, None::<()>)
.await?
.json::<types::Project>()
.await
}

fn exist<T>(&self, resp: reqwest::Result<T>) -> reqwest::Result<Option<T>> {
fn check_exists<T>(resp: reqwest::Result<T>) -> reqwest::Result<Option<T>> {
match resp {
Ok(p) => Ok(Some(p)),
Err(e) => {
Expand All @@ -110,7 +110,7 @@ impl Client {
}

pub async fn project_exist(&self, path: String) -> reqwest::Result<Option<types::Project>> {
self.exist(self.get_project(path).await)
Client::check_exists(self.get_project(path).await)
}

/// Parse value of Link header
Expand All @@ -130,9 +130,7 @@ impl Client {
.split(';')
.nth(next_page_link_position)
.expect(&invalid_link_msg);
if link.len() < 13 {
panic!("{}", invalid_link_msg);
}
assert!(link.len() >= 13, "{}", invalid_link_msg);
link[1..link.len() - 1].to_string()
}

Expand All @@ -147,7 +145,7 @@ impl Client {

let method = match group {
None => "projects".to_owned(),
Some(group) => format!("groups/{}/projects", group),
Some(group) => format!("groups/{group}/projects"),
};

let mut next_page_link_position = 0;
Expand All @@ -167,13 +165,13 @@ impl Client {
} else {
let mut query = format!("order_by=id&sort=asc&per_page={}", &self.limit);
if only_owned {
query += "&owned=true"
query += "&owned=true";
}
if only_membership {
query += "&only_membership=true"
query += "&only_membership=true";
}
if method != "projects" {
query += "&include_subgroups=true"
query += "&include_subgroups=true";
}
query
};
Expand All @@ -186,17 +184,13 @@ impl Client {

projects.append(&mut resp.json::<Vec<types::Project>>().await?);

match headers.get("x-next-page") {
None => break,
Some(has_next_page) => {
if has_next_page
.to_str()
.expect("Invalid x-next-page header")
.is_empty()
{
break;
}
}
let has_next_page = match headers.get("x-next-page") {
Some(h) => !h.to_str().expect("Invalid x-next-page header").is_empty(),
None => false,
};

if !has_next_page {
break;
}

let Some(link_header) = headers.get("link") else {
Expand Down Expand Up @@ -285,14 +279,14 @@ impl Client {

pub async fn get_group(&self, path: &str) -> reqwest::Result<types::Group> {
let path = urlencoding::encode(path);
self.request(Method::GET, format!("groups/{}", path), None, None::<()>)
self.request(Method::GET, format!("groups/{path}"), None, None::<()>)
.await?
.json::<types::Group>()
.await
}

pub async fn group_exist(&self, path: &str) -> reqwest::Result<Option<types::Group>> {
self.exist(self.get_group(path).await)
Client::check_exists(self.get_group(path).await)
}

pub async fn make_subgroup(
Expand Down Expand Up @@ -351,7 +345,7 @@ impl Client {
}

match self
.project_exist(format!("{}/{}", current_namespace, project_slug))
.project_exist(format!("{current_namespace}/{project_slug}"))
.await?
{
Some(p) => self.update_project(&p, project_info).await,
Expand Down
Loading

0 comments on commit a0cae8f

Please sign in to comment.