use std::ffi::OsStr;
use std::time::{Duration, UNIX_EPOCH};
use crate::error::{CoreError, ErrorCode};
use crate::model::sources::LapseReason;
use crate::remote::git::RunOutput;
use crate::store::utc_datetime;
use super::SourceRef;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SourceChangeKind {
HistoryRewritten,
Moved,
}
impl SourceChangeKind {
pub const fn as_str(self) -> &'static str {
self.reason().as_str()
}
pub const fn reason(self) -> LapseReason {
match self {
SourceChangeKind::HistoryRewritten => LapseReason::HistoryRewritten,
SourceChangeKind::Moved => LapseReason::Moved,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SourceChange {
pub kind: SourceChangeKind,
pub detail: Option<String>,
}
const REDIRECT_WARNING: &str = "warning: redirecting to ";
pub fn redirect_target(url: &str, stderr: &str) -> Option<String> {
let scheme = url.split_once("://")?.0;
if !scheme.eq_ignore_ascii_case("https") && !scheme.eq_ignore_ascii_case("http") {
return None;
}
stderr.lines().find_map(|line| {
let rest = line.strip_prefix(REDIRECT_WARNING)?;
let url = rest.trim().trim_end_matches('/');
let url = url.strip_suffix("/info/refs").unwrap_or(url);
(!url.is_empty()).then(|| url.to_owned())
})
}
pub fn target_of(source: &SourceRef, redirect: &str) -> Option<SourceRef> {
SourceRef::from_git_url(redirect)
.ok()
.filter(|target| target.key() != source.key())
}
pub fn moved_to(target: &SourceRef) -> SourceChange {
SourceChange {
kind: SourceChangeKind::Moved,
detail: Some(target.key().to_owned()),
}
}
pub fn moved(source: &SourceRef, output: &RunOutput) -> Option<SourceChange> {
let redirect = redirect_target(source.url(), &output.stderr)?;
target_of(source, &redirect).map(|target| moved_to(&target))
}
pub type GitIn<'a> = dyn Fn(&[&OsStr]) -> Result<RunOutput, CoreError> + 'a;
const SHALLOW_MARGIN: Duration = Duration::from_secs(86_400);
fn run_ok(git: &GitIn<'_>, args: &[&str]) -> Result<RunOutput, CoreError> {
let args: Vec<&OsStr> = args.iter().map(OsStr::new).collect();
git(&args)
}
pub fn history_rewritten(
git: &GitIn<'_>,
url: &str,
git_ref: Option<&str>,
old: &str,
new: &str,
) -> Result<bool, CoreError> {
if old.eq_ignore_ascii_case(new) {
return Ok(false);
}
let hex =
|text: &str| (4..=64).contains(&text.len()) && text.bytes().all(|b| b.is_ascii_hexdigit());
if !hex(old) || !hex(new) {
return Ok(true);
}
let shallow = run_ok(git, &["rev-parse", "--is-shallow-repository"])?;
if shallow.success && shallow.stdout.trim() == "true" {
let date = run_ok(
git,
&["show", "-s", "--format=%ct", &format!("{old}^{{commit}}")],
)?;
let seconds = date
.success
.then(|| date.stdout.trim().parse::<u64>().ok())
.flatten();
let deepen = match seconds {
Some(seconds) => {
let since = (UNIX_EPOCH + Duration::from_secs(seconds))
.checked_sub(SHALLOW_MARGIN)
.unwrap_or(UNIX_EPOCH);
format!("--shallow-since={}", utc_datetime(since))
}
None => "--unshallow".to_owned(),
};
let mut args = vec!["fetch", "--quiet", &deepen, "--", url];
if let Some(git_ref) = git_ref {
args.push(git_ref);
}
let output = run_ok(git, &args)?;
if !output.success {
let answers = run_ok(git, &["ls-remote", "--quiet", "--", url])?;
if answers.success {
return Ok(true);
}
let shown = SourceRef::from_git_url(url).map_or_else(
|_| "of this skill".to_owned(),
|source| source.url().to_owned(),
);
return Err(CoreError::new(
ErrorCode::SourceUnreachable,
SourceRef::redact_userinfo(&format!(
"the source {shown} cannot be reached to check its history: {}",
output
.stderr
.lines()
.rev()
.find(|line| !line.trim().is_empty())
.unwrap_or("git failed")
.trim()
)),
));
}
}
let ancestor = run_ok(git, &["merge-base", "--is-ancestor", old, new])?;
Ok(!ancestor.success)
}