1use anyhow::Result;
2use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
3use std::io::Write;
4use std::path::PathBuf;
5
6pub fn encode_brew_file(content: &str) -> String {
14 BASE64.encode(content.as_bytes())
15}
16
17pub fn decode_brew_file(encoded: &str) -> Result<String> {
25 let decoded = BASE64
26 .decode(encoded.trim())
27 .map_err(|e| anyhow::anyhow!("Failed to decode brew file: {}", e))?;
28
29 String::from_utf8(decoded)
30 .map_err(|e| anyhow::anyhow!("Failed to convert decoded bytes to string: {}", e))
31}
32
33pub fn patch_binary(bin_path: &PathBuf, script_path: &PathBuf) -> std::io::Result<()> {
34 let mut bin = std::fs::OpenOptions::new().append(true).open(bin_path)?;
35 let script = std::fs::read(script_path)?;
36 let len = script.len() as u64;
37
38 bin.write_all(&script)?;
39 bin.write_all(&len.to_le_bytes())?;
40 bin.write_all(b"REW!")?;
41 Ok(())
42}
43
44pub fn make_qrew(output: &PathBuf, file: &PathBuf) -> std::io::Result<()> {
45 if let Some(exe_path) = std::env::current_exe().ok() {
46 std::fs::copy(exe_path, output)?;
47 patch_binary(&output, file)
48 } else {
49 Err(std::io::Error::new(
50 std::io::ErrorKind::InvalidData,
51 "Could not find main qrew stub",
52 ))
53 }
54}
55
56pub fn to_qrew(file: PathBuf) -> PathBuf {
57 let mut new_file = file.clone();
58
59 let stem = file.file_stem().unwrap_or_default().to_string_lossy();
60
61 #[cfg(target_os = "windows")]
62 let new_name = format!("{}.qrew.exe", stem);
63
64 #[cfg(not(target_os = "windows"))]
65 let new_name = format!("{}.qrew", stem);
66
67 new_file.set_file_name(new_name);
68 new_file
69}