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
use std::collections::HashSet;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::iter::FromIterator;
use std::ops::{BitOr, Sub};
use std::path::PathBuf;
use std::str::FromStr;

use derive_more::{Deref, DerefMut, IntoIterator};
use serde::{Deserialize, Serialize};
use strum::{EnumString, EnumVariantNames, VariantNames};

/// Change to a path on the filesystem.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub struct Change {
    /// Unix timestamp (in seconds) when the server was notified of this change (not when the
    /// change occurred)
    pub timestamp: u64,

    /// Label describing the kind of change
    pub kind: ChangeKind,

    /// Path that was changed
    pub path: PathBuf,

    /// Additional details associated with the change
    #[serde(default, skip_serializing_if = "ChangeDetails::is_empty")]
    pub details: ChangeDetails,
}

/// Optional details about a change.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "snake_case", deny_unknown_fields)]
pub struct ChangeDetails {
    /// Clarity on type of attribute change that occurred (for kind == attribute).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub attribute: Option<ChangeDetailsAttribute>,

    /// When event is renaming, this will be populated with the resulting name
    /// when we know both the old and new names (for kind == rename)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub renamed: Option<PathBuf>,

    /// Unix timestamps (in seconds) related to the change. For other platforms, their timestamps
    /// are converted into a Unix timestamp format.
    ///
    /// * For create events, this represents the `ctime` field from stat (or equivalent on other platforms).
    /// * For modify events, this represents the `mtime` field from stat (or equivalent on other platforms).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timestamp: Option<u64>,

    /// Optional information about the change that is typically platform-specific.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub extra: Option<String>,
}

impl ChangeDetails {
    /// Returns true if no details are contained within.
    pub fn is_empty(&self) -> bool {
        self.attribute.is_none()
            && self.renamed.is_none()
            && self.timestamp.is_none()
            && self.extra.is_none()
    }
}

/// Specific details about modification
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub enum ChangeDetailsAttribute {
    Ownership,
    Permissions,
    Timestamp,
}

/// Represents a label attached to a [`Change`] that describes the kind of change.
///
/// This mirrors events seen from `incron`.
#[derive(
    Copy,
    Clone,
    Debug,
    strum::Display,
    EnumString,
    EnumVariantNames,
    Hash,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Serialize,
    Deserialize,
)]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
#[strum(serialize_all = "snake_case")]
pub enum ChangeKind {
    /// A file was read
    Access,

    /// A file's or directory's attributes were changed
    Attribute,

    /// A file open for writing was closed
    CloseWrite,

    /// A file not open for writing was closed
    CloseNoWrite,

    /// A file, directory, or something else was created within a watched directory
    Create,

    /// A file, directory, or something else was deleted
    Delete,

    /// A file's content was modified
    Modify,

    /// A file was opened
    Open,

    /// A file, directory, or something else was renamed in some way
    Rename,

    /// Catch-all for any other change
    Unknown,
}

impl ChangeKind {
    /// Returns a list of all variants as str names
    pub const fn variants() -> &'static [&'static str] {
        Self::VARIANTS
    }

    /// Returns a list of all variants as a vec
    pub fn all() -> Vec<ChangeKind> {
        ChangeKindSet::all().into_sorted_vec()
    }

    /// Returns true if kind is part of the access family.
    pub fn is_access(&self) -> bool {
        matches!(
            self,
            Self::Access | Self::CloseWrite | Self::CloseNoWrite | Self::Open
        )
    }

    /// Returns true if kind is part of the create family.
    pub fn is_create(&self) -> bool {
        matches!(self, Self::Create)
    }

    /// Returns true if kind is part of the delete family.
    pub fn is_delete(&self) -> bool {
        matches!(self, Self::Delete)
    }

    /// Returns true if kind is part of the modify family.
    pub fn is_modify(&self) -> bool {
        matches!(self, Self::Attribute | Self::Modify)
    }

    /// Returns true if kind is part of the rename family.
    pub fn is_rename(&self) -> bool {
        matches!(self, Self::Rename)
    }

    /// Returns true if kind is unknown.
    pub fn is_unknown(&self) -> bool {
        matches!(self, Self::Unknown)
    }
}

