Debian Codegraph @

src/app_id.rs

raw
1 use std::{ops::Deref, str::FromStr};
2
3 use serde::{Deserialize, Deserializer, Serialize};
4 use zbus::zvariant::{self, Basic, Type};
5
6 /// The application ID.
7 ///
8 /// See <https://developer.gnome.org/documentation/tutorials/application-id.html>.
9 #[derive(Debug, Serialize, PartialEq, Type, Eq, Hash, Clone)]
10 pub struct AppID(String);
11
12 impl Basic for AppID {
13 const SIGNATURE_CHAR: char = String::SIGNATURE_CHAR;
14 const SIGNATURE_STR: &'static str = String::SIGNATURE_STR;
15 }
16
17 impl zvariant::NoneValue for AppID {
18 type NoneType = String;
19
20 fn null_value() -> String {
21 String::default()
22 }
23 }
24
25 impl FromStr for AppID {
26 type Err = crate::Error;
27 fn from_str(value: &str) -> Result<Self, Self::Err> {
28 if is_valid_app_id(value) {
29 Ok(Self(value.to_owned()))
30 } else {
31 Err(Self::Err::InvalidAppID)
32 }
33 }
34 }
35
36 impl TryFrom<String> for AppID {
37 type Error = crate::Error;
38
39 fn try_from(value: String) -> Result<Self, Self::Error> {
40 value.parse::<Self>()
41 }
42 }
43
44 impl TryFrom<&str> for AppID {
45 type Error = crate::Error;
46
47 fn try_from(value: &str) -> Result<Self, Self::Error> {
48 value.parse::<Self>()
49 }
50 }
51
52 impl From<AppID> for String {
53 fn from(value: AppID) -> String {
54 value.0
55 }
56 }
57
58 impl AsRef<str> for AppID {
59 fn as_ref(&self) -> &str {
60 self.0.as_ref()
61 }
62 }
63
64 impl Deref for AppID {
65 type Target = str;
66
67 fn deref(&self) -> &Self::Target {
68 &self.0
69 }
70 }
71
72 impl std::fmt::Display for AppID {
73 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74 f.write_str(self.as_ref())
75 }
76 }
77
78 impl<'de> Deserialize<'de> for AppID {
79 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
80 where
81 D: serde::Deserializer<'de>,
82 {
83 let app_id = String::deserialize(deserializer)?;
84 app_id
85 .parse::<Self>()
86 .map_err(|err| serde::de::Error::custom(err.to_string()))
87 }
88 }
89
90 /// The application ID or the desktop file name without .desktop suffix.
91 ///
92 /// As unsandboxed applications might not be defining a strict application ID,
93 /// this type allows the backend implementation to fallback to the inner string
94 /// without causing an error and manually handle those applications.
95 #[derive(Debug, Eq, Hash, PartialEq, Type)]
96 #[zvariant(signature = "s")]
97 pub struct MaybeAppID(Result<AppID, String>);
98
99 impl MaybeAppID {
100 /// Returns the inner value. If the ID is valid, then `Ok` contains the
101 /// `AppID` else `Err` contains the invalid app ID as string.
102 pub fn inner(&self) -> &Result<AppID, String> {
103 &self.0
104 }
105 }
106
107 impl zvariant::NoneValue for MaybeAppID {
108 type NoneType = String;
109
110 fn null_value() -> String {
111 String::default()
112 }
113 }
114
115 impl From<AppID> for MaybeAppID {
116 fn from(value: AppID) -> Self {
117 Self(Ok(value))
118 }
119 }
120
121 impl From<String> for MaybeAppID {
122 fn from(value: String) -> Self {
123 Self(value.parse::<AppID>().or(Err(value)))
124 }
125 }
126
127 impl From<&str> for MaybeAppID {
128 fn from(value: &str) -> Self {
129 Self(value.parse::<AppID>().or(Err(String::from(value))))
130 }
131 }
132
133 impl Serialize for MaybeAppID {
134 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
135 where
136 S: serde::Serializer,
137 {
138 serializer.serialize_str(self.to_string().as_str())
139 }
140 }
141
142 impl<'de> Deserialize<'de> for MaybeAppID {
143 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
144 where
145 D: Deserializer<'de>,
146 {
147 let inner = String::deserialize(deserializer)?;
148 Ok(Self(inner.parse::<AppID>().or(Err(inner))))
149 }
150 }
151
152 impl std::fmt::Display for MaybeAppID {
153 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154 match &self.0 {
155 Ok(app_id) => f.write_str(app_id),
156 Err(app_id) => f.write_str(app_id),
157 }
158 }
159 }
160
161 /// The ID of a file in the document store.
162 #[derive(Debug, Serialize, Deserialize, Type, PartialEq, Eq, Hash, Clone)]
163 pub struct DocumentID(String);
164
165 impl Basic for DocumentID {
166 const SIGNATURE_CHAR: char = String::SIGNATURE_CHAR;
167 const SIGNATURE_STR: &'static str = String::SIGNATURE_STR;
168 }
169
170 impl From<&str> for DocumentID {
171 fn from(value: &str) -> Self {
172 Self(value.to_owned())
173 }
174 }
175
176 impl From<String> for DocumentID {
177 fn from(value: String) -> Self {
178 Self(value)
179 }
180 }
181
182 impl From<DocumentID> for String {
183 fn from(value: DocumentID) -> String {
184 value.0
185 }
186 }
187
188 impl AsRef<str> for DocumentID {
189 fn as_ref(&self) -> &str {
190 self.0.as_ref()
191 }
192 }
193
194 impl Deref for DocumentID {
195 type Target = str;
196
197 fn deref(&self) -> &Self::Target {
198 &self.0
199 }
200 }
201
202 impl std::fmt::Display for DocumentID {
203 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
204 f.write_str(self.as_ref())
205 }
206 }
207
208 // Helpers
209
210 fn is_valid_app_id(string: &str) -> bool {
211 let len = string.len();
212
213 // The app id has to be between 0 < len <= 255
214 if len == 0 || 255 < len {
215 return false;
216 }
217
218 let elements: Vec<&str> = string.split('.').collect();
219 let segments = elements.len();
220
221 if segments < 2 {
222 return false;
223 }
224
225 for (idx_segment, element) in elements.iter().enumerate() {
226 // No empty segments.
227 if element.is_empty() {
228 return false;
229 }
230
231 for (idx_char, c) in element.chars().enumerate() {
232 // First char cannot be a digit.
233 if idx_char == 0 && c.is_ascii_digit() {
234 return false;
235 }
236 if !is_valid_app_id_char(c) {
237 return false;
238 }
239 // Only the last segment can contain `-`.
240 if idx_segment < segments - 1 && c == '-' {
241 return false;
242 }
243 }
244 }
245
246 true
247 }
248
249 /// Only valid chars are a-z A-Z 0-9 - _
250 fn is_valid_app_id_char(c: char) -> bool {
251 c.is_ascii_alphanumeric() || matches!(c, '-' | '_')
252 }
253
254 #[cfg(test)]
255 mod tests {
256 use super::*;
257
258 #[test]
259 fn test_is_valid_app_id() {
260 assert!(is_valid_app_id("a.b"));
261 assert!(is_valid_app_id("a_c.b_c.h_c"));
262 assert!(is_valid_app_id("a.c-b"));
263 assert!(is_valid_app_id("a.c2.d"));
264
265 assert!(!is_valid_app_id("a"));
266 assert!(!is_valid_app_id(""));
267 assert!(!is_valid_app_id("a-z.b.c.d"));
268 assert!(!is_valid_app_id("a.b-z.c.d"));
269 assert!(!is_valid_app_id("a.b.c-z.d"));
270 assert!(!is_valid_app_id("a.0b.c"));
271 assert!(!is_valid_app_id("a..c"));
272 assert!(!is_valid_app_id("a.é"));
273 assert!(!is_valid_app_id("a.京"));
274
275 // Tests from
276 // https://github.com/bilelmoussaoui/flatpak-vscode/blob/master/src/test/suite/extension.test.ts
277
278 assert!(is_valid_app_id("_org.SomeApp"));
279 assert!(is_valid_app_id("com.org.SomeApp"));
280 assert!(is_valid_app_id("com.org_._SomeApp"));
281 assert!(is_valid_app_id("com.org._1SomeApp"));
282 assert!(is_valid_app_id("com.org._1_SomeApp"));
283 assert!(is_valid_app_id(
284 "VeryLongApplicationId.VeryLongApplicationId.VeryLongApplicationId.VeryLongApplicationId.VeryLongApplicationId.VeryLongApplicationId.VeryLongApplicationId.VeryLongApplicationId.VeryLongApplicationId.VeryLongApplicationId.VeryLongApplicationId.a111111111111"
285 ));
286
287 assert!(!is_valid_app_id("com.org-._SomeApp"));
288 assert!(!is_valid_app_id("package"));
289 assert!(!is_valid_app_id("NoDot"));
290 assert!(!is_valid_app_id("No-dot"));
291 assert!(!is_valid_app_id("No_dot"));
292 assert!(!is_valid_app_id("Has.Two..Consecutive.Dots"));
293 assert!(!is_valid_app_id("HasThree...Consecutive.Dots"));
294 assert!(!is_valid_app_id(".StartsWith.A.Period"));
295 assert!(!is_valid_app_id("."));
296 assert!(!is_valid_app_id("Ends.With.A.Period."));
297 assert!(!is_valid_app_id("0P.Starts.With.A.Digit"));
298 assert!(!is_valid_app_id("com.org.1SomeApp"));
299 assert!(!is_valid_app_id("Element.Starts.With.A.1Digit"));
300 assert!(!is_valid_app_id(
301 "VeryLongApplicationId.VeryLongApplicationId.VeryLongApplicationId.VeryLongApplicationId.VeryLongApplicationId.VeryLongApplicationId.VeryLongApplicationId.VeryLongApplicationId.VeryLongApplicationId.VeryLongApplicationId.VeryLongApplicationId.a1111111111112"
302 ));
303 assert!(!is_valid_app_id(""));
304 assert!(!is_valid_app_id("contains.;nvalid.characters"));
305 assert!(!is_valid_app_id("con\nins.invalid.characters"));
306 assert!(!is_valid_app_id("con/ains.invalid.characters"));
307 assert!(!is_valid_app_id("conta|ns.invalid.characters"));
308 assert!(!is_valid_app_id("contæins.inva_å_lid.characters"));
309 }
310 }