]> git.proxmox.com Git - proxmox-backup.git/blob - src/client/backup_repo.rs
525da9093219f342ca632e86e366800cfe71cc90
[proxmox-backup.git] / src / client / backup_repo.rs
1 use std::fmt;
2
3 use failure::*;
4
5 use proxmox::api::const_regex;
6 use proxmox::api::schema::*;
7
8 const_regex! {
9 /// Regular expression to parse repository URLs
10 pub BACKUP_REPO_URL_REGEX = r"^(?:(?:([\w@]+)@)?([\w\-_.]+):)?(\w+)$";
11 }
12
13 /// API schema format definition for repository URLs
14 pub const BACKUP_REPO_URL: ApiStringFormat = ApiStringFormat::Pattern(&BACKUP_REPO_URL_REGEX);
15
16 /// Reference remote backup locations
17 ///
18
19 #[derive(Debug)]
20 pub struct BackupRepository {
21 /// The user name used for Authentication
22 user: Option<String>,
23 /// The host name or IP address
24 host: Option<String>,
25 /// The name of the datastore
26 store: String,
27 }
28
29 impl BackupRepository {
30
31 pub fn new(user: Option<String>, host: Option<String>, store: String) -> Self {
32 Self { user, host, store }
33 }
34
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 }
52 }
53
54 impl 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 }
63 }
64 }
65
66 impl 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
76 let cap = (BACKUP_REPO_URL_REGEX.regex_obj)().captures(url)
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 }