impl BitOr for ChangeKind {
    type Output = ChangeKindSet;

    fn bitor(self, rhs: Self) -> Self::Output {
        let mut set = ChangeKindSet::empty();
        set.insert(self);
        set.insert(rhs);
        set
    }
}

/// Represents a distinct set of different change kinds
#[derive(Clone, Debug, Deref, DerefMut, IntoIterator, Serialize, Deserialize)]
pub struct ChangeKindSet(HashSet<ChangeKind>);

impl ChangeKindSet {
    pub fn new(set: impl IntoIterator<Item = ChangeKind>) -> Self {
        set.into_iter().collect()
    }

    /// Produces an empty set of [`ChangeKind`]
    pub fn empty() -> Self {
        Self(HashSet::new())
    }

    /// Produces a set of all [`ChangeKind`]
    pub fn all() -> Self {
        vec![
            ChangeKind::Access,
            ChangeKind::Attribute,
            ChangeKind::CloseWrite,
            ChangeKind::CloseNoWrite,
            ChangeKind::Create,
            ChangeKind::Delete,
            ChangeKind::Modify,
            ChangeKind::Open,
            ChangeKind::Rename,
            ChangeKind::Unknown,
        ]
        .into_iter()
        .collect()
    }

    /// Consumes set and returns a sorted vec of the kinds of changes
    pub fn into_sorted_vec(self) -> Vec<ChangeKind> {
        let mut v = self.0.into_iter().collect::<Vec<_>>();
        v.sort();
        v
    }
}

impl fmt::Display for ChangeKindSet {
    /// Outputs a comma-separated series of [`ChangeKind`] as string that are sorted
    /// such that this will always be consistent output
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut kinds = self
            .0
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<String>>();
        kinds.sort_unstable();
        write!(f, "{}", kinds.join(","))
    }
}

impl PartialEq for ChangeKindSet {
    fn eq(&self, other: &Self) -> bool {
        self.to_string() == other.to_string()
    }
}

impl Eq for ChangeKindSet {}

impl Hash for ChangeKindSet {
    /// Hashes based on the output of [`fmt::Display`]
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.to_string().hash(state);
    }
}

impl BitOr<ChangeKindSet> for ChangeKindSet {
    type Output = Self;

    fn bitor(mut self, rhs: ChangeKindSet) -> Self::Output {
        self.extend(rhs.0);
        self
    }
}

impl BitOr<ChangeKind> for ChangeKindSet {
    type Output = Self;

    fn bitor(mut self, rhs: ChangeKind) -> Self::Output {
        self.0.insert(rhs);
        self
    }
}

impl BitOr<ChangeKindSet> for ChangeKind {
    type Output = ChangeKindSet;

    fn bitor(self, rhs: ChangeKindSet) -> Self::Output {
        rhs | self
    }
}

impl Sub<ChangeKindSet> for ChangeKindSet {
    type Output = Self;

    fn sub(self, other: Self) -> Self::Output {
        ChangeKindSet(&self.0 - &other.0)
    }
}

impl Sub<&'_ ChangeKindSet> for &ChangeKindSet {
    type Output = ChangeKindSet;

    fn sub(self, other: &ChangeKindSet) -> Self::Output {
        ChangeKindSet(&self.0 - &other.0)
    }
}

impl FromStr for ChangeKindSet {
    type Err = strum::ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut change_set = HashSet::new();

        for word in s.split(',') {
            change_set.insert(ChangeKind::from_str(word.trim())?);
        }

        Ok(ChangeKindSet(change_set))
    }
}

