1use std::path::{Path, PathBuf};
17use std::process::Command;
18
19pub trait Fs: Send + Sync {
20 fn read(&self, path: &Path) -> Result<String, String>;
21 fn write(&self, path: &Path, content: &str) -> Result<(), String>;
22 fn canonicalize(&self, path: &Path) -> Result<PathBuf, String>;
25 fn is_local(&self) -> bool {
27 false
28 }
29}
30
31#[derive(Debug, Default, Clone)]
32pub struct LocalFs;
33
34impl Fs for LocalFs {
35 fn is_local(&self) -> bool {
36 true
37 }
38 fn read(&self, path: &Path) -> Result<String, String> {
39 std::fs::read_to_string(path).map_err(|e| format!("cannot read {}: {e}", path.display()))
40 }
41 fn write(&self, path: &Path, content: &str) -> Result<(), String> {
42 if let Some(dir) = path.parent() {
43 std::fs::create_dir_all(dir)
44 .map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
45 }
46 std::fs::write(path, content).map_err(|e| format!("cannot write {}: {e}", path.display()))
47 }
48 fn canonicalize(&self, path: &Path) -> Result<PathBuf, String> {
49 path.canonicalize()
50 .map_err(|e| format!("{}: {e}", path.display()))
51 }
52}
53
54#[derive(Debug, Clone)]
56pub struct ContainerFs {
57 pub container_id: String,
58}
59
60impl ContainerFs {
61 fn exec(&self, args: &[&str], stdin: Option<&str>) -> Result<(String, i32), String> {
62 use std::io::Write;
63 use std::process::Stdio;
64 let mut cmd = Command::new("docker");
65 cmd.args(["exec", "-i", &self.container_id])
66 .args(args)
67 .stdin(if stdin.is_some() {
68 Stdio::piped()
69 } else {
70 Stdio::null()
71 })
72 .stdout(Stdio::piped())
73 .stderr(Stdio::piped());
74 let mut child = cmd
75 .spawn()
76 .map_err(|e| format!("docker exec failed: {e}"))?;
77 if let Some(body) = stdin {
78 child
79 .stdin
80 .take()
81 .ok_or("no stdin")?
82 .write_all(body.as_bytes())
83 .map_err(|e| format!("cannot send content: {e}"))?;
84 }
85 let out = child
86 .wait_with_output()
87 .map_err(|e| format!("docker exec failed: {e}"))?;
88 Ok((
89 String::from_utf8_lossy(&out.stdout).to_string(),
90 out.status.code().unwrap_or(-1),
91 ))
92 }
93}
94
95impl Fs for ContainerFs {
96 fn read(&self, path: &Path) -> Result<String, String> {
97 let p = path.to_string_lossy().to_string();
98 match self.exec(&["cat", "--", &p], None)? {
99 (body, 0) => Ok(body),
100 _ => Err(format!("cannot read {p} in container")),
101 }
102 }
103 fn write(&self, path: &Path, content: &str) -> Result<(), String> {
104 let p = path.to_string_lossy().to_string();
105 let dir = path
106 .parent()
107 .map(|d| d.to_string_lossy().to_string())
108 .unwrap_or_default();
109 if !dir.is_empty() {
110 self.exec(&["mkdir", "-p", "--", &dir], None)?;
111 }
112 match self.exec(&["tee", "--", &p], Some(content))? {
115 (_, 0) => Ok(()),
116 _ => Err(format!("cannot write {p} in container")),
117 }
118 }
119 fn canonicalize(&self, path: &Path) -> Result<PathBuf, String> {
120 let p = path.to_string_lossy().to_string();
121 match self.exec(&["readlink", "-f", "--", &p], None)? {
122 (out, 0) if !out.trim().is_empty() => Ok(PathBuf::from(out.trim())),
123 _ => Err(format!("cannot resolve {p} in container")),
124 }
125 }
126}
127
128pub struct SessionFs {
134 shell: crate::shell::PersistentShell,
135 fallback: Box<dyn Fs>,
136}
137
138impl SessionFs {
139 pub fn container(container_id: String, workdir: PathBuf) -> Self {
140 Self {
141 shell: crate::shell::PersistentShell::container(container_id.clone(), workdir),
142 fallback: Box::new(ContainerFs { container_id }),
143 }
144 }
145
146 pub fn local(root: PathBuf) -> Self {
148 Self {
149 shell: crate::shell::PersistentShell::local(root),
150 fallback: Box::new(LocalFs),
151 }
152 }
153
154 fn run(&self, command: &str) -> Option<crate::shell::Output> {
155 use crate::shell::Shell;
156 if !self.shell.is_persistent() {
157 return None;
158 }
159 self.shell
160 .exec(command, Path::new("/"), std::time::Duration::from_secs(120))
161 .ok()
162 }
163}
164
165fn sh_quote(s: &str) -> String {
166 format!("'{}'", s.replace('\'', r"'\''"))
167}
168
169impl Fs for SessionFs {
170 fn read(&self, path: &Path) -> Result<String, String> {
171 let p = path.to_string_lossy().to_string();
172 match self.run(&format!("cat -- {}", sh_quote(&p))) {
173 Some(o) if o.exit_code == 0 => Ok(o.stdout),
174 Some(_) => Err(format!("cannot read {p} in container")),
175 None => self.fallback.read(path),
176 }
177 }
178
179 fn write(&self, path: &Path, content: &str) -> Result<(), String> {
180 let p = path.to_string_lossy().to_string();
181 let dir = path
182 .parent()
183 .map(|d| d.to_string_lossy().to_string())
184 .unwrap_or_default();
185 let mkdir = if dir.is_empty() {
186 String::new()
187 } else {
188 let d = sh_quote(&dir);
189 format!("{{ [ -d {d} ] || mkdir -p -- {d}; }} && ")
190 };
191 let delim = format!(
194 "__BLYTE_CONTENT_{}_{}__",
195 std::process::id(),
196 std::time::SystemTime::now()
197 .duration_since(std::time::UNIX_EPOCH)
198 .map(|d| d.as_nanos())
199 .unwrap_or(0)
200 );
201 let cmd = format!(
202 "IFS= read -r -d '' __blyte_w <<'{delim}' || true\n{content}\n{delim}\n\
203 __blyte_w=${{__blyte_w%$'\\n'}}; {mkdir}printf %s \"$__blyte_w\" > {}",
204 sh_quote(&p)
205 );
206 match self.run(&cmd) {
207 Some(o) if o.exit_code == 0 => Ok(()),
208 Some(_) => Err(format!("cannot write {p} in container")),
209 None => self.fallback.write(path, content),
210 }
211 }
212
213 fn canonicalize(&self, path: &Path) -> Result<PathBuf, String> {
214 let p = path.to_string_lossy().to_string();
215 match self.run(&format!("readlink -f -- {}", sh_quote(&p))) {
216 Some(o) if o.exit_code == 0 && !o.stdout.trim().is_empty() => {
217 Ok(PathBuf::from(o.stdout.trim()))
218 }
219 Some(_) => Err(format!("cannot resolve {p} in container")),
220 None => self.fallback.canonicalize(path),
221 }
222 }
223}