smarter remote branch name

This commit is contained in:
Nikita Galaiko 2023-07-25 14:39:03 +02:00
parent c335f3e60d
commit 46dd73c189
2 changed files with 17 additions and 10 deletions

View File

@ -1,14 +1,18 @@
use std::collections::HashSet;
pub fn dedup(existing: &[&str], new: &str) -> String {
dedup_fmt(existing, new, " ")
}
// dedup makes sure that _new_ is not in _existing_ by adding a number to it.
// the number is increased until the name is unique.
pub fn dedup(existing: &[&str], new: &str) -> String {
pub fn dedup_fmt(existing: &[&str], new: &str, separator: &str) -> String {
let used_numbers = existing
.iter()
.filter(|x| x.starts_with(new))
.filter_map(|x| {
x.strip_prefix(new)
.map(|x| x.trim_start())
.and_then(|x| x.strip_prefix(separator).or(Some(x)))
.map(|x| x.parse::<i32>().unwrap_or(-1))
})
.collect::<HashSet<_>>();
@ -20,7 +24,7 @@ pub fn dedup(existing: &[&str], new: &str) -> String {
while used_numbers.contains(&number) {
number += 1;
}
format!("{} {}", new, number)
format!("{}{}{}", new, separator, number)
}
}

View File

@ -20,6 +20,7 @@ pub use branch::{Branch, BranchCreateRequest, FileOwnership, Hunk, Ownership};
pub use iterator::BranchIterator as Iterator;
use uuid::Uuid;
use crate::dedup::dedup_fmt;
use crate::{
dedup::dedup,
gb_repository,
@ -2217,13 +2218,15 @@ pub fn push(
};
let remote_branches = project_repository.git_remote_branches()?;
let existing_branches = remote_branches.iter().collect::<HashSet<_>>();
let remote_branch = if existing_branches.contains(&remote_branch) {
let now = chrono::Utc::now().format("%Y%m%d%H%M%S");
remote_branch.with_branch(&format!("{}-{}", remote_branch.branch(), now))
} else {
remote_branch
};
let existing_branches = remote_branches
.iter()
.map(|name| name.branch())
.collect::<Vec<_>>();
let remote_branch = remote_branch.with_branch(&name_to_branch(&dedup_fmt(
&existing_branches,
remote_branch.branch(),
"-",
)));
project_repository
.push(&vbranch.head, &remote_branch)