tony / oxwm

Branch: 76d5d6e
Switch branches/tags
master
tonybtw Fixed unecessary init requirement if user already has config file. 76d5d6e 2025-10-13
253 lines · 6.7 KB Raw Blame History
1 use anyhow::Result;
2 use std::path::PathBuf;
3 use std::process::Command;
4
5 fn main() -> Result<()> {
6 let args: Vec<String> = std::env::args().collect();
7
8 match args.get(1).map(|s| s.as_str()) {
9 Some("--init") => return init_config(),
10 Some("--recompile") => return recompile_config(),
11 Some("--version") => {
12 println!("oxwm {}", env!("CARGO_PKG_VERSION"));
13 return Ok(());
14 }
15 Some("--help") => {
16 print_help();
17 return Ok(());
18 }
19 _ => {}
20 }
21
22 let config_path = get_config_path().join("config.rs");
23 let cache_binary = get_cache_binary_path();
24
25 if !config_path.exists() {
26 init_config()?;
27 notify(
28 "OXWM First Run",
29 "Config created at ~/.config/oxwm/config.rs\nEdit and reload with Mod+Shift+R",
30 );
31 }
32
33 if !cache_binary.exists() || should_recompile(&config_path, &cache_binary)? {
34 recompile_config()?;
35 }
36
37 use std::os::unix::process::CommandExt;
38 let err = Command::new(&cache_binary).args(&args[1..]).exec();
39 eprintln!("Failed to exec: {}", err);
40 std::process::exit(1);
41 }
42
43 #[derive(Debug)]
44 enum BuildMethod {
45 NixFlake,
46 NixBuild,
47 Cargo,
48 }
49
50 fn detect_build_method() -> BuildMethod {
51 let config_dir = get_config_path();
52
53 if config_dir.join("flake.nix").exists() {
54 println!("Detected flake.nix, will use nix flake for recompilation");
55 return BuildMethod::NixFlake;
56 }
57
58 if config_dir.join("default.nix").exists() || config_dir.join("shell.nix").exists() {
59 println!("Detected nix files, will use nix-shell for recompilation");
60 return BuildMethod::NixBuild;
61 }
62
63 println!("Will use cargo for recompilation");
64 BuildMethod::Cargo
65 }
66
67 fn init_config() -> Result<()> {
68 let config_dir = get_config_path();
69 std::fs::create_dir_all(&config_dir)?;
70
71 let config_template = include_str!("../../templates/config.rs");
72 std::fs::write(config_dir.join("config.rs"), config_template)?;
73
74 let main_template = include_str!("../../templates/main.rs");
75 std::fs::write(config_dir.join("main.rs"), main_template)?;
76
77 let cargo_toml = r#"[package]
78 name = "oxwm-user"
79 version = "0.1.0"
80 edition = "2024"
81
82 [dependencies]
83 oxwm = { git = "https://github.com/tonybanters/oxwm" }
84 anyhow = "1"
85
86 [[bin]]
87 name = "oxwm-user"
88 path = "main.rs"
89 "#;
90
91 std::fs::write(config_dir.join("Cargo.toml"), cargo_toml)?;
92 std::fs::write(config_dir.join(".gitignore"), "target/\nCargo.lock\n")?;
93
94 if is_nixos() {
95 let shell_nix = r#"{ pkgs ? import <nixpkgs> {} }:
96 pkgs.mkShell {
97 buildInputs = with pkgs; [
98 rustc
99 cargo
100 pkg-config
101 xorg.libX11
102 xorg.libXft
103 xorg.libXrender
104 freetype
105 fontconfig
106 ];
107 }
108 "#;
109 std::fs::write(config_dir.join("shell.nix"), shell_nix)?;
110 }
111
112 Ok(())
113 }
114
115 fn recompile_config() -> Result<()> {
116 let config_dir = get_config_path();
117
118 if !config_dir.join("config.rs").exists() {
119 anyhow::bail!("No config found. Run: oxwm --init");
120 }
121
122 println!("Compiling oxwm configuration...");
123
124 let build_method = detect_build_method();
125
126 let output = match build_method {
127 BuildMethod::NixFlake => {
128 println!("Using nix flake build...");
129 Command::new("nix")
130 .args(&["build", ".#", "--no-link"])
131 .current_dir(&config_dir)
132 .output()?
133 }
134 BuildMethod::NixBuild => {
135 println!("Using nix-shell...");
136 Command::new("nix-shell")
137 .args(&["--run", "cargo build --release"])
138 .current_dir(&config_dir)
139 .output()?
140 }
141 BuildMethod::Cargo => Command::new("cargo")
142 .args(&["build", "--release"])
143 .current_dir(&config_dir)
144 .output()?,
145 };
146
147 if !output.status.success() {
148 let stderr = String::from_utf8_lossy(&output.stderr);
149 eprintln!("\nāŒ Compilation failed:\n{}", stderr);
150
151 notify_error("OXWM Compile Error", "Check terminal for details");
152
153 anyhow::bail!("Failed to compile configuration");
154 }
155
156 let source = config_dir.join("target/release/oxwm-user");
157 let dest = get_cache_binary_path();
158
159 std::fs::create_dir_all(dest.parent().unwrap())?;
160
161 match std::fs::copy(&source, &dest) {
162 Ok(_) => {}
163 Err(e) if e.raw_os_error() == Some(26) => {
164 let temp_dest = dest.with_extension("new");
165 std::fs::copy(&source, &temp_dest)?;
166 std::fs::rename(&temp_dest, &dest)?;
167 }
168 Err(e) => return Err(e.into()),
169 }
170
171 println!("āœ“ Compiled successfully");
172
173 notify(
174 "OXWM",
175 "Configuration recompiled! Hit Mod+Shift+R to restart.",
176 );
177
178 Ok(())
179 }
180
181 fn is_nixos() -> bool {
182 std::path::Path::new("/etc/NIXOS").exists()
183 || std::path::Path::new("/run/current-system/nixos-version").exists()
184 || std::env::var("NIX_PATH").is_ok()
185 }
186
187 fn should_recompile(config: &PathBuf, binary: &PathBuf) -> Result<bool> {
188 if !config.exists() {
189 return Ok(false);
190 }
191
192 let config_dir = get_config_path();
193 let binary_time = std::fs::metadata(binary)?.modified()?;
194
195 let watch_files = [
196 "config.rs",
197 "main.rs",
198 "Cargo.toml",
199 "flake.nix",
200 "shell.nix",
201 ];
202
203 for filename in &watch_files {
204 let path = config_dir.join(filename);
205 if !path.exists() {
206 continue;
207 }
208
209 let file_time = std::fs::metadata(&path)?.modified()?;
210 if file_time > binary_time {
211 return Ok(true);
212 }
213 }
214
215 Ok(false)
216 }
217
218 fn get_config_path() -> PathBuf {
219 dirs::config_dir()
220 .expect("Could not find config directory")
221 .join("oxwm")
222 }
223
224 fn get_cache_binary_path() -> PathBuf {
225 dirs::cache_dir()
226 .expect("Could not find cache directory")
227 .join("oxwm/oxwm-binary")
228 }
229
230 fn notify(title: &str, body: &str) {
231 let _ = Command::new("notify-send").args(&[title, body]).spawn();
232 }
233
234 fn notify_error(title: &str, body: &str) {
235 let _ = Command::new("notify-send")
236 .args(&["-u", "critical", title, body])
237 .spawn();
238 }
239
240 fn print_help() {
241 println!("OXWM - A dynamic window manager written in Rust\n");
242 println!("USAGE:");
243 println!(" oxwm [OPTIONS]\n");
244 println!("OPTIONS:");
245 println!(" --init Recreate config template in ~/.config/oxwm");
246 println!(" --recompile Manually recompile configuration");
247 println!(" --version Print version information");
248 println!(" --help Print this help message\n");
249 println!("FIRST RUN:");
250 println!(" Just run 'oxwm' - config will be auto-generated at:");
251 println!(" ~/.config/oxwm/config.rs");
252 println!("\n Edit your config and reload with Mod+Shift+R\n");
253 }