]> git.proxmox.com Git - proxmox-backup.git/blob - src/client/backup_repo.rs
replace file_set_contents with replace_file
[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 user(&self) -> &str {
32 if let Some(ref user) = self.user {
33 return user;
34 }
35 "root@pam"
36 }
37
38 pub fn host(&self) -> &str {
39 if let Some(ref host) = self.host {
40 return host;
41 }
42 "localhost"
43 }
44
45 pub fn store(&self) -> &str {
46 &self.store
47 }
48 }
49
50 impl fmt::Display for BackupRepository {
51 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
52 if let Some(ref user) = self.user {
53 write!(f, "{}@{}:{}", user, self.host(), self.store)
54 } else if let Some(ref host) = self.host {
55 write!(f, "{}:{}", host, self.store)
56 } else {
57 write!(f, "{}", self.store)
58 }
59 }
60 }
61
62 impl std::str::FromStr for BackupRepository {
63 type Err = Error;
64
65 /// Parse a repository URL.
66 ///
67 /// This parses strings like `user@host:datastore`. The `user` and
68 /// `host` parts are optional, where `host` defaults to the local
69 /// host, and `user` defaults to `root@pam`.
70 fn from_str(url: &str) -> Result<Self, Self::Err> {
71
72 let cap = (BACKUP_REPO_URL_REGEX.regex_obj)().captures(url)
73 .ok_or_else(|| format_err!("unable to parse repository url '{}'", url))?;
74
75 Ok(Self {
76 user: cap.get(1).map(|m| m.as_str().to_owned()),
77 host: cap.get(2).map(|m| m.as_str().to_owned()),
78 store: cap[3].to_owned(),
79 })
80 }
81 }
82