ctb_formats_applescript/applescript.rs
1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program. If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! AppleScript string escaping and literal formatting helpers.
21
22#[allow(
23 unused_imports,
24 clippy::wildcard_imports,
25 reason = "Standard workspace crate prelude"
26)]
27pub(crate) use ctb_utilities::*;
28
29/// Converts `text` into an AppleScript string literal.
30///
31/// The result is wrapped in double quotes, and any `"` or `\` characters are
32/// escaped with a leading backslash.
33pub fn escape_string(text: &str) -> String {
34 let mut out = String::with_capacity(text.len().saturating_add(2));
35 out.push('"');
36 out.push_str(escape_string_fragment(text).as_str());
37 out.push('"');
38 out
39}
40
41/// Converts `text` into an AppleScript string literal.
42///
43/// Any `"` or `\` characters are escaped with a leading backslash.
44pub fn escape_string_fragment(text: &str) -> String {
45 let mut out = String::with_capacity(text.len());
46 for ch in text.chars() {
47 match ch {
48 '\\' => out.push_str("\\\\"),
49 '"' => out.push_str("\\\""),
50 _ => out.push(ch),
51 }
52 }
53 out
54}
55
56#[cfg(test)]
57#[allow(
58 clippy::panic,
59 clippy::expect_used,
60 clippy::unwrap_used,
61 clippy::unwrap_in_result,
62 clippy::panic_in_result_fn,
63 clippy::indexing_slicing,
64 clippy::arithmetic_side_effects,
65 reason = "Standard repository test boilerplate"
66)]
67mod tests {
68 use super::*;
69
70 #[crate::ctb_test]
71 fn test_quotes() {
72 assert_eq!(escape_string(r#"a"b\c"#), r#""a\"b\\c""#);
73 assert_eq!(escape_string_fragment(r#"a"b\c"#), r#"a\"b\\c"#);
74 }
75}