sweet-cli 0.4.1

Cross-platform utilities and dev tools
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
use clap::Parser;
use quote::quote;
use rapidhash::RapidHashMap;
use std::path::Path;
use std::path::PathBuf;
use sweet::fs::exports::notify::EventKind;
use sweet::fs::exports::notify::event::ModifyKind;
use sweet::fs::exports::notify::event::RenameMode;
use sweet::prelude::*;
use syn::File;
use syn::Ident;
use syn::ItemMod;
use syn::ItemUse;
use syn::UseTree;


#[derive(Debug, Default, Clone, Parser)]
#[command(name = "mod")]
pub struct AutoMod {
	#[command(flatten)]
	pub watcher: FsWatcher,

	#[arg(short, long)]
	pub quiet: bool,
}

/// Returns whether a change was made
#[derive(PartialEq)]
enum DidMutate {
	No,
	/// For printing
	Yes {
		action: String,
		path: PathBuf,
	},
}


impl AutoMod {
	pub async fn run(mut self) -> Result<()> {
		self.watcher.assert_path_exists()?;
		if !self.quiet {
			println!(
				"🤘 sweet as 🤘\nWatching for file changes in {}",
				self.watcher.cwd.canonicalize()?.display()
			);
		}

		self.watcher.infallible = true;
		self.watcher.filter = self
			.watcher
			.filter
			.with_exclude("**/mod.rs")
			.with_exclude("**/lib.rs")
			.with_include("**/*.rs");
		self.watcher
			.watch_async(|e| {
				let mut files = ModFiles::default();
				let any_mutated = e
					.events
					.iter()
					.map(|e| self.handle_event(&mut files, e))
					.collect::<Result<Vec<_>>>()?
					.into_iter()
					.filter_map(|r| match r {
						DidMutate::No => None,
						DidMutate::Yes { action, path } => {
							if !self.quiet {
								println!(
									"AutoMod: {action} {}",
									PathExt::relative(&path)
										.unwrap_or(&path)
										.display(),
								);
							}
							Some(())
						}
					})
					.next()
					.is_some();
				if any_mutated {
					files.write_all()?;
				}
				Ok(())
			})
			.await?;
		Ok(())
	}


	fn handle_event(
		&self,
		files: &mut ModFiles,
		e: &WatchEvent,
	) -> Result<DidMutate> {
		enum Step {
			Insert,
			Remove,
		}

		// let (parent_mod, mod_file) = Self::insert_mod(&e.path)?;
		// self.write_file("insert", &e.path, parent_mod, mod_file)?;

		let step = match e.kind {
			EventKind::Create(_)
			| EventKind::Modify(ModifyKind::Name(RenameMode::To)) => Step::Insert,
			EventKind::Remove(_)
			| EventKind::Modify(ModifyKind::Name(RenameMode::From)) => Step::Remove,
			EventKind::Modify(ModifyKind::Name(_))
			| EventKind::Modify(ModifyKind::Data(_)) => {
				if e.path.exists() {
					Step::Insert
				} else {
					Step::Remove
				}
			}
			_ => {
				return Ok(DidMutate::No);
			}
		};

		let file_meta = FileMeta::new(&e.path)?;
		let file = files.get_mut(&file_meta.parent_mod)?;
		match step {
			Step::Insert => Self::insert_mod(file, file_meta),
			Step::Remove => Self::remove_mod(file, file_meta),
		}
	}