impl FromIterator<ChangeKind> for ChangeKindSet {
    fn from_iter<I: IntoIterator<Item = ChangeKind>>(iter: I) -> Self {
        let mut change_set = HashSet::new();

        for i in iter {
            change_set.insert(i);
        }

        ChangeKindSet(change_set)
    }
}

impl From<ChangeKind> for ChangeKindSet {
    fn from(change_kind: ChangeKind) -> Self {
        let mut set = Self::empty();
        set.insert(change_kind);
        set
    }
}

impl From<Vec<ChangeKind>> for ChangeKindSet {
    fn from(changes: Vec<ChangeKind>) -> Self {
        changes.into_iter().collect()
    }
}

impl Default for ChangeKindSet {
    fn default() -> Self {
        Self::empty()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    mod change_kind_set {
        use super::*;

        #[test]
        fn should_be_able_to_serialize_to_json() {
            let set = ChangeKindSet::new([ChangeKind::CloseWrite]);

            let value = serde_json::to_value(set).unwrap();
            assert_eq!(value, serde_json::json!(["close_write"]));
        }

        #[test]
        fn should_be_able_to_deserialize_from_json() {
            let value = serde_json::json!(["close_write"]);

            let set: ChangeKindSet = serde_json::from_value(value).unwrap();
            assert_eq!(set, ChangeKindSet::new([ChangeKind::CloseWrite]));
        }

        #[test]
        fn should_be_able_to_serialize_to_msgpack() {
            let set = ChangeKindSet::new([ChangeKind::CloseWrite]);

            // NOTE: We don't actually check the output here because it's an implementation detail
            // and could change as we change how serialization is done. This is merely to verify
            // that we can serialize since there are times when serde fails to serialize at
            // runtime.
            let _ = rmp_serde::encode::to_vec_named(&set).unwrap();
        }

        #[test]
        fn should_be_able_to_deserialize_from_msgpack() {
            // NOTE: It may seem odd that we are serializing just to deserialize, but this is to
            // verify that we are not corrupting or causing issues when serializing on a
            // client/server and then trying to deserialize on the other side. This has happened
            // enough times with minor changes that we need tests to verify.
            let buf =
                rmp_serde::encode::to_vec_named(&ChangeKindSet::new([ChangeKind::CloseWrite]))
                    .unwrap();

            let set: ChangeKindSet = rmp_serde::decode::from_slice(&buf).unwrap();
            assert_eq!(set, ChangeKindSet::new([ChangeKind::CloseWrite]));
        }
    }

    mod change_kind {
        use super::*;

        #[test]
        fn should_be_able_to_serialize_to_json() {
            let kind = ChangeKind::CloseWrite;

            let value = serde_json::to_value(kind).unwrap();
            assert_eq!(value, serde_json::json!("close_write"));
        }

        #[test]
        fn should_be_able_to_deserialize_from_json() {
            let value = serde_json::json!("close_write");

            let kind: ChangeKind = serde_json::from_value(value).unwrap();
            assert_eq!(kind, ChangeKind::CloseWrite);
        }

        #[test]
        fn should_be_able_to_serialize_to_msgpack() {
            let kind = ChangeKind::CloseWrite;

            // NOTE: We don't actually check the output here because it's an implementation detail
            // and could change as we change how serialization is done. This is merely to verify
            // that we can serialize since there are times when serde fails to serialize at
            // runtime.
            let _ = rmp_serde::encode::to_vec_named(&kind).unwrap();
        }

        #[test]
        fn should_be_able_to_deserialize_from_msgpack() {
            // NOTE: It may seem odd that we are serializing just to deserialize, but this is to
            // verify that we are not corrupting or causing issues when serializing on a
            // client/server and then trying to deserialize on the other side. This has happened
            // enough times with minor changes that we need tests to verify.
            let buf = rmp_serde::encode::to_vec_named(&ChangeKind::CloseWrite).unwrap();

            let kind: ChangeKind = rmp_serde::decode::from_slice(&buf).unwrap();
            assert_eq!(kind, ChangeKind::CloseWrite);
        }
    }
}