File: config.rs

package info (click to toggle)
rust-breezyshim 0.7.8-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 996 kB
  • sloc: makefile: 2
file content (544 lines) | stat: -rw-r--r-- 17,119 bytes parent folder | download | duplicates (2)
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
//! Configuration handling.
//!
//! This module provides access to the Breezy configuration system.
//! It allows reading and writing configuration values, and provides
//! access to credential stores.
use crate::Result;
use pyo3::prelude::*;
use pyo3::BoundObject;

/// Parse a username string into name and email components.
///
/// # Parameters
///
/// * `e` - The username string to parse, typically in the format "Name <email@example.com>".
///
/// # Returns
///
/// A tuple containing the name and email address. If no email address is present,
/// the second element will be an empty string.
pub fn parse_username(e: &str) -> (String, String) {
    if let Some((_, username, email)) =
        lazy_regex::regex_captures!(r"(.*?)\s*<?([\[\]\w+.-]+@[\w+.-]+)>?", e)
    {
        (username.to_string(), email.to_string())
    } else {
        (e.to_string(), "".to_string())
    }
}

/// Extract an email address from a username string.
///
/// # Parameters
///
/// * `e` - The username string to extract an email address from.
///
/// # Returns
///
/// The email address, or None if no email address is present.
pub fn extract_email_address(e: &str) -> Option<String> {
    let (_name, email) = parse_username(e);

    if email.is_empty() {
        None
    } else {
        Some(email)
    }
}

/// Trait for values that can be stored in a configuration.
///
/// This trait is implemented for common types like strings, integers, and booleans,
/// and can be implemented for other types that need to be stored in a configuration.
pub trait ConfigValue: for<'py> IntoPyObject<'py> {}

impl ConfigValue for String {}
impl ConfigValue for &str {}
impl ConfigValue for i64 {}
impl ConfigValue for bool {}

/// Configuration for a branch.
///
/// This struct wraps a Python branch configuration object and provides methods for
/// accessing and modifying branch-specific configuration options.
pub struct BranchConfig(Py<PyAny>);

impl Clone for BranchConfig {
    fn clone(&self) -> Self {
        Python::attach(|py| -> Self { Self(self.0.clone_ref(py)) })
    }
}

impl<'py> IntoPyObject<'py> for BranchConfig {
    type Target = PyAny;
    type Output = Bound<'py, Self::Target>;
    type Error = std::convert::Infallible;

    fn into_pyobject(self, py: Python<'py>) -> std::result::Result<Self::Output, Self::Error> {
        Ok(self.0.into_bound(py))
    }
}

impl BranchConfig {
    /// Create a new BranchConfig from a Python object.
    ///
    /// # Parameters
    ///
    /// * `o` - A Python object representing a branch configuration.
    ///
    /// # Returns
    ///
    /// A new BranchConfig instance.
    pub fn new(o: Py<PyAny>) -> Self {
        Self(o)
    }

    /// Set a user option in this branch configuration.
    ///
    /// # Parameters
    ///
    /// * `key` - The option key to set.
    /// * `value` - The value to set the option to.
    ///
    /// # Returns
    ///
    /// `Ok(())` on success, or an error if the option could not be set.
    pub fn set_user_option<T: ConfigValue>(&self, key: &str, value: T) -> Result<()> {
        Python::attach(|py| -> Result<()> {
            let py_value = value
                .into_pyobject(py)
                .map_err(|_| {
                    crate::error::Error::Other(
                        pyo3::PyErr::new::<pyo3::exceptions::PyValueError, _>(
                            "Failed to convert value to Python object",
                        ),
                    )
                })?
                .unbind();
            self.0
                .call_method1(py, "set_user_option", (key, py_value))?;
            Ok(())
        })?;
        Ok(())
    }
}

/// A stack of configuration sources.
///
/// This struct represents a stack of configuration sources, where more specific
/// sources (like branch-specific configuration) override more general sources
/// (like global configuration).
pub struct ConfigStack(Py<PyAny>);