	/// Load the parents `mod.rs` or `lib.rs` file and insert a new module
	fn insert_mod(
		mod_file: &mut File,
		FileMeta {
			is_lib_dir,
			file_stem,
			mod_ident,
			event_path,
			..
		}: FileMeta,
	) -> Result<DidMutate> {
		for item in &mut mod_file.items {
			if let syn::Item::Mod(m) = item {
				if m.ident == file_stem {
					// module already exists, nothing to do here
					return Ok(DidMutate::No);
				}
			}
		}

		let vis = if is_lib_dir {
			quote! {pub}
		} else {
			Default::default()
		};


		let insert_pos = mod_file
			.items
			.iter()
			.position(|item| matches!(item, syn::Item::Mod(_)))
			.unwrap_or(mod_file.items.len());

		let mod_def: ItemMod = syn::parse_quote!(#vis mod #mod_ident;);
		mod_file.items.insert(insert_pos, mod_def.into());

		if is_lib_dir {
			// export in prelude
			for item in &mut mod_file.items {
				if let syn::Item::Mod(m) = item {
					if m.ident == "prelude" {
						if let Some(content) = m.content.as_mut() {
							content.1.push(
								syn::parse_quote!(pub use crate::#mod_ident::*;),
							);
						} else {
							m.content =
								Some((syn::token::Brace::default(), vec![
									syn::parse_quote!(pub use crate::#mod_ident::*;),
								]));
						}
						break;
					}
				}
			}
		} else {
			// export at root
			mod_file.items.insert(
				insert_pos + 1,
				syn::parse_quote!(pub use #mod_ident::*;),
			);
		}

		Ok(DidMutate::Yes {
			action: "insert".into(),
			path: event_path.to_path_buf(),
		})
	}

	fn remove_mod(
		mod_file: &mut File,
		FileMeta {
			is_lib_dir,
			file_stem,
			mod_ident,
			event_path,
			..
		}: FileMeta,
	) -> Result<DidMutate> {
		let mut did_mutate = false;
		mod_file.items.retain(|item| {
			if let syn::Item::Mod(m) = item {
				if m.ident == file_stem {
					did_mutate = true;
					return false;
				}
			}
			true
		});

		// Remove the re-export
		if is_lib_dir {
			// Remove from prelude
			for item in &mut mod_file.items {
				if let syn::Item::Mod(m) = item {
					if m.ident == "prelude" {
						if let Some(content) = m.content.as_mut() {
							content.1.retain(|item| {
								if let syn::Item::Use(use_item) = item {
									if let Some(last) = use_item_ident(use_item)
									{
										if last == &mod_ident {
											did_mutate = true;
											return false;
										}
									}
								}
								true
							});
						}
						break;
					}
				}
			}
		} else {
			// Remove re-export at root
			mod_file.items.retain(|item| {
				if let syn::Item::Use(use_item) = item {
					if let Some(last) = use_item_ident(use_item) {
						if last == &mod_ident {
							did_mutate = true;
							return false;
						}
					}
				}
				true
			});
		}

		Ok(match did_mutate {
			true => DidMutate::Yes {
				action: "remove".into(),
				path: event_path.to_path_buf(),
			},
			false => DidMutate::No,
		})
	}
}
/// find the first part of an ident, skiping `crate`, `super` or `self`
fn use_item_ident(use_item: &ItemUse) -> Option<&Ident> {
	const SKIP: [&str; 3] = ["crate", "super", "self"];
	match &use_item.tree {
		UseTree::Path(use_path) => {
			if SKIP.contains(&use_path.ident.to_string().as_str()) {
				match &*use_path.tree {
					UseTree::Path(use_path) => {
						return Some(&use_path.ident);
					}
					UseTree::Name(use_name) => {
						return Some(&use_name.ident);
					}
					_ => {}
				}
			} else {
				return Some(&use_path.ident);
			}
		}
		_ => {}
	}
	None
}

#[derive(Default, Clone)]
struct ModFiles {
	map: RapidHashMap<PathBuf, File>,
}

impl ModFiles {
	/// Get a mutable reference to the file at the given path.
	/// If it doesnt exist, an empty file is created, and will be
	/// written to disk on [`ModFiles::write_all`].
	pub fn get_mut(&mut self, path: impl AsRef<Path>) -> Result<&mut File> {
		let path = path.as_ref();
		if !self.map.contains_key(path) {
			// if it doesnt exist create an empty file
			let file = ReadFile::to_string(path).unwrap_or_default();
			let file = syn::parse_file(&file)?;
			self.map.insert(path.to_path_buf(), file);
		}
		Ok(self.map.get_mut(path).unwrap())
	}
	pub fn write_all(&self) -> Result<()> {
		// TODO only perform write if hash changed
		for (path, file) in &self.map {
			let file = prettyplease::unparse(file);
			FsExt::write(path, &file)?;
			println!(
				"AutoMod: write  {}",
				PathExt::relative(path).unwrap_or(path).display()
			);
		}
		Ok(())
	}
}

struct FileMeta<'a> {
	pub is_lib_dir: bool,
	pub parent_mod: PathBuf,
	pub file_stem: String,
	#[allow(dead_code)]
	pub event_path: &'a Path,
	pub mod_ident: syn::Ident,
}

impl<'a> FileMeta<'a> {
	/// Returns either `lib.rs` or `mod.rs` for the given path's parent
	fn new(event_path: &'a Path) -> Result<Self> {
		let Some(parent) = event_path.parent() else {
			anyhow::bail!("No parent found for path {}", event_path.display());
		};
		let is_lib_dir =
			parent.file_name().map(|f| f == "src").unwrap_or(false);
		let parent_mod = if is_lib_dir {
			parent.join("lib.rs")
		} else {
			parent.join("mod.rs")
		};
		let Some(file_stem) = event_path
			.file_stem()
			.map(|s| s.to_string_lossy().to_string())
		else {
			anyhow::bail!(
				"No file stem found for path {}",
				event_path.display()
			);
		};

		let mod_ident =
			syn::Ident::new(&file_stem, proc_macro2::Span::call_site());

		Ok(Self {
			event_path,
			is_lib_dir,
			parent_mod,
			file_stem,
			mod_ident,
		})
	}
}

#[cfg(test)]
mod test {
	use super::*;

	#[test]
	fn insert_works() {
		fn insert(workspace_path: impl AsRef<Path>) -> Result<String> {
			let abs = AbsPathBuf::new_unchecked(
				FsExt::workspace_root().join(workspace_path.as_ref()),
			);
			let file_meta = FileMeta::new(abs.as_ref())?;
			let file = ReadFile::to_string(&file_meta.parent_mod)?;
			let mut file = syn::parse_file(&file)?;
			AutoMod::insert_mod(&mut file, file_meta)?;
			let file = prettyplease::unparse(&file);
			Ok(file)
		}

		let insert_lib = insert("crates/sweet-cli/src/foo.rs").unwrap();
		expect(&insert_lib).to_contain("pub mod foo;");
		expect(&insert_lib).to_contain("pub use crate::foo::*;");

		let insert_mod = insert("crates/sweet-cli/src/bench/foo.rs").unwrap();
		expect(&insert_mod).to_contain("mod foo;");
		expect(&insert_mod).to_contain("pub use foo::*;");
	}
	#[test]
	fn remove_works() {
		fn remove(workspace_path: impl AsRef<Path>) -> Result<String> {
			let abs = AbsPathBuf::new_unchecked(
				FsExt::workspace_root().join(workspace_path.as_ref()),
			);
			let file_meta = FileMeta::new(abs.as_ref())?;
			let file = ReadFile::to_string(&file_meta.parent_mod)?;
			let mut file = syn::parse_file(&file)?;
			AutoMod::remove_mod(&mut file, file_meta)?;
			let file = prettyplease::unparse(&file);
			Ok(file)
		}

		let remove_lib = remove("crates/sweet-cli/src/automod").unwrap();
		expect(&remove_lib).not().to_contain("pub mod automod;");
		expect(&remove_lib)
			.not()
			.to_contain("pub use crate::automod::*;");


		let remove_mod =
			remove("crates/sweet-cli/src/bench/bench_assert.rs").unwrap();
		expect(&remove_mod)
			.not()
			.to_contain("pub mod bench_assert;");
		expect(&remove_mod)
			.not()
			.to_contain("pub use bench_assert::*;");
	}
}