surjection_core/sources/
detect.rs1use std::ffi::OsStr;
6use std::time::{Duration, UNIX_EPOCH};
7
8use crate::error::{CoreError, ErrorCode};
9use crate::model::sources::LapseReason;
10use crate::remote::git::RunOutput;
11use crate::store::utc_datetime;
12
13use super::SourceRef;
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
16pub enum SourceChangeKind {
17 HistoryRewritten,
19 Moved,
21}
22
23impl SourceChangeKind {
24 pub const fn as_str(self) -> &'static str {
25 self.reason().as_str()
26 }
27
28 pub const fn reason(self) -> LapseReason {
29 match self {
30 SourceChangeKind::HistoryRewritten => LapseReason::HistoryRewritten,
31 SourceChangeKind::Moved => LapseReason::Moved,
32 }
33 }
34}
35
36#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct SourceChange {
39 pub kind: SourceChangeKind,
40 pub detail: Option<String>,
42}
43
44const REDIRECT_WARNING: &str = "warning: redirecting to ";
47
48pub fn redirect_target(url: &str, stderr: &str) -> Option<String> {
54 let scheme = url.split_once("://")?.0;
55 if !scheme.eq_ignore_ascii_case("https") && !scheme.eq_ignore_ascii_case("http") {
56 return None;
57 }
58 stderr.lines().find_map(|line| {
59 let rest = line.strip_prefix(REDIRECT_WARNING)?;
60 let url = rest.trim().trim_end_matches('/');
61 let url = url.strip_suffix("/info/refs").unwrap_or(url);
62 (!url.is_empty()).then(|| url.to_owned())
63 })
64}
65
66pub fn target_of(source: &SourceRef, redirect: &str) -> Option<SourceRef> {
69 SourceRef::from_git_url(redirect)
70 .ok()
71 .filter(|target| target.key() != source.key())
72}
73
74pub fn moved_to(target: &SourceRef) -> SourceChange {
76 SourceChange {
77 kind: SourceChangeKind::Moved,
78 detail: Some(target.key().to_owned()),
79 }
80}
81
82pub fn moved(source: &SourceRef, output: &RunOutput) -> Option<SourceChange> {
85 let redirect = redirect_target(source.url(), &output.stderr)?;
86 target_of(source, &redirect).map(|target| moved_to(&target))
87}
88
89pub type GitIn<'a> = dyn Fn(&[&OsStr]) -> Result<RunOutput, CoreError> + 'a;
91
92const SHALLOW_MARGIN: Duration = Duration::from_secs(86_400);
95
96fn run_ok(git: &GitIn<'_>, args: &[&str]) -> Result<RunOutput, CoreError> {
97 let args: Vec<&OsStr> = args.iter().map(OsStr::new).collect();
98 git(&args)
99}
100
101pub fn history_rewritten(
111 git: &GitIn<'_>,
112 url: &str,
113 git_ref: Option<&str>,
114 old: &str,
115 new: &str,
116) -> Result<bool, CoreError> {
117 if old.eq_ignore_ascii_case(new) {
118 return Ok(false);
119 }
120 let hex =
121 |text: &str| (4..=64).contains(&text.len()) && text.bytes().all(|b| b.is_ascii_hexdigit());
122 if !hex(old) || !hex(new) {
123 return Ok(true);
125 }
126 let shallow = run_ok(git, &["rev-parse", "--is-shallow-repository"])?;
127 if shallow.success && shallow.stdout.trim() == "true" {
128 let date = run_ok(
129 git,
130 &["show", "-s", "--format=%ct", &format!("{old}^{{commit}}")],
131 )?;
132 let seconds = date
133 .success
134 .then(|| date.stdout.trim().parse::<u64>().ok())
135 .flatten();
136 let deepen = match seconds {
137 Some(seconds) => {
138 let since = (UNIX_EPOCH + Duration::from_secs(seconds))
139 .checked_sub(SHALLOW_MARGIN)
140 .unwrap_or(UNIX_EPOCH);
141 format!("--shallow-since={}", utc_datetime(since))
142 }
143 None => "--unshallow".to_owned(),
144 };
145 let mut args = vec!["fetch", "--quiet", &deepen, "--", url];
146 if let Some(git_ref) = git_ref {
147 args.push(git_ref);
148 }
149 let output = run_ok(git, &args)?;
150 if !output.success {
151 let answers = run_ok(git, &["ls-remote", "--quiet", "--", url])?;
152 if answers.success {
153 return Ok(true);
154 }
155 let shown = SourceRef::from_git_url(url).map_or_else(
156 |_| "of this skill".to_owned(),
157 |source| source.url().to_owned(),
158 );
159 return Err(CoreError::new(
160 ErrorCode::SourceUnreachable,
161 SourceRef::redact_userinfo(&format!(
162 "the source {shown} cannot be reached to check its history: {}",
163 output
164 .stderr
165 .lines()
166 .rev()
167 .find(|line| !line.trim().is_empty())
168 .unwrap_or("git failed")
169 .trim()
170 )),
171 ));
172 }
173 }
174 let ancestor = run_ok(git, &["merge-base", "--is-ancestor", old, new])?;
175 Ok(!ancestor.success)
176}