impl ConfigStack {
    /// Create a new ConfigStack from a Python object.
    ///
    /// # Parameters
    ///
    /// * `o` - A Python object representing a configuration stack.
    ///
    /// # Returns
    ///
    /// A new ConfigStack instance.
    pub fn new(o: Py<PyAny>) -> Self {
        Self(o)
    }

    /// Get a configuration value from this stack.
    ///
    /// # Parameters
    ///
    /// * `key` - The configuration key to get.
    ///
    /// # Returns
    ///
    /// The configuration value, or None if the key is not present.
    pub fn get(&self, key: &str) -> Result<Option<Py<PyAny>>> {
        Python::attach(|py| -> Result<Option<Py<PyAny>>> {
            let value = self.0.call_method1(py, "get", (key,))?;
            if value.is_none(py) {
                Ok(None)
            } else {
                Ok(Some(value))
            }
        })
    }

    /// Set a configuration value in this stack.
    ///
    /// # Parameters
    ///
    /// * `key` - The configuration key to set.
    /// * `value` - The value to set the configuration to.
    ///
    /// # Returns
    ///
    /// `Ok(())` on success, or an error if the configuration could not be set.
    pub fn set<T: ConfigValue>(&self, key: &str, value: T) -> Result<()> {
        Python::attach(|py| -> Result<()> {
            let py_value = value
                .into_pyobject(py)
                .map_err(|_| {
                    crate::error::Error::Other(
                        pyo3::PyErr::new::<pyo3::exceptions::PyValueError, _>(
                            "Failed to convert value to Python object",
                        ),
                    )
                })?
                .unbind();
            self.0.call_method1(py, "set", (key, py_value))?;
            Ok(())
        })?;
        Ok(())
    }
}

/// Get the global configuration stack.
///
/// # Returns
///
/// The global configuration stack, or an error if it could not be retrieved.
pub fn global_stack() -> Result<ConfigStack> {
    Python::attach(|py| -> Result<ConfigStack> {
        let m = py.import("breezy.config")?;
        let stack = m.call_method0("GlobalStack")?;
        Ok(ConfigStack::new(stack.unbind()))
    })
}

/// Credentials for accessing a remote service.
///
/// This struct contains the credentials for accessing a remote service,
/// such as username, password, host, port, etc.
pub struct Credentials {
    /// The scheme of the service, like "https", "ftp", etc.
    pub scheme: Option<String>,
    /// The username for authenticating with the service.
    pub username: Option<String>,
    /// The password for authenticating with the service.
    pub password: Option<String>,
    /// The hostname of the service.
    pub host: Option<String>,
    /// The port number of the service.
    pub port: Option<i64>,
    /// The path on the service.
    pub path: Option<String>,
    /// The authentication realm of the service.
    pub realm: Option<String>,
    /// Whether to verify SSL certificates when connecting to the service.
    pub verify_certificates: Option<bool>,
}

impl<'a, 'py> FromPyObject<'a, 'py> for Credentials {
    type Error = PyErr;

    fn extract(ob: Borrowed<'a, 'py, PyAny>) -> PyResult<Self> {
        let scheme = ob.get_item("scheme")?.extract()?;
        let username = ob.get_item("username")?.extract()?;
        let password = ob.get_item("password")?.extract()?;
        let host = ob.get_item("host")?.extract()?;
        let port = ob.get_item("port")?.extract()?;
        let path = ob.get_item("path")?.extract()?;
        let realm = ob.get_item("realm")?.extract()?;
        let verify_certificates = ob.get_item("verify_certificates")?.extract()?;

        Ok(Credentials {
            scheme,
            username,
            password,
            host,
            port,
            path,
            realm,
            verify_certificates,
        })
    }
}

impl<'py> IntoPyObject<'py> for Credentials {
    type Target = PyAny;
    type Output = Bound<'py, Self::Target>;
    type Error = std::convert::Infallible;

    fn into_pyobject(self, py: Python<'py>) -> std::result::Result<Self::Output, Self::Error> {
        let dict = pyo3::types::PyDict::new(py);
        dict.set_item("scheme", &self.scheme).unwrap();
        dict.set_item("username", &self.username).unwrap();
        dict.set_item("password", &self.password).unwrap();
        dict.set_item("host", &self.host).unwrap();
        dict.set_item("port", self.port).unwrap();
        dict.set_item("path", &self.path).unwrap();
        dict.set_item("realm", &self.realm).unwrap();
        dict.set_item("verify_certificates", self.verify_certificates)
            .unwrap();
        Ok(dict.into_any())
    }
}

