use crate::{utils, QmlUri, QtInstallation, QtTool};
use semver::Version;
use std::{
path::{Path, PathBuf},
process::Command,
};
pub struct QtToolQmlTypeRegistrar {
executable: PathBuf,
}
impl QtToolQmlTypeRegistrar {
pub fn new(qt_installation: &dyn QtInstallation) -> Self {
let executable = qt_installation
.try_find_tool(QtTool::QmlTypeRegistrar)
.expect("Could not find qmltyperegistrar");
utils::check_executable_help(&executable).unwrap();
Self { executable }
}
pub fn compile(
&self,
metatypes_json: &[impl AsRef<Path>],
qmltypes: impl AsRef<Path>,
uri: &QmlUri,
version: Version,
) -> Option<PathBuf> {
let metatypes_json: Vec<_> = metatypes_json
.iter()
.filter(|f| {
std::fs::metadata(f)
.unwrap_or_else(|_| panic!("couldn't open json file {}", f.as_ref().display()))
.len()
> 0
})
.map(|f| f.as_ref().to_string_lossy().into_owned())
.collect();
if metatypes_json.is_empty() {
return None;
}
let qml_uri_underscores = uri.as_underscores();
let output_folder = QtTool::QmlTypeRegistrar.writable_path();
std::fs::create_dir_all(&output_folder).expect("Could not create qmltyperegistrar dir");
let qmltyperegistrar_output_path =
output_folder.join(format!("{qml_uri_underscores}_qmltyperegistration.cpp"));
let mut args = vec![
"--generate-qmltypes".to_owned(),
qmltypes.as_ref().to_string_lossy().into_owned(),
"--major-version".to_owned(),
version.major.to_string(),
"--minor-version".to_owned(),
version.minor.to_string(),
"--import-name".to_owned(),
uri.to_string(),
"-o".to_owned(),
qmltyperegistrar_output_path.to_string_lossy().into_owned(),
];
args.extend(metatypes_json);
let cmd = Command::new(&self.executable)
.args(args)
.env_clear()
.output()
.unwrap_or_else(|_| panic!("qmltyperegistrar failed for {uri}"));
if !cmd.status.success() {
panic!(
"qmltyperegistrar failed for {uri}:\n{}",
String::from_utf8_lossy(&cmd.stderr)
);
}
Some(qmltyperegistrar_output_path)
}
}