From 9638dc44c5946eb5fe06b47c74abb2f067e7eb99 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 14:32:16 -0700 Subject: [PATCH] feat(asc): propose a rule to komorebi-application-specific-configuration A rule written from what a recording shows, and the pull request that sends it, for either komorebi: the rule goes in the file of the komorebi the recording is of (applications.json or applications.mac.json), not of the machine it is looked at on. asc::rule is the rule. It is an ignore rule, always composite so that never the whole program is ignored: the program and the class on Windows, the application and the title on a Mac, which has no class. When the program's other windows in the recording share the ghost's class, the title is added; when nothing tells the ghost from a window that is on screen no rule is written, and it says why. It puts the rule into the file changing the lines of the rule and no others: a new application is a pure insertion where it sorts (case ignored, as just sort does it), a known one gets the rule in its ignore list and its comma. The result is checked to be the old file and the rule and nothing more, and a file not laid out as jq prints it is refused instead of reprinted. Applied to the real applications.json: 16 lines added and none removed. asc::submit clones the repository into a temporary directory, branches, commits with a message that says what was seen, why an ignore rule and why one this narrow, and pushes. With gh signed in it pushes to the repository if the user may and to their fork if not (making one), and opens the pull request; without, it pushes with git and gives a link. git is used for every push, so it is the user's own credential helper that is asked. gh is looked for where Homebrew puts it, for a program started from Finder. Anything that fails leaves the clone, with the commit in it, and says what is left to do. Every location is injectable, and the tests send to local repositories, a fake gh and a hook that refuses, never to GitHub. --- komorebi-recorder/src/asc/mod.rs | 75 ++ komorebi-recorder/src/asc/rule.rs | 807 ++++++++++++++++ komorebi-recorder/src/asc/submit.rs | 1352 +++++++++++++++++++++++++++ komorebi-recorder/src/lib.rs | 1 + 4 files changed, 2235 insertions(+) create mode 100644 komorebi-recorder/src/asc/mod.rs create mode 100644 komorebi-recorder/src/asc/rule.rs create mode 100644 komorebi-recorder/src/asc/submit.rs diff --git a/komorebi-recorder/src/asc/mod.rs b/komorebi-recorder/src/asc/mod.rs new file mode 100644 index 00000000..3b060e8a --- /dev/null +++ b/komorebi-recorder/src/asc/mod.rs @@ -0,0 +1,75 @@ +//! Rules for komorebi-application-specific-configuration, written from what a recording shows. +//! +//! [komorebi-application-specific-configuration](https://github.com/LGUG2Z/komorebi-application-specific-configuration) +//! (the ASC) is where the rules that make applications "just work" with komorebi are kept for +//! everyone. A recording that shows a ghost tile ([`crate::analysis::ghost`]) is evidence for one, +//! and this module turns it into a pull request: +//! +//! - [`rule`] is the rule, as narrow as it has to be to leave the application's other windows +//! alone, and puts it into the repository's rule file without reformatting it; +//! - [`submit`] clones the repository into a temporary directory, commits the rule on a branch with +//! a message that says how it was found and why, and opens a pull request with the credentials +//! the user has already set up, and, if that cannot be done, says what is left for the user to do. +//! +//! Each komorebi has a file of its own in the repository, and a rule goes in the file of the +//! komorebi the recording is of, not of the machine it is looked at on: a Mac can look at a +//! recording of komorebi for Windows and the rule is still for Windows. See [`Platform`]. + +pub mod rule; +pub mod submit; + +use crate::analysis::flavor::Flavor; +use schemars::JsonSchema; +use serde::Serialize; + +/// Which komorebi a rule is for, and so which of the repository's files it goes in. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, JsonSchema)] +#[serde(rename_all = "kebab-case")] +pub enum Platform { + /// komorebi for Windows: `applications.json`. Programs are executable file names, and a window + /// has a class. + Windows, + /// komorebi for Mac: `applications.mac.json`. Programs are application names, and a window has + /// no class. + Macos, +} + +impl Platform { + /// Returns the platform of the komorebi a recording is of. + #[must_use] + pub fn of(flavor: Flavor) -> Self { + match flavor { + Flavor::Windows => Self::Windows, + Flavor::Macos => Self::Macos, + } + } + + /// Returns the name of the rule file of this platform in the repository. + #[must_use] + pub fn file(self) -> &'static str { + match self { + Self::Windows => "applications.json", + Self::Macos => "applications.mac.json", + } + } + + /// Returns what the platform's komorebi is called. + #[must_use] + pub fn komorebi(self) -> &'static str { + match self { + Self::Windows => "komorebi for Windows", + Self::Macos => "komorebi for Mac", + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn each_komorebi_has_its_own_file() { + assert_eq!(Platform::of(Flavor::Windows).file(), "applications.json"); + assert_eq!(Platform::of(Flavor::Macos).file(), "applications.mac.json"); + } +} diff --git a/komorebi-recorder/src/asc/rule.rs b/komorebi-recorder/src/asc/rule.rs new file mode 100644 index 00000000..b067843d --- /dev/null +++ b/komorebi-recorder/src/asc/rule.rs @@ -0,0 +1,807 @@ +//! A rule for komorebi-application-specific-configuration, and putting it in the file. +//! +//! The repository keeps its rules in `applications.json` (komorebi for Windows) and +//! `applications.mac.json` (komorebi for Mac), one entry per application, as `jq` prints them: +//! two-space indentation, the entries sorted by name with case ignored (`just sort` does it), and +//! each rule under the kind of rule it is (`ignore`, `manage`, `floating`...). A pull request that +//! reprints the whole file is a pull request nobody can read, so [`Rule::apply`] changes the text +//! of the file where the rule goes and nowhere else, and then checks that what it made is the old +//! file and the rule and nothing more. +//! +//! # Example +//! +//! ```rust +//! use komorebi_recorder::asc::rule::Applied; +//! use komorebi_recorder::asc::rule::Identifier; +//! use komorebi_recorder::asc::rule::Rule; +//! +//! let rule = Rule::ignore( +//! "DDM", +//! vec![Identifier::exe("DDM.exe"), Identifier::class("DDMWindow")], +//! ); +//! let file = "{\n \"$schema\": \"https://example.com/schema.json\",\n \"Ableton Live\": {\n \"ignore\": [\n {\n \"kind\": \"Class\",\n \"id\": \"Vst3PlugWindow\",\n \"matching_strategy\": \"Legacy\"\n }\n ]\n }\n}\n"; +//! +//! let Applied::Changed(text) = rule.apply(file)? else { +//! panic!("the rule was not there"); +//! }; +//! assert!(text.contains("\"DDM\": {")); +//! // the entry goes after the one that sorts before it, and the rest is as it was +//! assert!(text.starts_with(&file[..file.len() - 4])); +//! # Ok::<(), Box>(()) +//! ``` + +use crate::analysis::ghost::GhostTile; +use crate::asc::Platform; +use serde_json::Value; +use serde_json::json; + +/// What a rule asks about a window. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Identifier { + /// What of the window is looked at: `Exe`, `Class`, `Title` or `Path`. + pub kind: &'static str, + /// What it is looked for as. + pub id: String, + /// How it is matched: `Equals`, `StartsWith`, `EndsWith`, `Contains`, `Regex`... + pub strategy: &'static str, +} + +impl Identifier { + /// The program is exactly `exe`. + #[must_use] + pub fn exe(exe: &str) -> Self { + Self { + kind: "Exe", + id: exe.to_string(), + strategy: "Equals", + } + } + + /// The window class is exactly `class`. + #[must_use] + pub fn class(class: &str) -> Self { + Self { + kind: "Class", + id: class.to_string(), + strategy: "Equals", + } + } + + /// The window's title is exactly `title`. + #[must_use] + pub fn title(title: &str) -> Self { + Self { + kind: "Title", + id: title.to_string(), + strategy: "Equals", + } + } + + fn value(&self) -> Value { + json!({"kind": self.kind, "id": self.id, "matching_strategy": self.strategy}) + } + + /// The identifier as `jq` prints it, from `indent` spaces in: the keys in the order the + /// repository has them (a `serde_json` map would sort them). + fn text(&self, indent: usize) -> String { + let pad = " ".repeat(indent); + format!( + "{pad}{{\n{pad} \"kind\": {},\n{pad} \"id\": {},\n{pad} \"matching_strategy\": {}\n{pad}}}", + quoted(self.kind), + quoted(&self.id), + quoted(self.strategy), + ) + } +} + +fn quoted(text: &str) -> String { + serde_json::to_string(text).unwrap_or_else(|_| "\"\"".to_string()) +} + +/// A rule that ignores windows: not one of komorebi's tiles, and not touched by komorebi at all. +/// +/// More than one identifier means a composite rule, which matches a window only when all of them +/// do (the nested array of `applications.json`): the way to ignore one window of an application and +/// not the rest. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Rule { + /// The entry's name in the file: the application. + pub app: String, + /// What a window has to be, all of it. + pub identifiers: Vec, +} + +/// What [`Rule::apply`] came to. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Applied { + /// The file with the rule in it. + Changed(String), + /// The file has the rule already. + AlreadyThere, +} + +/// Why [`Rule::apply`] did not. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ApplyError { + /// The file is not JSON, or is not an object of applications. + NotAnObject(String), + /// The file is not laid out the way `jq` prints it, so the rule cannot be put in without + /// reprinting the file. + Layout(String), +} + +impl std::fmt::Display for ApplyError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::NotAnObject(why) => { + write!(f, "the file is not a JSON object of applications: {why}") + } + Self::Layout(why) => write!( + f, + "the file is not laid out as `jq` prints it, so the rule cannot be added to it: {why}" + ), + } + } +} + +impl std::error::Error for ApplyError {} + +/// Why there is no rule to write for a ghost tile. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NoRule(pub String); + +impl std::fmt::Display for NoRule { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for NoRule {} + +impl Rule { + /// A rule that ignores the windows that match every one of `identifiers`, as the entry `app`. + #[must_use] + pub fn ignore(app: &str, identifiers: Vec) -> Self { + Self { + app: app.to_string(), + identifiers, + } + } + + /// The rule that ignores a ghost tile, and only that: as narrow as it has to be to leave the + /// rest of the application's windows alone. + /// + /// It is always a composite rule, so that it is never the whole program that is ignored: + /// + /// - **Windows**: the program and the class. If another window of the program that the + /// recording saw has the same class, the class does not tell them apart, and the title is + /// added. + /// - **Mac**: the program (the application's name) and the title, which is all a Mac window has + /// to tell it from the application's others. + /// + /// # Errors + /// + /// Returns [`NoRule`] when there is not enough to write a rule that catches the ghost and + /// nothing the application is for: komorebi did not report its program, or its class on + /// Windows, or it has no title where the title is needed, or a window of the program that was on + /// screen looks exactly like it. + pub fn for_ghost(ghost: &GhostTile) -> Result { + if ghost.exe.is_empty() { + return Err(NoRule( + "komorebi did not report which program the window belongs to".to_string(), + )); + } + let mut identifiers = vec![Identifier::exe(&ghost.exe)]; + + match ghost.platform { + Platform::Windows => { + if ghost.class.is_empty() { + return Err(NoRule( + "komorebi did not report the window's class, and a rule on the program \ + alone would ignore all of its windows" + .to_string(), + )); + } + identifiers.push(Identifier::class(&ghost.class)); + let shared = ghost + .siblings + .iter() + .any(|sibling| sibling.class == ghost.class); + if shared { + // the program's windows that are on screen have this class too + if ghost.title.is_empty() + || ghost + .siblings + .iter() + .any(|sibling| sibling.title == ghost.title) + { + return Err(NoRule(format!( + "windows of {} that are on screen have the same class, and nothing \ + (its title is {}) tells them from the ghost", + ghost.exe, + if ghost.title.is_empty() { + "empty".to_string() + } else { + format!("{:?}, the same as theirs", ghost.title) + } + ))); + } + identifiers.push(Identifier::title(&ghost.title)); + } + } + Platform::Macos => { + if ghost.title.is_empty() { + return Err(NoRule( + "the window has no title, and on a Mac the title is all there is to tell it \ + from the application's other windows" + .to_string(), + )); + } + if ghost + .siblings + .iter() + .any(|sibling| sibling.title == ghost.title) + { + return Err(NoRule(format!( + "a window of {} that is on screen has the same title ({:?})", + ghost.exe, ghost.title + ))); + } + identifiers.push(Identifier::title(&ghost.title)); + } + } + + Ok(Self::ignore(&app_name(&ghost.exe), identifiers)) + } + + /// The rule as the value it is in the file: one identifier alone, or an array of them. + fn value(&self) -> Value { + match self.identifiers.as_slice() { + [one] => one.value(), + many => Value::Array(many.iter().map(Identifier::value).collect()), + } + } + + /// The rule as the file would have it, from `indent` spaces in. + fn text(&self, indent: usize) -> String { + match self.identifiers.as_slice() { + [one] => one.text(indent), + many => { + let pad = " ".repeat(indent); + let items: Vec = many.iter().map(|item| item.text(indent + 2)).collect(); + format!("{pad}[\n{}\n{pad}]", items.join(",\n")) + } + } + } + + /// The entry as a reader sees it, to read before it is sent: what goes into `platform`'s file. + #[must_use] + pub fn preview(&self) -> String { + format!( + " {}: {{\n \"ignore\": [\n{}\n ]\n }}", + quoted(&self.app), + self.text(6) + ) + } + + /// Returns the file with this rule in it. + /// + /// The entry for [`Rule::app`] is added where it sorts, or, if the file has one already, the + /// rule is added to its `ignore` list, which is made if it has none. The result is checked: it + /// must be JSON, and the same JSON as `file` with the rule added. + /// + /// # Errors + /// + /// Returns an error when `file` is not a JSON object, or is not laid out as `jq` prints it + /// (two-space indentation, entries one to a block): the rule is then not added, so as not to + /// reprint a file whose layout is not understood. + pub fn apply(&self, file: &str) -> Result { + let original: Value = serde_json::from_str(file) + .map_err(|error| ApplyError::NotAnObject(error.to_string()))?; + let Some(entries) = original.as_object() else { + return Err(ApplyError::NotAnObject("it is not an object".to_string())); + }; + + let rule = self.value(); + let existing = entries.get(&self.app); + if existing + .and_then(|entry| entry.get("ignore")) + .and_then(Value::as_array) + .is_some_and(|rules| rules.contains(&rule)) + { + return Ok(Applied::AlreadyThere); + } + + let lines: Vec<&str> = file.split_inclusive('\n').collect(); + let found = blocks(&lines)?; + let mut out: Vec = lines.iter().map(|line| (*line).to_string()).collect(); + + if let Some(block) = found.iter().find(|block| block.name == self.app) { + self.add_to(&mut out, &lines, block)?; + } else { + self.add_entry(&mut out, &found)?; + } + let text = out.concat(); + + // what was made is the file and the rule, and nothing else + let mut expected = original; + if let Some(rules) = expected + .as_object_mut() + .and_then(|entries| { + entries + .entry(self.app.clone()) + .or_insert_with(|| json!({})) + .as_object_mut() + }) + .and_then(|entry| { + entry + .entry("ignore") + .or_insert_with(|| json!([])) + .as_array_mut() + }) + { + rules.push(rule); + } + let made: Value = serde_json::from_str(&text) + .map_err(|error| ApplyError::Layout(format!("the result is not JSON ({error})")))?; + if made != expected { + return Err(ApplyError::Layout( + "the result is not the file with the rule added".to_string(), + )); + } + + // a file that was sorted still is + let names = |lines: &[&str]| -> Result, ApplyError> { + Ok(blocks(lines)?.into_iter().map(|block| block.name).collect()) + }; + let before = names(&lines)?; + let made_lines: Vec<&str> = text.split_inclusive('\n').collect(); + let after = names(&made_lines)?; + if is_sorted(&before) && !is_sorted(&after) { + return Err(ApplyError::Layout( + "the entries would no longer be sorted".to_string(), + )); + } + Ok(Applied::Changed(text)) + } + + /// Adds the rule to an entry the file has. + fn add_to(&self, out: &mut [String], lines: &[&str], block: &Block) -> Result<(), ApplyError> { + let line = |at: usize| lines[at].trim_end_matches('\n'); + // the line that opens the entry's `ignore` list, if it has one + let ignore_open = (block.start + 1..block.end).find(|at| line(*at) == " \"ignore\": ["); + + if let Some(open) = ignore_open { + let close = (open + 1..block.end) + .find(|at| matches!(line(*at), " ]" | " ],")) + .ok_or_else(|| ApplyError::Layout("an `ignore` list is not closed".to_string()))?; + if close > open + 1 { + out[close - 1] = format!("{},\n", line(close - 1)); + } + out[close] = format!("{}\n{}", self.text(6), out[close]); + return Ok(()); + } + + // no `ignore` yet: it joins the entry's other rules, after the last of them + let close = block.end; + out[close - 1] = format!("{},\n", line(close - 1)); + out[close] = format!(" \"ignore\": [\n{}\n ]\n{}", self.text(6), out[close]); + Ok(()) + } + + /// Adds an entry for the application, where its name sorts. + fn add_entry(&self, out: &mut [String], blocks: &[Block]) -> Result<(), ApplyError> { + let entry = self.preview(); + let upper = self.app.to_ascii_uppercase(); + match blocks + .iter() + .find(|block| block.name.to_ascii_uppercase() > upper) + { + Some(next) => { + out[next.start] = format!("{entry},\n{}", out[next.start]); + } + None => { + let last = blocks + .last() + .ok_or_else(|| ApplyError::Layout("the file has no entries".to_string()))?; + out[last.end] = format!("{},\n{entry}\n", out[last.end].trim_end_matches('\n')); + } + } + Ok(()) + } +} + +/// Whether the names are in the order `just sort` puts them in: case ignored. +fn is_sorted(names: &[String]) -> bool { + let upper: Vec = names.iter().map(|name| name.to_ascii_uppercase()).collect(); + upper.windows(2).all(|pair| pair[0] <= pair[1]) +} + +/// One application's entry in the file: its name and the lines it is on. +#[derive(Debug)] +struct Block { + name: String, + /// The line ` "name": {` is on. + start: usize, + /// The line ` }` or ` },` that closes it. + end: usize, +} + +/// The entries of the file, found by the layout `jq` gives them: a line ` "name": {` opens one +/// and the next ` }` or ` },` closes it. +fn blocks(lines: &[&str]) -> Result, ApplyError> { + let mut found = Vec::new(); + let mut open: Option<(String, usize)> = None; + for (at, raw) in lines.iter().enumerate() { + if raw.ends_with("\r\n") { + return Err(ApplyError::Layout("the lines end in CRLF".to_string())); + } + let line = raw.trim_end_matches('\n'); + match &open { + None => { + if let Some(rest) = line + .strip_prefix(" ") + .filter(|rest| rest.starts_with('"')) + .and_then(|rest| rest.strip_suffix(": {")) + { + let name: String = serde_json::from_str(rest).map_err(|_| { + ApplyError::Layout(format!("line {} is not an entry", at + 1)) + })?; + open = Some((name, at)); + } + } + Some((name, start)) => { + if line == " }" || line == " }," { + found.push(Block { + name: name.clone(), + start: *start, + end: at, + }); + open = None; + } + } + } + } + if open.is_some() { + return Err(ApplyError::Layout("an entry is not closed".to_string())); + } + Ok(found) +} + +/// The name of an application for its program: `DDM.exe` is `DDM`. +#[must_use] +pub fn app_name(exe: &str) -> String { + let stem = exe + .strip_suffix(".exe") + .or_else(|| exe.strip_suffix(".EXE")) + .unwrap_or(exe); + stem.to_string() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::analysis::ghost::Sibling; + + const FILE: &str = r#"{ + "$schema": "https://example.com/schema.json", + "1Password": { + "ignore": [ + { + "kind": "Exe", + "id": "1Password.exe", + "matching_strategy": "Equals" + } + ] + }, + "Ableton Live": { + "ignore": [ + { + "kind": "Class", + "id": "Vst3PlugWindow", + "matching_strategy": "Legacy" + } + ], + "manage": [ + { + "kind": "Exe", + "id": "Live.exe", + "matching_strategy": "Equals" + } + ] + }, + "Zoom": { + "floating": [ + { + "kind": "Class", + "id": "ZPContentViewWndClass", + "matching_strategy": "Equals" + } + ] + } +} +"#; + + fn ghost_rule(app: &str) -> Rule { + Rule::ignore( + app, + vec![Identifier::exe("DDM.exe"), Identifier::class("DDMWindow")], + ) + } + + fn changed(rule: &Rule, file: &str) -> String { + match rule.apply(file).expect("apply") { + Applied::Changed(text) => text, + Applied::AlreadyThere => panic!("the rule was there already"), + } + } + + #[test] + fn a_new_application_goes_where_it_sorts_and_nothing_else_moves() { + let text = changed(&ghost_rule("DDM"), FILE); + + let a = text.find("\"Ableton Live\"").expect("ableton"); + let d = text.find("\"DDM\"").expect("ddm"); + let z = text.find("\"Zoom\"").expect("zoom"); + assert!(a < d && d < z, "{text}"); + // every line of the old file is still there, in order, and the new entry is the only + // addition + let added: Vec<&str> = text + .lines() + .filter(|line| !FILE.lines().any(|old| old == *line)) + .collect(); + assert!( + added.iter().any(|line| line.contains("\"DDMWindow\"")), + "{added:?}" + ); + let old_lines: Vec<&str> = FILE.lines().collect(); + let kept: Vec<&str> = text + .lines() + .filter(|line| old_lines.contains(line)) + .collect(); + assert!(kept.len() >= old_lines.len() - 1, "{text}"); + assert!(text.ends_with("}\n")); + } + + #[test] + fn sorting_ignores_case_like_just_sort() { + // `ddm` sorts after `Ableton Live` and before `Zoom` whatever its case + let text = changed(&ghost_rule("ddm"), FILE); + + let d = text.find("\"ddm\"").expect("ddm"); + assert!(text.find("\"Ableton Live\"").expect("a") < d); + assert!(d < text.find("\"Zoom\"").expect("z")); + } + + #[test] + fn an_application_that_sorts_last_is_added_at_the_end_with_the_comma_moved() { + let text = changed(&ghost_rule("ZZZ"), FILE); + + assert!(text.contains(" },\n \"ZZZ\": {"), "{text}"); + assert!(text.ends_with(" ]\n }\n}\n"), "{text}"); + } + + #[test] + fn an_application_that_sorts_first_is_added_before_the_first_entry() { + let text = changed(&ghost_rule("0Day"), FILE); + + assert!(text.find("\"0Day\"").expect("0day") < text.find("\"1Password\"").expect("1p")); + assert!(text.find("\"$schema\"").expect("schema") < text.find("\"0Day\"").expect("0day")); + } + + #[test] + fn an_application_the_file_has_gets_the_rule_in_its_ignore_list() { + let rule = Rule::ignore( + "Ableton Live", + vec![Identifier::exe("Live.exe"), Identifier::class("Ghost")], + ); + + let text = changed(&rule, FILE); + + let value: Value = serde_json::from_str(&text).expect("json"); + assert_eq!( + value["Ableton Live"]["ignore"].as_array().map(Vec::len), + Some(2) + ); + assert_eq!( + value["Ableton Live"]["manage"].as_array().map(Vec::len), + Some(1) + ); + } + + #[test] + fn an_application_with_no_ignore_list_gets_one() { + let rule = Rule::ignore("Zoom", vec![Identifier::class("Ghost")]); + + let text = changed(&rule, FILE); + + let value: Value = serde_json::from_str(&text).expect("json"); + assert_eq!(value["Zoom"]["ignore"].as_array().map(Vec::len), Some(1)); + assert_eq!(value["Zoom"]["floating"].as_array().map(Vec::len), Some(1)); + // a single identifier is not wrapped in an array + assert_eq!(value["Zoom"]["ignore"][0]["id"], "Ghost"); + } + + #[test] + fn a_rule_the_file_has_is_not_added_again() { + let rule = Rule::ignore("1Password", vec![Identifier::exe("1Password.exe")]); + + assert_eq!(rule.apply(FILE), Ok(Applied::AlreadyThere)); + } + + #[test] + fn a_composite_rule_is_the_nested_array_the_file_uses() { + let text = changed(&ghost_rule("DDM"), FILE); + + let value: Value = serde_json::from_str(&text).expect("json"); + let rule = &value["DDM"]["ignore"][0]; + assert_eq!(rule[0]["kind"], "Exe"); + assert_eq!(rule[1]["kind"], "Class"); + assert_eq!(rule[1]["matching_strategy"], "Equals"); + // and the keys are in the order of the rest of the file + assert!( + text.contains("\"kind\": \"Exe\",\n \"id\": \"DDM.exe\""), + "{text}" + ); + } + + #[test] + fn a_file_that_is_not_laid_out_like_jq_prints_it_is_refused() { + let error = ghost_rule("DDM") + .apply("{\"A\":{\"ignore\":[]}}") + .expect_err("compact"); + + assert!(matches!(error, ApplyError::Layout(_)), "{error:?}"); + assert!(matches!( + ghost_rule("DDM").apply("[]"), + Err(ApplyError::NotAnObject(_)) + )); + assert!(matches!( + ghost_rule("DDM").apply("not json"), + Err(ApplyError::NotAnObject(_)) + )); + } + + #[test] + fn what_is_quoted_is_escaped() { + let rule = Rule::ignore("A \"quoted\" app", vec![Identifier::class("a\\b")]); + + let text = changed(&rule, FILE); + + let value: Value = serde_json::from_str(&text).expect("json"); + assert_eq!(value["A \"quoted\" app"]["ignore"][0]["id"], "a\\b"); + } + + fn ghost(platform: Platform, exe: &str, class: &str, title: &str) -> GhostTile { + GhostTile { + platform, + hwnd: 1, + exe: exe.into(), + class: class.into(), + title: title.into(), + hidden_how: "cloaked".into(), + place: String::new(), + reads: 2, + first_seq: 1, + first_video_s: 0.0, + last_video_s: 1.0, + persisted_to_end: true, + siblings: Vec::new(), + } + } + + fn sibling(class: &str, title: &str) -> Sibling { + Sibling { + id: 2, + class: class.into(), + title: title.into(), + } + } + + fn kinds(rule: &Rule) -> Vec<(&'static str, String)> { + rule.identifiers + .iter() + .map(|identifier| (identifier.kind, identifier.id.clone())) + .collect() + } + + #[test] + fn a_ghost_on_windows_is_ignored_by_its_program_and_class_together() { + let ghost = ghost(Platform::Windows, "DDM.exe", "DDMWindow", ""); + + let rule = Rule::for_ghost(&ghost).expect("rule"); + + assert_eq!(rule.app, "DDM"); + assert_eq!( + kinds(&rule), + [ + ("Exe", "DDM.exe".to_string()), + ("Class", "DDMWindow".to_string()) + ] + ); + } + + #[test] + fn a_program_that_has_windows_of_another_class_keeps_the_rule_on_the_ghosts_class() { + let mut ghost = ghost(Platform::Windows, "chrome.exe", "Chrome_Helper", ""); + ghost.siblings = vec![sibling("Chrome_WidgetWin_1", "A page")]; + + let rule = Rule::for_ghost(&ghost).expect("rule"); + + // the program's real windows are another class: the class already tells them apart + assert_eq!(rule.identifiers.len(), 2); + } + + #[test] + fn a_class_the_programs_real_windows_share_is_told_apart_by_the_title() { + let mut ghost = ghost(Platform::Windows, "app.exe", "Frame", "Update helper"); + ghost.siblings = vec![sibling("Frame", "Main window")]; + + let rule = Rule::for_ghost(&ghost).expect("rule"); + + assert_eq!( + kinds(&rule), + [ + ("Exe", "app.exe".to_string()), + ("Class", "Frame".to_string()), + ("Title", "Update helper".to_string()), + ] + ); + } + + #[test] + fn nothing_is_written_that_would_ignore_what_is_on_screen() { + let mut shared_class_and_no_title = ghost(Platform::Windows, "app.exe", "Frame", ""); + shared_class_and_no_title.siblings = vec![sibling("Frame", "Main window")]; + let mut same_title = ghost(Platform::Windows, "app.exe", "Frame", "Main window"); + same_title.siblings = vec![sibling("Frame", "Main window")]; + + for ghost in [shared_class_and_no_title, same_title] { + let error = Rule::for_ghost(&ghost).expect_err("it would ignore real windows"); + assert!(error.0.contains("tells them from the ghost"), "{error}"); + } + } + + #[test] + fn a_ghost_whose_class_is_not_known_has_no_rule() { + let error = Rule::for_ghost(&ghost(Platform::Windows, "DDM.exe", "", "")).expect_err("no"); + assert!(error.0.contains("ignore all of its windows"), "{error}"); + + let error = Rule::for_ghost(&ghost(Platform::Windows, "", "Class", "")).expect_err("no"); + assert!(error.0.contains("which program"), "{error}"); + } + + #[test] + fn a_ghost_on_a_mac_is_ignored_by_its_application_and_title() { + let mut ghost = ghost(Platform::Macos, "Safari", "", "Reader Helper"); + ghost.siblings = vec![sibling("", "Apple")]; + + let rule = Rule::for_ghost(&ghost).expect("rule"); + + assert_eq!(rule.app, "Safari"); + assert_eq!( + kinds(&rule), + [ + ("Exe", "Safari".to_string()), + ("Title", "Reader Helper".to_string()), + ] + ); + } + + #[test] + fn on_a_mac_a_title_is_needed_and_must_not_be_the_title_of_a_window_on_screen() { + let error = Rule::for_ghost(&ghost(Platform::Macos, "Safari", "", "")).expect_err("no"); + assert!(error.0.contains("no title"), "{error}"); + + let mut same = ghost(Platform::Macos, "Safari", "", "Apple"); + same.siblings = vec![sibling("", "Apple")]; + let error = Rule::for_ghost(&same).expect_err("no"); + assert!(error.0.contains("same title"), "{error}"); + } + + #[test] + fn a_program_loses_its_exe_in_its_name() { + assert_eq!(app_name("WindowsTerminal.exe"), "WindowsTerminal"); + assert_eq!(app_name("Safari"), "Safari"); + } +} diff --git a/komorebi-recorder/src/asc/submit.rs b/komorebi-recorder/src/asc/submit.rs new file mode 100644 index 00000000..72c4a229 --- /dev/null +++ b/komorebi-recorder/src/asc/submit.rs @@ -0,0 +1,1352 @@ +//! Sending a rule to komorebi-application-specific-configuration as a pull request. +//! +//! [`submit`] does, with the tools the user already has and the credentials they have already set +//! up, what a person would do by hand: +//! +//! 1. clone the repository into a temporary directory (shallow: the rule file is all it needs); +//! 2. make a branch, and put the [`Rule`] in the platform's file ([`Rule::apply`]: only the lines +//! of the rule change); +//! 3. commit it, with a message that says what the rule is and how and why it was found; +//! 4. push the branch and open a pull request, as below. +//! +//! # Pushing and opening the pull request +//! +//! With the GitHub CLI (`gh`) signed in, the branch goes to the repository itself if the user may +//! write to it, and to their fork of it (made if they have none) if not, and `gh pr create` opens +//! the pull request from there. The push is `git push`, so it uses whatever credential helper the +//! user has configured for git; `gh` is used for the rest, with its own sign-in. +//! +//! Without `gh`, or not signed in to it, the branch is pushed to the repository with `git push`: +//! that works for someone who may write to it, and the pull request is then [`Outcome::Pushed`], a +//! link for the user to open it with. For anyone else it fails, as does any step that fails, and +//! then the outcome is [`Outcome::Failed`]: it keeps the clone, with the commit in it, and says +//! what is left for the user to do to push it and open the pull request themselves. +//! +//! Nothing here asks a question: git is told not to prompt on a terminal (there is none), so a +//! credential helper with a window of its own can still ask, and anything that would otherwise +//! wait for a keyboard fails instead. +//! +//! # Tests +//! +//! Where the repository and the forks are is in [`Upstream`], so that the tests send to local +//! repositories and never to GitHub. + +use super::Platform; +use super::rule::Applied; +use super::rule::Rule; +use crate::analysis::ghost::GhostTile; +use std::ffi::OsStr; +use std::ffi::OsString; +use std::io::Read; +use std::path::Path; +use std::path::PathBuf; +use std::process::Command; +use std::process::Stdio; +use std::time::Duration; +use std::time::Instant; + +/// How long any one git or `gh` command may take: a clone of a repository this small, or a push, +/// is seconds, and a credential helper's window is waiting for a person. +const COMMAND_TIMEOUT: Duration = Duration::from_secs(180); + +/// How many times the push to a fork just made is tried: GitHub takes a moment to have one. +const FORK_PUSH_TRIES: usize = 4; + +/// Where the rules go. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Upstream { + /// What `git clone` is given. + pub url: String, + /// The repository on GitHub, as `owner/name`. + pub slug: String, + /// The branch a pull request is for, and the clone is of. + pub base: String, + /// Where on the web a fork is: its address is `//`. + pub fork_base: String, +} + +impl Upstream { + /// komorebi-application-specific-configuration, on GitHub. + #[must_use] + pub fn komorebi_asc() -> Self { + Self { + url: "https://github.com/LGUG2Z/komorebi-application-specific-configuration.git" + .to_string(), + slug: "LGUG2Z/komorebi-application-specific-configuration".to_string(), + base: "master".to_string(), + fork_base: "https://github.com".to_string(), + } + } + + /// The repository's name without its owner. + fn name(&self) -> &str { + self.slug.rsplit('/').next().unwrap_or(&self.slug) + } + + /// The address of a fork of the repository by `login`. + fn fork_url(&self, login: &str) -> String { + format!("{}/{login}/{}.git", self.fork_base, self.name()) + } + + /// The web page that starts a pull request of `branch` of `owner`'s copy. + fn compare_url(&self, owner: &str, branch: &str) -> String { + format!( + "https://github.com/{}/compare/{}...{owner}:{branch}?expand=1", + self.slug, self.base + ) + } +} + +/// The programs it works with. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Tools { + /// `git`. + pub git: OsString, + /// The GitHub CLI, if there is one. + pub gh: Option, + /// Environment variables for every command: none, unless something has to be told to them + /// (the tests tell git who is committing). + pub env: Vec<(String, String)>, +} + +impl Tools { + /// Looks for `gh` on the `PATH`, and where Homebrew puts it on a Mac, which a program started + /// from Finder has no `PATH` to find: `git` is needed and not looked for, so that its absence + /// says so when it is run. + #[must_use] + pub fn detect() -> Self { + let gh = ["gh", "/opt/homebrew/bin/gh", "/usr/local/bin/gh"] + .into_iter() + .map(OsString::from) + .find(|candidate| { + run( + candidate, + &["--version"], + None, + &[], + Duration::from_secs(10), + ) + .is_ok_and(|out| out.ok) + }); + Self { + git: OsString::from("git"), + gh, + env: Vec::new(), + } + } +} + +/// What to send, and what to say about it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Proposal { + /// Which file it goes in. + pub platform: Platform, + /// The rule. + pub rule: Rule, + /// The commit's first line and the pull request's title. + pub title: String, + /// The rest of the commit message and the pull request's description. + pub body: String, +} + +impl Proposal { + /// The proposal that ignores a ghost tile: what was seen, why an ignore rule and why one this + /// narrow, and how it was found, in words for the person who reads the pull request and has to + /// decide. It is for the rule file of the komorebi the ghost was seen on. + #[must_use] + pub fn ghost_tile(ghost: &GhostTile, rule: Rule, version: &str) -> Self { + let platform = ghost.platform; + let title = format!("feat(apps): ignore the ghost window of {}", ghost.exe); + let what = match platform { + Platform::Windows => format!( + "window {hwnd} of `{exe}` (class `{class}`, {titled})", + hwnd = ghost.hwnd, + exe = ghost.exe, + class = ghost.class, + titled = quoted_title(&ghost.title), + ), + Platform::Macos => format!( + "window {hwnd} of `{exe}` ({titled})", + hwnd = ghost.hwnd, + exe = ghost.exe, + titled = quoted_title(&ghost.title), + ), + }; + let evidence = match platform { + Platform::Windows => format!( + "on every one of those reads Windows said that the window was {how}. Windows never \ + said it was on screen, and never that it was minimized, so this is not a window in \ + the middle of appearing or one a person put away", + how = ghost.hidden_how + ), + Platform::Macos => format!( + "in every one of those states the frame of the window, read from the accessibility \ + API, was {how}, and it was never a frame a person could see. (macOS cannot be asked \ + whether a window is drawn, so this is the frame komorebi had for it)", + how = ghost.hidden_how + ), + }; + let recorded_with = match platform { + Platform::Windows => "with `komorebi-recorder record --probe-windows`", + Platform::Macos => "of komorebi for Mac", + }; + let reads = match platform { + Platform::Windows => "read the state of", + Platform::Macos => "recorded the state of", + }; + let others = if ghost.siblings.is_empty() { + format!( + "The recording saw no other window of `{}`, but the application is more than this \ + window, so the rule is a composite one all the same.", + ghost.exe + ) + } else { + let mut seen: Vec = ghost + .siblings + .iter() + .map(|sibling| match platform { + Platform::Windows => format!( + "class `{}`, {}", + sibling.class, + quoted_title(&sibling.title) + ), + Platform::Macos => quoted_title(&sibling.title), + }) + .collect(); + seen.sort(); + seen.dedup(); + format!( + "`{exe}` has windows that are on screen and that this rule must not ignore: {list}.", + exe = ghost.exe, + list = seen.join("; ") + ) + }; + let matched = match platform { + Platform::Windows => { + if rule + .identifiers + .iter() + .any(|identifier| identifier.kind == "Title") + { + "the program, the class **and** the title: the program's other windows have \ + this class too, and the title is what tells the ghost from them" + } else { + "the program **and** the class" + } + } + Platform::Macos => "the application **and** the title", + }; + let body = format!( + "Ignore {what}: {komorebi} gives it a tile that a person can never see.\n\ + \n\ + ## What happened\n\ + \n\ + A recording {recorded_with} {reads} {what} {reads_n} times between {first:.1} s and \ + {last:.1} s of its video. komorebi had it in front on {place}, so it took a tile of the \ + layout, and {evidence}: the tile stays empty for as long as the window exists{lasting}.\n\ + \n\ + ## Why this rule\n\ + \n\ + The README of this repository asks for `ignore` rules for ghost windows. This one \ + is a composite rule that matches {matched}, so that only this window is ignored and not \ + the application. {others}\n\ + \n\ + ## The rule\n\ + \n\ + For `{file}`:\n\ + \n\ + ```json\n{preview}\n```\n\ + \n\ + ## How it was added\n\ + \n\ + Proposed by komorebi-recorder {version}. The entry is put where it sorts and the rest \ + of the file is unchanged, line for line. `just sort` was not run.\n\ + \n\ + Please check, as with any ignore rule, that this window is not one that people do want \ + tiled.\n", + komorebi = platform.komorebi(), + reads_n = ghost.reads, + first = ghost.first_video_s, + last = ghost.last_video_s, + place = ghost.place, + lasting = if ghost.persisted_to_end { + ", and it was still not on screen at the last read" + } else { + "" + }, + file = platform.file(), + preview = rule.preview(), + ); + Self { + platform, + rule, + title, + body, + } + } +} + +/// A title as a sentence has it: in quotes, or that there is none. +fn quoted_title(title: &str) -> String { + if title.is_empty() { + "no title".to_string() + } else { + format!("titled {title:?}") + } +} +/// What [`submit`] came to. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Outcome { + /// The repository has the rule already: there is nothing to send. + AlreadyThere, + /// The pull request is open. + Opened { + /// Where. + url: String, + /// The branch it is from. + branch: String, + }, + /// The branch is pushed to the repository, and the user is left to open the pull request. + Pushed { + /// The branch. + branch: String, + /// A link that starts the pull request. + compare_url: String, + }, + /// Something failed. What is left to do is in the failure. + Failed(Failure), +} + +/// Where it went wrong, and what the user can do instead. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Failure { + /// What was being done: `cloning the repository`, `pushing the branch`... + pub step: String, + /// What went wrong, in the tool's own words. + pub error: String, + /// The temporary directory, which has the clone and the text of the pull request in it. `None` + /// if there was none to keep. + pub dir: Option, + /// The branch the commit is on. + pub branch: String, + /// What the user does to finish, in steps. + pub instructions: String, +} + +/// A step that failed, before it is put together with where it left things. +struct StepError { + step: &'static str, + error: String, +} + +type Step = Result; + +fn fail(step: &'static str, error: impl Into) -> Step { + Err(StepError { + step, + error: error.into(), + }) +} + +/// What a command printed, and whether it succeeded. +struct Out { + ok: bool, + stdout: String, + stderr: String, +} + +impl Out { + /// What to tell the user it said: the error stream, or failing that the output. + fn said(&self) -> String { + let text = if self.stderr.trim().is_empty() { + &self.stdout + } else { + &self.stderr + }; + text.trim().to_string() + } +} + +/// Runs `program` and waits up to `timeout` for it. +/// +/// Returns an error when it cannot be started (it is not there) or does not finish in time (and +/// is then stopped). +fn run( + program: &OsStr, + args: &[&str], + dir: Option<&Path>, + env: &[(String, String)], + timeout: Duration, +) -> Result { + let mut command = Command::new(program); + command + .args(args) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + // there is no terminal to ask anything on: a credential helper with a window may still + .env("GIT_TERMINAL_PROMPT", "0"); + if let Some(dir) = dir { + command.current_dir(dir); + } + command.envs(env.iter().map(|(name, value)| (name, value))); + #[cfg(windows)] + crate::platform::process::isolate(&mut command); + + let mut child = command + .spawn() + .map_err(|error| format!("could not run {}: {error}", program.to_string_lossy()))?; + let read = |pipe: Option>| { + std::thread::spawn(move || { + let mut text = String::new(); + if let Some(mut pipe) = pipe { + let mut bytes = Vec::new(); + let _ = pipe.read_to_end(&mut bytes); + text = String::from_utf8_lossy(&bytes).into_owned(); + } + text + }) + }; + let stdout = read(child.stdout.take().map(|pipe| Box::new(pipe) as _)); + let stderr = read(child.stderr.take().map(|pipe| Box::new(pipe) as _)); + + let started = Instant::now(); + let status = loop { + match child.try_wait() { + Ok(Some(status)) => break status, + Ok(None) if started.elapsed() > timeout => { + let _ = child.kill(); + let _ = child.wait(); + return Err(format!( + "{} took longer than {} s and was stopped", + program.to_string_lossy(), + timeout.as_secs() + )); + } + Ok(None) => std::thread::sleep(Duration::from_millis(40)), + Err(error) => { + return Err(format!( + "could not wait for {}: {error}", + program.to_string_lossy() + )); + } + } + }; + Ok(Out { + ok: status.success(), + stdout: stdout.join().unwrap_or_default(), + stderr: stderr.join().unwrap_or_default(), + }) +} + +/// Everything one submission has and does. +struct Submission<'a> { + tools: &'a Tools, + upstream: &'a Upstream, + proposal: &'a Proposal, + root: PathBuf, + repo: PathBuf, + branch: String, + progress: &'a mut dyn FnMut(&str), + /// The commit was made: what the user does instead starts from it. + committed: bool, +} + +/// Returns the name of a branch for a rule, which is unique to the second so that a second +/// proposal of the same thing never meets the first in the user's fork. +fn branch_name(rule: &Rule, now: chrono::DateTime) -> String { + let slug: String = rule + .app + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() { + c.to_ascii_lowercase() + } else { + '-' + } + }) + .collect(); + let slug = slug.trim_matches('-'); + format!( + "ghost-tile/{}-{}", + if slug.is_empty() { "window" } else { slug }, + now.format("%Y%m%d-%H%M%S") + ) +} + +/// A directory in the temporary one that nothing else has: named for the time and the process, and +/// for how many were made before it, since two proposals in a second are two directories. +fn fresh_directory(now: chrono::DateTime) -> PathBuf { + static MADE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + loop { + let root = std::env::temp_dir().join(format!( + "komorebi-recorder-asc-{}-{}-{}", + now.format("%Y%m%dT%H%M%S"), + std::process::id(), + MADE.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + )); + // `create_dir` fails if it is there, so that this one is ours + if std::fs::create_dir(&root).is_ok() { + return root; + } + } +} + +/// Sends `proposal` to `upstream`, as in the [module](self) documentation. +/// +/// `progress` is told what is being done, one short line at a time, as each step starts. It runs on +/// the calling thread, which is blocked for as long as the steps take (up to a few minutes at the +/// worst), so call this off the UI thread. +/// +/// A temporary directory is made for the clone and is removed again once the pull request is open +/// or there turns out to be nothing to send; in any other case it is left, and the outcome says +/// where. +pub fn submit( + proposal: &Proposal, + tools: &Tools, + upstream: &Upstream, + progress: &mut dyn FnMut(&str), +) -> Outcome { + let now = chrono::Utc::now(); + let root = fresh_directory(now); + let mut work = Submission { + tools, + upstream, + proposal, + repo: root.join("repo"), + root, + branch: branch_name(&proposal.rule, now), + progress, + committed: false, + }; + + match work.go() { + Ok(outcome) => { + if matches!(outcome, Outcome::Opened { .. } | Outcome::AlreadyThere) { + let _ = std::fs::remove_dir_all(&work.root); + } + outcome + } + Err(error) => Outcome::Failed(work.failure(error)), + } +} + +impl Submission<'_> { + fn say(&mut self, what: &str) { + (self.progress)(what); + } + + fn git(&self, args: &[&str]) -> Result { + run( + &self.tools.git, + args, + Some(&self.repo), + &self.tools.env, + COMMAND_TIMEOUT, + ) + } + + /// A git command that has to succeed. + fn git_ok(&self, step: &'static str, args: &[&str]) -> Step { + match self.git(args) { + Ok(out) if out.ok => Ok(out), + Ok(out) => fail(step, out.said()), + Err(error) => fail(step, error), + } + } + + fn go(&mut self) -> Step { + let file = self.proposal.platform.file(); + std::fs::create_dir_all(&self.root) + .or_else(|error| fail("making a temporary directory", error.to_string()))?; + + self.say("cloning the repository"); + let clone = run( + &self.tools.git, + &[ + "clone", + "--quiet", + "--depth", + "1", + "--branch", + &self.upstream.base, + &self.upstream.url, + &self.repo.to_string_lossy(), + ], + Some(&self.root), + &self.tools.env, + COMMAND_TIMEOUT, + ); + match clone { + Ok(out) if out.ok => {} + Ok(out) => return fail("cloning the repository", out.said()), + Err(error) => return fail("cloning the repository", error), + } + + self.say("adding the rule"); + let path = self.repo.join(file); + let before = std::fs::read_to_string(&path) + .or_else(|error| fail("adding the rule", format!("could not read {file}: {error}")))?; + let after = match self.proposal.rule.apply(&before) { + Ok(Applied::Changed(text)) => text, + Ok(Applied::AlreadyThere) => return Ok(Outcome::AlreadyThere), + Err(error) => return fail("adding the rule", error.to_string()), + }; + self.git_ok( + "making a branch", + &["checkout", "--quiet", "-b", &self.branch], + )?; + std::fs::write(&path, after).or_else(|error| { + fail( + "adding the rule", + format!("could not write {file}: {error}"), + ) + })?; + + self.say("committing it"); + let message = self.root.join("commit-message.txt"); + std::fs::write( + &message, + format!("{}\n\n{}", self.proposal.title, self.proposal.body), + ) + .or_else(|error| fail("committing", error.to_string()))?; + std::fs::write( + self.root.join("pull-request.md"), + format!("{}\n\n{}", self.proposal.title, self.proposal.body), + ) + .or_else(|error| fail("committing", error.to_string()))?; + self.git_ok("committing", &["add", file])?; + self.git_ok( + "committing", + &["commit", "--quiet", "--file", &message.to_string_lossy()], + )?; + self.committed = true; + + self.push_and_open() + } + + /// Whether `gh` is there and signed in. + fn gh(&self) -> Option<&OsStr> { + let gh = self.tools.gh.as_deref()?; + run( + gh, + &["auth", "status"], + None, + &self.tools.env, + Duration::from_secs(30), + ) + .ok() + .filter(|out| out.ok) + .map(|_| gh) + } + + /// What `gh` printed for `args`, in the clone, or the failure of `step`. + fn gh_text(&self, gh: &OsStr, step: &'static str, args: &[&str]) -> Step { + match run(gh, args, Some(&self.repo), &self.tools.env, COMMAND_TIMEOUT) { + Ok(out) if out.ok => Ok(out.stdout.trim().to_string()), + Ok(out) => fail(step, out.said()), + Err(error) => fail(step, error), + } + } + + fn push_and_open(&mut self) -> Step { + let Some(gh) = self.gh().map(OsStr::to_os_string) else { + // no way to open a pull request from here: a person who may write to the repository + // can still push, and be given the link + self.say("pushing the branch"); + self.git_ok( + "pushing the branch", + &["push", "--quiet", "origin", &self.branch.clone()], + )?; + let owner = self + .upstream + .slug + .split('/') + .next() + .unwrap_or_default() + .to_string(); + return Ok(Outcome::Pushed { + compare_url: self.upstream.compare_url(&owner, &self.branch), + branch: self.branch.clone(), + }); + }; + + self.say("checking whether you may push to the repository"); + let may_push = self.gh_text( + &gh, + "checking your access", + &[ + "api", + &format!("repos/{}", self.upstream.slug), + "--jq", + ".permissions.push", + ], + )?; + + let branch = self.branch.clone(); + let head = if may_push == "true" { + self.say("pushing the branch"); + self.git_ok( + "pushing the branch", + &["push", "--quiet", "origin", &branch], + )?; + branch.clone() + } else { + self.say("forking the repository"); + self.gh_text( + &gh, + "forking the repository", + &[ + "repo", + "fork", + &self.upstream.slug, + "--clone=false", + "--remote=false", + ], + )?; + let login = self.gh_text( + &gh, + "asking who you are", + &["api", "user", "--jq", ".login"], + )?; + self.git_ok( + "adding your fork", + &["remote", "add", "fork", &self.upstream.fork_url(&login)], + )?; + + self.say("pushing the branch to your fork"); + let mut last = String::new(); + let mut pushed = false; + for attempt in 0..FORK_PUSH_TRIES { + if attempt > 0 { + std::thread::sleep(Duration::from_secs(3)); + } + match self.git(&["push", "--quiet", "fork", &branch]) { + Ok(out) if out.ok => { + pushed = true; + break; + } + Ok(out) => last = out.said(), + Err(error) => last = error, + } + } + if !pushed { + return fail("pushing the branch to your fork", last); + } + format!("{login}:{branch}") + }; + + self.say("opening the pull request"); + let body = self.root.join("pull-request-body.md"); + std::fs::write(&body, &self.proposal.body) + .or_else(|error| fail("opening the pull request", error.to_string()))?; + let output = self.gh_text( + &gh, + "opening the pull request", + &[ + "pr", + "create", + "--repo", + &self.upstream.slug, + "--base", + &self.upstream.base, + "--head", + &head, + "--title", + &self.proposal.title, + "--body-file", + &body.to_string_lossy(), + ], + )?; + let url = output + .lines() + .rev() + .map(str::trim) + .find(|line| line.starts_with("http")) + .map_or_else(|| output.clone(), str::to_string); + Ok(Outcome::Opened { url, branch }) + } + + /// The failure, with what the user can do about it. + fn failure(&self, error: StepError) -> Failure { + let dir = self.root.is_dir().then(|| self.root.clone()); + let instructions = self.instructions(&error); + Failure { + step: error.step.to_string(), + error: error.error, + dir, + branch: self.branch.clone(), + instructions, + } + } + + fn instructions(&self, error: &StepError) -> String { + let up = self.upstream; + let file = self.proposal.platform.file(); + if !self.committed { + return format!( + "The rule could not be prepared ({}). To propose it by hand, add this to {file} in \ + https://github.com/{}, in its place in the sorted list, and open a pull request:\n\n{}\n", + error.step, + up.slug, + self.proposal.rule.preview() + ); + } + let repo = self.repo.display(); + let pull_request = self.root.join("pull-request.md"); + format!( + "The rule is committed on the branch {branch} of the clone in\n {repo}\n\ + To open the pull request yourself:\n\ + \n\ + 1. Fork https://github.com/{slug} if you have not (https://github.com/{slug}/fork).\n\ + 2. In the clone, add your fork and push the branch to it:\n\ + \n\ + \x20 cd \"{repo}\"\n\ + \x20 git remote add fork https://github.com//{name}.git\n\ + \x20 git push -u fork {branch}\n\ + \n\ + 3. Open https://github.com/{slug}/compare/{base}...:{branch}?expand=1 and use \ + the title and description in\n {pr}\n", + branch = self.branch, + slug = up.slug, + name = up.name(), + base = up.base, + pr = pull_request.display(), + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::analysis::ghost::Sibling; + use crate::asc::rule::Identifier; + + fn git_available() -> bool { + run( + OsStr::new("git"), + &["--version"], + None, + &[], + Duration::from_secs(10), + ) + .is_ok_and(|out| out.ok) + } + + const FILE: &str = "{\n \"$schema\": \"https://example.com/schema.json\",\n \"Zoom\": {\n \"floating\": [\n {\n \"kind\": \"Class\",\n \"id\": \"ZPContentViewWndClass\",\n \"matching_strategy\": \"Equals\"\n }\n ],\n \"ignore\": [\n {\n \"kind\": \"Class\",\n \"id\": \"ZoomGhostClass\",\n \"matching_strategy\": \"Equals\"\n }\n ]\n }\n}\n"; + + /// The Mac file: its own layout of the same kind. + const MAC_FILE: &str = "{\n \"$schema\": \"https://example.com/mac.json\",\n \"Discord\": {\n \"ignore\": [\n [\n {\n \"kind\": \"Exe\",\n \"id\": \"Discord\",\n \"matching_strategy\": \"Equals\"\n },\n {\n \"kind\": \"Title\",\n \"id\": \"DiscordUpdater\",\n \"matching_strategy\": \"Equals\"\n }\n ]\n ]\n }\n}\n"; + + fn rule() -> Rule { + Rule::ignore( + "DDM", + vec![Identifier::exe("DDM.exe"), Identifier::class("DDMWindow")], + ) + } + + fn proposal() -> Proposal { + Proposal { + platform: Platform::Windows, + rule: rule(), + title: "feat(apps): ignore the ghost window of DDM.exe".to_string(), + body: "Why and how.\n".to_string(), + } + } + + fn git_in(dir: &Path, args: &[&str]) -> String { + let out = run( + OsStr::new("git"), + args, + Some(dir), + &identity_env(), + Duration::from_secs(30), + ) + .expect("git"); + assert!(out.ok, "git {args:?}: {}", out.said()); + out.stdout.trim().to_string() + } + + /// A bare repository with the rule file in it, on `master`, and the place to put it. + struct Fixture { + base: PathBuf, + } + + impl Fixture { + fn new(name: &str) -> Self { + let base = std::env::temp_dir().join(format!( + "komorebi-recorder-asc-test-{name}-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&base); + let seed = base.join("seed"); + std::fs::create_dir_all(&seed).expect("seed"); + git_in(&seed, &["init", "--quiet", "--initial-branch=master"]); + std::fs::write(seed.join("applications.json"), FILE).expect("file"); + std::fs::write(seed.join("applications.mac.json"), MAC_FILE).expect("mac file"); + git_in(&seed, &["add", "."]); + git_in( + &seed, + &[ + "-c", + "user.name=T", + "-c", + "user.email=t@example.com", + "commit", + "--quiet", + "-m", + "seed", + ], + ); + let bare = base.join("asc.git"); + git_in(&base, &["clone", "--quiet", "--bare", "seed", "asc.git"]); + assert!(bare.is_dir()); + Self { base } + } + + fn upstream(&self) -> Upstream { + Upstream { + url: self.base.join("asc.git").to_string_lossy().into_owned(), + slug: "LGUG2Z/komorebi-application-specific-configuration".to_string(), + base: "master".to_string(), + // forks are directories of bare repositories here + fork_base: self.base.join("forks").to_string_lossy().into_owned(), + } + } + + fn bare(&self) -> PathBuf { + self.base.join("asc.git") + } + + /// A fake `gh` that answers as a signed-in user who `may_push` or not, and says a pull + /// request was opened. + fn gh(&self, may_push: bool) -> OsString { + #[cfg(windows)] + let (name, script) = ( + "gh.cmd", + format!( + "@echo off\r\n\ + if \"%1\"==\"auth\" exit /b 0\r\n\ + if \"%1\"==\"repo\" exit /b 0\r\n\ + if \"%1\"==\"api\" if \"%2\"==\"user\" (echo someone& exit /b 0)\r\n\ + if \"%1\"==\"api\" (echo {may_push}& exit /b 0)\r\n\ + if \"%1\"==\"pr\" (echo https://github.com/LGUG2Z/x/pull/7& exit /b 0)\r\n\ + exit /b 1\r\n" + ), + ); + #[cfg(not(windows))] + let (name, script) = ( + "gh.sh", + format!( + "#!/bin/sh\n\ + case \"$1\" in\n\ + auth|repo) exit 0;;\n\ + api) if [ \"$2\" = user ]; then echo someone; else echo {may_push}; fi; exit 0;;\n\ + pr) echo https://github.com/LGUG2Z/x/pull/7; exit 0;;\n\ + esac\n\ + exit 1\n" + ), + ); + let path = self.base.join(name); + std::fs::write(&path, script).expect("fake gh"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)) + .expect("chmod"); + } + path.into_os_string() + } + + /// A bare repository for `someone`'s fork. + fn fork(&self) { + let forks = self.base.join("forks").join("someone"); + std::fs::create_dir_all(&forks).expect("forks"); + git_in( + &forks, + &[ + "clone", + "--quiet", + "--bare", + &self.bare().to_string_lossy(), + "komorebi-application-specific-configuration.git", + ], + ); + } + } + + /// Who commits: a machine under test may have no git identity of its own. + fn identity_env() -> Vec<(String, String)> { + [ + ("GIT_AUTHOR_NAME", "Test"), + ("GIT_AUTHOR_EMAIL", "test@example.com"), + ("GIT_COMMITTER_NAME", "Test"), + ("GIT_COMMITTER_EMAIL", "test@example.com"), + ] + .into_iter() + .map(|(name, value)| (name.to_string(), value.to_string())) + .collect() + } + + fn tools(gh: Option) -> Tools { + Tools { + git: "git".into(), + gh, + env: identity_env(), + } + } + + fn submit_with(tools: &Tools, upstream: &Upstream) -> (Outcome, Vec) { + let mut said = Vec::new(); + let outcome = submit(&proposal(), tools, upstream, &mut |line| { + said.push(line.to_string()) + }); + (outcome, said) + } + + #[test] + fn a_branch_is_named_for_the_application_and_the_second() { + let now = chrono::DateTime::parse_from_rfc3339("2026-10-27T11:45:01Z") + .expect("time") + .with_timezone(&chrono::Utc); + + assert_eq!(branch_name(&rule(), now), "ghost-tile/ddm-20261027-114501"); + assert_eq!( + branch_name(&Rule::ignore("Windows Terminal!", vec![]), now), + "ghost-tile/windows-terminal-20261027-114501" + ); + assert_eq!( + branch_name(&Rule::ignore("***", vec![]), now), + "ghost-tile/window-20261027-114501" + ); + } + + #[test] + fn the_pull_request_says_what_was_seen_and_why() { + let ghost = GhostTile { + platform: Platform::Windows, + hwnd: 131_072, + exe: "DDM.exe".into(), + class: "DDMWindow".into(), + title: String::new(), + hidden_how: "cloaked".into(), + place: "monitor 65537 workspace one (container 0)".into(), + reads: 3, + first_seq: 7, + first_video_s: 2.0, + last_video_s: 9.5, + persisted_to_end: true, + siblings: vec![Sibling { + id: 9, + class: "DDMMain".into(), + title: "Display Manager".into(), + }], + }; + let rule = Rule::for_ghost(&ghost).expect("rule"); + + let proposal = Proposal::ghost_tile(&ghost, rule, "0.1.1"); + + assert_eq!( + proposal.title, + "feat(apps): ignore the ghost window of DDM.exe" + ); + for expected in [ + "window 131072 of `DDM.exe` (class `DDMWindow`, no title)", + "komorebi for Windows", + "3 times", + "cloaked", + "never said it was on screen", + "the program **and** the class", + "windows that are on screen and that this rule must not ignore", + "class `DDMMain`, titled \"Display Manager\"", + "For `applications.json`", + "\"id\": \"DDMWindow\"", + "komorebi-recorder 0.1.1", + "not on screen at the last read", + ] { + assert!( + proposal.body.contains(expected), + "{expected}: {}", + proposal.body + ); + } + } + + #[test] + fn without_gh_a_branch_that_can_be_pushed_is_pushed_and_a_link_is_given() { + if !git_available() { + eprintln!("skipped: git is not available"); + return; + } + let fixture = Fixture::new("pushed"); + + let (outcome, said) = submit_with(&tools(None), &fixture.upstream()); + + let Outcome::Pushed { + branch, + compare_url, + } = outcome + else { + panic!("{outcome:#?}"); + }; + assert!(branch.starts_with("ghost-tile/ddm-"), "{branch}"); + assert!(compare_url.contains("/compare/master..."), "{compare_url}"); + assert_eq!( + said.first().map(String::as_str), + Some("cloning the repository") + ); + + // the branch is in the repository, with one commit that changed only the rule file + let files = git_in(&fixture.bare(), &["diff", "--name-only", "master", &branch]); + assert_eq!(files, "applications.json"); + let changed = git_in(&fixture.bare(), &["diff", "master", &branch]); + assert!(changed.contains("+ \"DDM\": {"), "{changed}"); + assert_eq!( + changed + .lines() + .filter(|line| line.starts_with('-') && !line.starts_with("---")) + .count(), + 0, + "an entry that sorts before another is added without touching any line: {changed}" + ); + let subject = git_in(&fixture.bare(), &["log", "-1", "--format=%s", &branch]); + assert_eq!(subject, "feat(apps): ignore the ghost window of DDM.exe"); + } + + #[test] + fn a_signed_in_gh_opens_the_pull_request_from_the_repository_when_pushing_is_allowed() { + if !git_available() { + eprintln!("skipped: git is not available"); + return; + } + let fixture = Fixture::new("opened"); + let tools = tools(Some(fixture.gh(true))); + + let (outcome, said) = submit_with(&tools, &fixture.upstream()); + + let Outcome::Opened { url, branch } = outcome else { + panic!("{outcome:#?}"); + }; + assert_eq!(url, "https://github.com/LGUG2Z/x/pull/7"); + assert!( + said.contains(&"opening the pull request".to_string()), + "{said:?}" + ); + git_in(&fixture.bare(), &["rev-parse", "--verify", &branch]); + } + + #[test] + fn without_write_access_the_branch_goes_to_a_fork_the_user_has() { + if !git_available() { + eprintln!("skipped: git is not available"); + return; + } + let fixture = Fixture::new("forked"); + fixture.fork(); + let tools = tools(Some(fixture.gh(false))); + + let (outcome, said) = submit_with(&tools, &fixture.upstream()); + + let Outcome::Opened { branch, .. } = outcome else { + panic!("{outcome:#?} {said:?}"); + }; + assert!( + said.contains(&"forking the repository".to_string()), + "{said:?}" + ); + let fork = fixture + .base + .join("forks") + .join("someone") + .join("komorebi-application-specific-configuration.git"); + git_in(&fork, &["rev-parse", "--verify", &branch]); + // and the repository itself was not pushed to + let heads = git_in(&fixture.bare(), &["branch", "--list"]); + assert!(!heads.contains("ghost-tile"), "{heads}"); + } + + #[test] + fn a_push_that_is_refused_leaves_the_clone_and_says_what_to_do() { + if !git_available() { + eprintln!("skipped: git is not available"); + return; + } + let fixture = Fixture::new("refused"); + let hook = fixture.bare().join("hooks").join("pre-receive"); + std::fs::write(&hook, "#!/bin/sh\necho 'no pushes here' >&2\nexit 1\n").expect("hook"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).expect("chmod"); + } + + let (outcome, _) = submit_with(&tools(None), &fixture.upstream()); + + let Outcome::Failed(failure) = outcome else { + panic!("{outcome:#?}"); + }; + assert_eq!(failure.step, "pushing the branch"); + assert!( + failure.error.contains("no pushes here"), + "{}", + failure.error + ); + let dir = failure.dir.expect("the clone is kept"); + // the commit is in it, and what is left to do names it + let subject = git_in(&dir.join("repo"), &["log", "-1", "--format=%s"]); + assert_eq!(subject, "feat(apps): ignore the ghost window of DDM.exe"); + assert!(dir.join("pull-request.md").is_file()); + for expected in [ + &failure.branch, + "git remote add fork", + "/fork", + "compare/master...:", + "pull-request.md", + ] { + assert!( + failure.instructions.contains(expected), + "{expected}: {}", + failure.instructions + ); + } + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn a_repository_that_cannot_be_cloned_says_so_and_gives_the_rule_to_send_by_hand() { + let mut upstream = Fixture::new("noclone").upstream(); + upstream.url = std::env::temp_dir() + .join("komorebi-recorder-asc-test-nothing-here") + .to_string_lossy() + .into_owned(); + if !git_available() { + eprintln!("skipped: git is not available"); + return; + } + + let (outcome, _) = submit_with(&tools(None), &upstream); + + let Outcome::Failed(failure) = outcome else { + panic!("{outcome:#?}"); + }; + assert_eq!(failure.step, "cloning the repository"); + assert!( + failure.instructions.contains("\"DDMWindow\""), + "{}", + failure.instructions + ); + if let Some(dir) = failure.dir { + let _ = std::fs::remove_dir_all(dir); + } + } + + #[test] + fn a_rule_the_repository_has_already_is_not_sent_again() { + if !git_available() { + eprintln!("skipped: git is not available"); + return; + } + let fixture = Fixture::new("there"); + let mut again = proposal(); + again.rule = Rule::ignore("Zoom", vec![Identifier::class("ZoomGhostClass")]); + + let mut said = Vec::new(); + let outcome = submit(&again, &tools(None), &fixture.upstream(), &mut |line| { + said.push(line.to_string()); + }); + + assert_eq!(outcome, Outcome::AlreadyThere, "{said:?}"); + // and nothing is left behind, or pushed + let heads = git_in(&fixture.bare(), &["branch", "--list"]); + assert!(!heads.contains("ghost-tile"), "{heads}"); + } + + fn mac_ghost() -> GhostTile { + GhostTile { + platform: Platform::Macos, + hwnd: 7, + exe: "Discord".into(), + class: String::new(), + title: "Rich Presence".into(), + hidden_how: "zero-sized".into(), + place: "monitor 1 workspace one (container 0)".into(), + reads: 2, + first_seq: 3, + first_video_s: 1.0, + last_video_s: 4.0, + persisted_to_end: false, + siblings: vec![Sibling { + id: 8, + class: String::new(), + title: "General | Server".into(), + }], + } + } + + #[test] + fn a_mac_ghost_is_proposed_for_the_mac_file_in_the_words_of_a_mac() { + let ghost = mac_ghost(); + let rule = Rule::for_ghost(&ghost).expect("rule"); + + let proposal = Proposal::ghost_tile(&ghost, rule, "0.1.1"); + + assert_eq!(proposal.platform, Platform::Macos); + for expected in [ + "komorebi for Mac", + "window 7 of `Discord` (titled \"Rich Presence\")", + "accessibility API", + "zero-sized", + "the application **and** the title", + "titled \"General | Server\"", + "For `applications.mac.json`", + "\"kind\": \"Title\"", + ] { + assert!( + proposal.body.contains(expected), + "{expected}: {}", + proposal.body + ); + } + for unexpected in ["Windows said", "--probe-windows", "class `"] { + assert!( + !proposal.body.contains(unexpected), + "{unexpected}: {}", + proposal.body + ); + } + } + + #[test] + fn a_mac_rule_goes_into_the_mac_file_and_the_windows_file_is_left_alone() { + if !git_available() { + eprintln!("skipped: git is not available"); + return; + } + let fixture = Fixture::new("mac"); + let ghost = mac_ghost(); + let proposal = + Proposal::ghost_tile(&ghost, Rule::for_ghost(&ghost).expect("rule"), "0.1.1"); + + let mut said = Vec::new(); + let outcome = submit(&proposal, &tools(None), &fixture.upstream(), &mut |line| { + said.push(line.to_string()); + }); + + let Outcome::Pushed { branch, .. } = outcome else { + panic!("{outcome:#?} {said:?}"); + }; + let files = git_in(&fixture.bare(), &["diff", "--name-only", "master", &branch]); + assert_eq!(files, "applications.mac.json"); + // Discord has an entry already: the rule joins its `ignore` list, after the one it has + let text = git_in( + &fixture.bare(), + &["show", &format!("{branch}:applications.mac.json")], + ); + let value: serde_json::Value = serde_json::from_str(&text).expect("json"); + let rules = value["Discord"]["ignore"].as_array().expect("ignore"); + assert_eq!(rules.len(), 2); + assert_eq!(rules[1][0]["id"], "Discord"); + assert_eq!(rules[1][1]["kind"], "Title"); + assert_eq!(rules[1][1]["id"], "Rich Presence"); + } +} diff --git a/komorebi-recorder/src/lib.rs b/komorebi-recorder/src/lib.rs index 7ce6b28d..ac65a384 100644 --- a/komorebi-recorder/src/lib.rs +++ b/komorebi-recorder/src/lib.rs @@ -77,6 +77,7 @@ pub mod analysis; pub mod annotations; pub mod app; +pub mod asc; pub mod av; pub mod capture; pub mod cli;