// IntoPy is replaced by IntoPyObject in PyO3 0.25
// The IntoPyObject implementation above handles the conversion

/// A store for retrieving credentials.
///
/// This trait defines the interface for a credential store, which can be used to
/// retrieve credentials for accessing remote services. Implementations of this trait
/// can store credentials in different ways, like in a keychain, a config file, etc.
pub trait CredentialStore: Send + Sync {
    /// Get credentials for accessing a remote service.
    ///
    /// # Parameters
    ///
    /// * `scheme` - The scheme of the service, like "https", "ftp", etc.
    /// * `host` - The hostname of the service.
    /// * `port` - The port number of the service, or None for the default port.
    /// * `user` - The username to use, or None to use the default username.
    /// * `path` - The path on the service, or None for the root path.
    /// * `realm` - The authentication realm, or None for the default realm.
    ///
    /// # Returns
    ///
    /// The credentials for accessing the service, or an error if the credentials
    /// could not be retrieved.
    fn get_credentials(
        &self,
        scheme: &str,
        host: &str,
        port: Option<i64>,
        user: Option<&str>,
        path: Option<&str>,
        realm: Option<&str>,
    ) -> Result<Credentials>;
}

struct PyCredentialStore(Py<PyAny>);

impl CredentialStore for PyCredentialStore {
    fn get_credentials(
        &self,
        scheme: &str,
        host: &str,
        port: Option<i64>,
        user: Option<&str>,
        path: Option<&str>,
        realm: Option<&str>,
    ) -> Result<Credentials> {
        Python::attach(|py| -> Result<Credentials> {
            let creds = self.0.call_method1(
                py,
                "get_credentials",
                (scheme, host, port, user, path, realm),
            )?;
            Ok(creds.extract(py)?)
        })
    }
}

#[pyclass]
/// A wrapper for a `CredentialStore` that can be exposed to Python.
///
/// This struct wraps a `CredentialStore` implementation and exposes it to Python
/// through the Pyo3 type system.
pub struct CredentialStoreWrapper(Box<dyn CredentialStore + Send + Sync>);

#[pymethods]
impl CredentialStoreWrapper {
    #[pyo3(signature = (scheme, host, port=None, user=None, path=None, realm=None))]
    fn get_credentials(
        &self,
        scheme: &str,
        host: &str,
        port: Option<i64>,
        user: Option<&str>,
        path: Option<&str>,
        realm: Option<&str>,
    ) -> PyResult<Credentials> {
        self.0
            .get_credentials(scheme, host, port, user, path, realm)
            .map_err(|e| PyErr::new::<pyo3::exceptions::PyException, _>(e.to_string()))
    }
}

/// A registry of credential stores.
///
/// This struct wraps a Python credential store registry, which can be used to
/// register and retrieve credential stores.
pub struct CredentialStoreRegistry(Py<PyAny>);

impl CredentialStoreRegistry {
    /// Create a new `CredentialStoreRegistry`.
    ///
    /// # Returns
    ///
    /// A new `CredentialStoreRegistry` instance.
    pub fn new() -> Self {
        Python::attach(|py| -> Self {
            let m = py.import("breezy.config").unwrap();
            let registry = m.call_method0("CredentialStoreRegistry").unwrap();
            Self(registry.unbind())
        })
    }

    /// Get a credential store from this registry.
    ///
    /// # Parameters
    ///
    /// * `encoding` - The encoding of the credential store, or None for the default encoding.
    ///
    /// # Returns
    ///
    /// The credential store, or None if no credential store was found for the specified encoding.
    pub fn get_credential_store(
        &self,
        encoding: Option<&str>,
    ) -> Result<Option<Box<dyn CredentialStore>>> {
        Python::attach(|py| -> Result<Option<Box<dyn CredentialStore>>> {
            let store = match self.0.call_method1(py, "get_credential_store", (encoding,)) {
                Ok(store) => store,
                Err(e) if e.is_instance_of::<pyo3::exceptions::PyKeyError>(py) => {
                    return Ok(None);
                }
                Err(e) => {
                    return Err(e.into());
                }
            };
            Ok(Some(Box::new(PyCredentialStore(store))))
        })
    }

