care_ef_zeroinstall/
lib.rs1pub mod xmlutil;
2
3use anyhow::{bail, Result};
4use itertools::Itertools;
5use log::debug;
6use path_slash::PathBufExt as _;
7use url::Url;
8
9use std::collections::BTreeMap;
10use std::io::ErrorKind;
11use std::path::{Path, PathBuf};
12use std::process::Command;
13
14pub struct Effector {
15 apps: BTreeMap<PathBuf, String>,
16}
17
18impl Effector {
19 pub fn new() -> Result<Effector> {
20 query_0install()
21 }
22}
23
24impl effectors::Callee for Effector {
25 fn start(_: std::env::Args) -> Result<Self> {
26 Effector::new()
27 }
28
29 fn detect(&mut self, path: &Path) -> Result<bool> {
30 Ok(self.apps.contains_key(path))
31 }
32
33 fn gather(&mut self, path: &Path, shadow_prefix: &Path) -> Result<()> {
34 let s = self.apps.get(path).unwrap();
35 std::fs::write(shadow_prefix.join(path), s)?;
36 Ok(())
37 }
38
39 fn affect(&mut self, path: &Path, shadow_prefix: &Path) -> Result<()> {
40 let shadow_path = shadow_prefix.join(path);
42
43 let mut url = Url::parse("http://akavel.com").unwrap();
46 let mut components = path.components();
47 let Some((scheme, host)) = components.next_tuple() else {
48 bail!("missing scheme or host in path: {path:?}");
49 };
50 let rel_path = components.collect::<PathBuf>();
51 url.set_path(&rel_path.to_slash().unwrap());
52 let Ok(_) = url.set_host(Some(host.as_os_str().to_str().unwrap())) else {
56 bail!("error setting host as: {host:?}");
57 };
58 let Ok(_) = url.set_scheme(scheme.as_os_str().to_str().unwrap()) else {
59 bail!("error setting scheme as: {scheme:?}");
60 };
61
62 let maybe_content = std::fs::read(shadow_path);
64
65 if let Err(ref err) = maybe_content {
68 if err.kind() == ErrorKind::NotFound {
69 let out = Command::new("0install")
70 .args(["remove", &String::from(url)])
71 .output()?;
72 if !out.status.success() {
73 bail!(
74 "0install remove failed; STDOUT: {:?}, STDERR: {:?}",
75 String::from_utf8_lossy(&out.stdout),
76 String::from_utf8_lossy(&out.stderr),
77 );
78 }
79 return Ok(());
81 }
82 }
83
84 let content = maybe_content?;
85 let s = std::str::from_utf8(&content)?;
86 let mut app = yaserde::de::from_str::<raw::App>(s).unwrap();
89
90 app.interface = Some(url.into());
92 let list = raw::AppList { app: vec![app] };
93 let list_file = tempfile::NamedTempFile::new()?;
94 let rs = yaserde::ser::serialize_with_writer(&list, list_file, &Default::default());
95 let Ok(list_file) = rs else {
96 bail!("{}", rs.unwrap_err());
97 };
98 let xml_path = list_file.into_temp_path();
102 debug!("- 0install {path:?}...");
103 let out = Command::new("0install")
104 .args(["import-apps", "--batch", &xml_path.to_string_lossy()])
106 .output()?;
107 if !out.status.success() {
108 bail!(
109 "0install failed; STDOUT: {:?}, STDERR: {:?}",
110 String::from_utf8_lossy(&out.stdout),
111 String::from_utf8_lossy(&out.stderr),
112 );
113 }
114
115 Ok(())
118 }
119}
120
121fn query_0install() -> Result<Effector> {
122 let stdout = Command::new("0install")
125 .args(["list-apps", "--xml"])
126 .output()?
127 .stdout;
129 let s = String::from_utf8_lossy(&stdout);
131 let app_list = yaserde::de::from_str::<raw::AppList>(&s).unwrap();
133 debug!("{:?}", app_list); let map: Result<BTreeMap<_, _>> = app_list
135 .app
136 .into_iter()
137 .map(|mut app| {
138 let url = Url::parse(&app.interface.take().unwrap())?;
139 let scheme = url.scheme().to_string();
141 let host = url.host_str().unwrap().to_string();
142 let path: PathBuf = url
143 .path_segments()
144 .unwrap()
145 .map(|s| Path::new(s).to_path_buf())
146 .collect();
147 let disk_path = Path::new(&scheme).join(host).join(path);
148 let cfg = yaserde::ser::Config {
149 perform_indent: true,
150 write_document_declaration: false,
151 indent_string: None, };
153 let xml = yaserde::ser::to_string_with_config(&app, &cfg).unwrap();
154 Ok((disk_path, xml))
155 })
156 .collect();
157 Ok(Effector { apps: map? })
159}
160
161mod raw {
162 use crate::xmlutil;
163 use yaserde::{YaDeserialize, YaSerialize};
164
165 #[derive(YaDeserialize, YaSerialize, Debug)]
166 #[yaserde(
167 rename = "app-list",
168 namespace = "http://0install.de/schema/desktop-integration/app-list"
169 )]
170 pub struct AppList {
171 #[yaserde(child)]
172 pub app: Vec<App>,
173 }
174
175 #[derive(YaDeserialize, YaSerialize, Debug)]
176 #[yaserde(rename = "app")]
177 pub struct App {
178 #[yaserde(attribute)]
179 pub interface: Option<String>,
180 #[yaserde(attribute)]
181 pub timestamp: u64,
182 #[yaserde(child)]
183 pub capabilities: Option<xmlutil::OpaqueXml>,
184 #[yaserde(child, rename = "access-points")]
185 pub access_points: Option<xmlutil::OpaqueXml>,
186 }
187}