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
use std::collections::HashMap;
use std::default::Default;
use {Patch, Username, UserGroupId};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Role {
#[serde(rename = "viewer")]
Viewer,
#[serde(rename = "editor")]
Editor,
}
fromstr_deserialize!(Role);
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Sharing<R> {
#[serde(skip_serializing_if="Option::is_none")]
pub anyone: Option<R>,
#[serde(default = "HashMap::default", skip_serializing_if="HashMap::is_empty")]
pub users: HashMap<Username, R>,
#[serde(default = "HashMap::default", skip_serializing_if="HashMap::is_empty")]
pub groups: HashMap<UserGroupId, R>,
}
pub type SharingState = Sharing<Role>;
pub type SharingPatch = Sharing<Option<Role>>;
impl Default for Sharing<Option<Role>> {
fn default() -> Self {
Sharing {
anyone: None,
users: HashMap::new(),
groups: HashMap::new(),
}
}
}
impl Patch for Sharing<Option<Role>> {}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use std::iter::{self, FromIterator};
use serde_json;
use super::{SharingPatch, SharingState, Role};
use {Username, UserGroupId};
static SAMPLE_1: &'static str = r#"{
"anyone": "viewer",
"users": {
"abirmingham": "editor",
"botha": "editor",
"dave": "editor",
"ehd": "editor",
"green": "editor",
"mikelly": "editor",
"mikem": "editor"
},
"groups": {}
}"#;
#[test]
fn deserialize_sharing() {
let parsed: SharingState = serde_json::from_str(SAMPLE_1).unwrap();
assert_eq!(Some(&Role::Editor),
parsed.users.get(&Username::new("ehd".to_string())));
}
#[test]
fn serialize_full_patch() {
let change = SharingPatch {
anyone: Some(None),
users: HashMap::from_iter(vec![(Username::new("ehd"), None),
(Username::new("mikelly"), Some(Role::Viewer))]),
groups: HashMap::from_iter(iter::once((UserGroupId::new("remote.pm-team"),
Some(Role::Editor)))),
};
println!("{}", serde_json::to_string_pretty(&change).unwrap());
}
#[test]
fn serialize_targeted() {
let change = SharingPatch {
users: HashMap::from_iter(iter::once((Username::new("ehd"), Some(Role::Editor)))),
..SharingPatch::default()
};
println!("{}", serde_json::to_string_pretty(&change).unwrap());
}
#[test]
fn noop_patch() {
assert_eq!("{}",
&serde_json::to_string(&SharingPatch::default()).unwrap());
assert_eq!(SharingPatch::default(),
serde_json::from_str::<SharingPatch>("{}").unwrap());
}
}