    /// Get fallback credentials for accessing a remote service.
    ///
    /// # Parameters
    ///
    /// * `scheme` - The scheme of the service, like "https", "ftp", etc.
    /// * `port` - The port number of the service, or None for the default port.
    /// * `user` - The username to use, or None to use the default username.
    /// * `path` - The path on the service, or None for the root path.
    /// * `realm` - The authentication realm, or None for the default realm.
    ///
    /// # Returns
    ///
    /// The fallback credentials for accessing the service, or an error if the
    /// credentials could not be retrieved.
    pub fn get_fallback_credentials(
        &self,
        scheme: &str,
        port: Option<i64>,
        user: Option<&str>,
        path: Option<&str>,
        realm: Option<&str>,
    ) -> Result<Credentials> {
        Python::attach(|py| -> Result<Credentials> {
            let creds = self.0.call_method1(
                py,
                "get_fallback_credentials",
                (scheme, port, user, path, realm),
            )?;
            Ok(creds.extract(py)?)
        })
    }

    /// Register a credential store with this registry.
    ///
    /// # Parameters
    ///
    /// * `key` - The key to register the credential store under.
    /// * `store` - The credential store to register.
    ///
    /// # Returns
    ///
    /// `Ok(())` on success, or an error if the store could not be registered.
    pub fn register(&self, key: &str, store: Box<dyn CredentialStore>) -> Result<()> {
        Python::attach(|py| -> Result<()> {
            self.0
                .call_method1(py, "register", (key, CredentialStoreWrapper(store)))?;
            Ok(())
        })?;
        Ok(())
    }

    /// Register a fallback credential store with this registry.
    ///
    /// # Parameters
    ///
    /// * `store` - The credential store to register as a fallback.
    ///
    /// # Returns
    ///
    /// `Ok(())` on success, or an error if the store could not be registered.
    pub fn register_fallback(&self, store: Box<dyn CredentialStore>) -> Result<()> {
        Python::attach(|py| -> Result<()> {
            let kwargs = pyo3::types::PyDict::new(py);
            kwargs.set_item("fallback", true)?;
            self.0.call_method(
                py,
                "register_fallback",
                (CredentialStoreWrapper(store),),
                Some(&kwargs),
            )?;
            Ok(())
        })?;
        Ok(())
    }
}

impl Default for CredentialStoreRegistry {
    fn default() -> Self {
        Self::new()
    }
}

lazy_static::lazy_static! {
    /// The global credential store registry.
    ///
    /// This is a lazily initialized static reference to a `CredentialStoreRegistry`
    /// instance, which can be used to access credential stores.
    pub static ref CREDENTIAL_STORE_REGISTRY: CredentialStoreRegistry =
        CredentialStoreRegistry::new()
    ;
}

#[cfg(test)]
mod tests {
    #[test]
    fn test_credential_store() {
        fn takes_config_value<T: crate::config::ConfigValue>(_t: T) {}

        takes_config_value("foo");
        takes_config_value(1);
        takes_config_value(true);
        takes_config_value("foo".to_string());
    }

    use super::*;
    use serial_test::serial;

    #[test]
    #[serial]
    fn test_config_stack() {
        let env = crate::testing::TestEnv::new();
        let stack = global_stack().unwrap();
        stack.get("email").unwrap();
        std::mem::drop(env);
    }

    #[test]
    fn test_parse_username() {
        assert_eq!(
            parse_username("John Doe <joe@example.com>"),
            ("John Doe".to_string(), "joe@example.com".to_string())
        );
        assert_eq!(
            parse_username("John Doe"),
            ("John Doe".to_string(), "".to_string())
        );
    }

    #[test]
    fn test_extract_email_address() {
        assert_eq!(
            extract_email_address("John Doe <joe@example.com>"),
            Some("joe@example.com".to_string())
        );
        assert_eq!(extract_email_address("John Doe"), None);
    }
}