]> git.proxmox.com Git - proxmox-backup.git/blame - src/client/backup_repo.rs
switch from failure to anyhow
[proxmox-backup.git] / src / client / backup_repo.rs
CommitLineData
cad540e9 1use std::fmt;
151c6ce2 2
f7d4e4b5 3use anyhow::{format_err, Error};
151c6ce2 4
cad540e9 5use proxmox::api::schema::*;
9ea4bce4 6use proxmox::const_regex;
151c6ce2 7
255f378a 8const_regex! {
db4868ef 9 /// Regular expression to parse repository URLs
255f378a 10 pub BACKUP_REPO_URL_REGEX = r"^(?:(?:([\w@]+)@)?([\w\-_.]+):)?(\w+)$";
151c6ce2
DM
11}
12
255f378a
DM
13/// API schema format definition for repository URLs
14pub const BACKUP_REPO_URL: ApiStringFormat = ApiStringFormat::Pattern(&BACKUP_REPO_URL_REGEX);
15
151c6ce2
DM
16/// Reference remote backup locations
17///
18
19#[derive(Debug)]
20pub struct BackupRepository {
21 /// The user name used for Authentication
d0a03d40 22 user: Option<String>,
151c6ce2 23 /// The host name or IP address
d0a03d40 24 host: Option<String>,
151c6ce2 25 /// The name of the datastore
d0a03d40 26 store: String,
151c6ce2
DM
27}
28
29impl BackupRepository {
30
25de1c80
DM
31 pub fn new(user: Option<String>, host: Option<String>, store: String) -> Self {
32 Self { user, host, store }
33 }
34
d0a03d40
DM
35 pub fn user(&self) -> &str {
36 if let Some(ref user) = self.user {
37 return user;
38 }
39 "root@pam"
40 }
41
42 pub fn host(&self) -> &str {
43 if let Some(ref host) = self.host {
44 return host;
45 }
46 "localhost"
47 }
48
49 pub fn store(&self) -> &str {
50 &self.store
51 }
874acb70 52}
d0a03d40 53
874acb70
DM
54impl fmt::Display for BackupRepository {
55 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
56 if let Some(ref user) = self.user {
57 write!(f, "{}@{}:{}", user, self.host(), self.store)
58 } else if let Some(ref host) = self.host {
59 write!(f, "{}:{}", host, self.store)
60 } else {
61 write!(f, "{}", self.store)
62 }
d0a03d40 63 }
151c6ce2 64}
edd3c8c6
DM
65
66impl std::str::FromStr for BackupRepository {
67 type Err = Error;
68
69 /// Parse a repository URL.
70 ///
71 /// This parses strings like `user@host:datastore`. The `user` and
72 /// `host` parts are optional, where `host` defaults to the local
73 /// host, and `user` defaults to `root@pam`.
74 fn from_str(url: &str) -> Result<Self, Self::Err> {
75
255f378a 76 let cap = (BACKUP_REPO_URL_REGEX.regex_obj)().captures(url)
edd3c8c6
DM
77 .ok_or_else(|| format_err!("unable to parse repository url '{}'", url))?;
78
79 Ok(Self {
80 user: cap.get(1).map(|m| m.as_str().to_owned()),
81 host: cap.get(2).map(|m| m.as_str().to_owned()),
82 store: cap[3].to_owned(),
83 })
84 }
85}