use std::fmt;
use crate::types::report::Diagnostic;
use crate::types::resolve::FetchError;
use crate::types::resolve::SourceKey;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GitStep {
LsRemote,
LsTree,
RevParse,
CatFile,
}
impl fmt::Display for GitStep {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::LsRemote => "ls-remote",
Self::LsTree => "ls-tree",
Self::RevParse => "rev-parse",
Self::CatFile => "cat-file",
})
}
}
#[must_use]
pub fn first_line(output: &[u8]) -> String {
let text = String::from_utf8_lossy(output);
text.trim()
.split(['\n', '\0'])
.next()
.unwrap_or_default()
.to_owned()
}
#[must_use]
pub fn unreadable(step: GitStep, output: &[u8]) -> FetchError {
FetchError::GitUnreadable {
subcommand: step.to_string(),
first_line: first_line(output),
}
}
#[must_use]
pub fn unreadable_at(key: &SourceKey, step: GitStep, output: &[u8]) -> Diagnostic {
Diagnostic::new(key.location(), unreadable(step, output))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::name::PackName;
type TestResult = Result<(), Box<dyn std::error::Error>>;
#[test]
fn unreadable_quotes_the_first_line() -> TestResult {
let output = b" junk\nmore\n";
assert_eq!(
unreadable(GitStep::LsRemote, output).to_string(),
"git ls-remote printed output agentstacks cannot read: \"junk\""
);
let key = SourceKey::Pack(PackName::new("core")?);
assert_eq!(
unreadable_at(&key, GitStep::LsRemote, output).to_string(),
"agentstacks.toml: packs.core: git ls-remote printed output agentstacks cannot read: \"junk\""
);
Ok(())
}
#[test]
fn unreadable_decodes_lossy_utf8() {
assert_eq!(
unreadable(GitStep::LsTree, b"a\xffb").to_string(),
"git ls-tree printed output agentstacks cannot read: \"a\u{fffd}b\""
);
}
#[test]
fn first_line_stops_at_the_first_record_of_nul_separated_output() {
assert_eq!(first_line(b"one\0two\0"), "one");
assert_eq!(first_line(b""), "");
}
#[test]
fn git_step_words() {
assert_eq!(GitStep::LsRemote.to_string(), "ls-remote");
assert_eq!(GitStep::LsTree.to_string(), "ls-tree");
assert_eq!(GitStep::RevParse.to_string(), "rev-parse");
assert_eq!(GitStep::CatFile.to_string(), "cat-file");
}
}