use std::{
io::{self, IsTerminal},
path::{Path, PathBuf},
};
use alpm_common::MetadataFile;
use alpm_srcinfo::{
SourceInfo,
SourceInfoSchema,
SourceInfoV1,
cli::{PackagesOutputFormat, SourceInfoOutputFormat},
source_info::v1::merged::MergedPackage,
};
use alpm_types::Architecture;
use fluent_i18n::t;
use thiserror::Error;
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum Error {
#[error("{msg}", msg = t!("error-json", { "error" => .0.to_string() }))]
Json(#[from] serde_json::Error),
#[error("{msg}", msg = t!("error-no-input-file"))]
NoInputFile,
#[error(transparent)]
Srcinfo(#[from] alpm_srcinfo::Error),
}
pub fn create(
pkgbuild_path: &Path,
output_format: SourceInfoOutputFormat,
pretty: bool,
) -> Result<(), Error> {
let source_info = SourceInfoV1::from_pkgbuild(pkgbuild_path)?;
match output_format {
SourceInfoOutputFormat::Json => {
let json = if pretty {
serde_json::to_string_pretty(&source_info)?
} else {
serde_json::to_string(&source_info)?
};
println!("{json}");
}
SourceInfoOutputFormat::Srcinfo => {
print!("{}", source_info.as_srcinfo())
}
}
Ok(())
}
pub fn validate(file: Option<&PathBuf>, schema: Option<SourceInfoSchema>) -> Result<(), Error> {
let _result = parse(file, schema)?;
Ok(())
}
pub fn format_source_info(
file: Option<&PathBuf>,
schema: Option<SourceInfoSchema>,
output_format: SourceInfoOutputFormat,
pretty: bool,
) -> Result<(), Error> {
let srcinfo = parse(file, schema)?;
let SourceInfo::V1(source_info) = srcinfo;
match output_format {
SourceInfoOutputFormat::Json => {
let json = if pretty {
serde_json::to_string_pretty(&source_info)?
} else {
serde_json::to_string(&source_info)?
};
println!("{json}");
}
SourceInfoOutputFormat::Srcinfo => {
println!("{}", source_info.as_srcinfo())
}
}
Ok(())
}
pub fn format_packages(
file: Option<&PathBuf>,
schema: Option<SourceInfoSchema>,
output_format: PackagesOutputFormat,
architecture: Architecture,
pretty: bool,
) -> Result<(), Error> {
let srcinfo = parse(file, schema)?;
let SourceInfo::V1(source_info) = srcinfo;
let packages: Vec<MergedPackage> = source_info
.packages_for_architecture(architecture)
.collect();
match output_format {
PackagesOutputFormat::Json => {
let json = if pretty {
serde_json::to_string_pretty(&packages)?
} else {
serde_json::to_string(&packages)?
};
println!("{json}");
}
}
Ok(())
}
pub fn parse(
file: Option<&PathBuf>,
schema: Option<SourceInfoSchema>,
) -> Result<SourceInfo, Error> {
let source_info = if let Some(file) = file {
SourceInfo::from_file_with_schema(file, schema)?
} else if !io::stdin().is_terminal() {
SourceInfo::from_stdin_with_schema(schema)?
} else {
Err(Error::NoInputFile)?
};
Ok(source_info)
}