rew_brew/
lib.rs

1use anyhow::Result;
2use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
3use std::io::Write;
4use std::path::PathBuf;
5
6/// Encodes the provided string content into Base64 format.
7///
8/// # Arguments
9/// * `content` - The string to encode.
10///
11/// # Returns
12/// * A Base64 encoded string.
13pub fn encode_brew_file(content: &str) -> String {
14  BASE64.encode(content.as_bytes())
15}
16
17/// Decodes a Base64 encoded string back into its original form.
18///
19/// # Arguments
20/// * `encoded` - The Base64 encoded string to decode.
21///
22/// # Returns
23/// * A `Result` containing the decoded string or an error message.
24pub 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}