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
use std::collections::{HashMap, HashSet};

use crate::types::{Branch, Host, NomadRef, RemoteNomadRefSet, User};

/// A point in time view of refs we care about. [`Snapshot`] is only for local branches and refs
/// and thus is scoped under a specific [`User`].
#[allow(clippy::manual_non_exhaustive)]
pub struct Snapshot<'a, Ref> {
    /// The active branches in this clone that the user manipulates directly with `git branch` etc.
    pub local_branches: HashSet<Branch<'static>>,
    /// The refs that nomad manages to follow the local branches.
    pub nomad_refs: Vec<NomadRef<'a, Ref>>,
    /// Force all callers to go through [`Snapshot::new`] which can validate invariants.
    _private: (),
}

/// Describes where a ref should be removed from.
#[derive(Debug, PartialEq, Eq)]
pub enum PruneFrom<'a, Ref> {
    LocalOnly(NomadRef<'a, Ref>),
    LocalAndRemote(NomadRef<'a, Ref>),
}

impl<Ref> Snapshot<'_, Ref> {
    /// Smart constructor that enforces the "scoped under a specific [`User`]" invariant.
    ///
    /// # Panics
    ///
    /// If `nomad_refs` points to a different [`User`] than the `user` passed in. This indicates
    /// serious programmer error.
    pub fn new<'a>(
        user: &'a User,
        local_branches: HashSet<Branch<'static>>,
        nomad_refs: Vec<NomadRef<'a, Ref>>,
    ) -> Snapshot<'a, Ref> {
        for nomad_ref in &nomad_refs {
            assert_eq!(user, &nomad_ref.user);
        }

        Snapshot {
            local_branches,
            nomad_refs,
            _private: (),
        }
    }
}

impl<'a, Ref> Snapshot<'a, Ref> {
    /// Find nomad host branches that can be pruned because:
    /// 1. The local branch they were based on no longer exists.
    /// 2. The remote branch they were based on no longer exists.
    pub fn prune_deleted_branches(
        self,
        host: &Host,
        remote_nomad_refs: &RemoteNomadRefSet,
    ) -> Vec<PruneFrom<'a, Ref>> {
        let Self {
            nomad_refs,
            local_branches,
            ..
        } = self;

        let mut prune = Vec::<PruneFrom<Ref>>::new();

        for nomad_ref in nomad_refs {
            if &nomad_ref.host == host {
                if !local_branches.contains(&nomad_ref.branch) {
                    prune.push(PruneFrom::LocalAndRemote(nomad_ref));
                }
            } else if !remote_nomad_refs.contains(&nomad_ref) {
                prune.push(PruneFrom::LocalOnly(nomad_ref));
            }
        }

        prune
    }

    /// Return all nomad branches for specific hosts.
    pub fn prune_by_hosts(self, host_filter: impl Fn(&Host) -> bool) -> Vec<PruneFrom<'a, Ref>> {
        let Self { nomad_refs, .. } = self;
        nomad_refs
            .into_iter()
            .filter_map(|nomad_ref| {
                if !host_filter(&nomad_ref.host) {
                    return None;
                }

                Some(PruneFrom::LocalAndRemote(nomad_ref))
            })
            .collect()
    }

    /// Return all [`NomadRef`]s grouped by host in sorted order.
    pub fn sorted_hosts_and_branches(self) -> Vec<(Host<'a>, Vec<NomadRef<'a, Ref>>)> {
        let mut by_host = HashMap::<Host, Vec<NomadRef<Ref>>>::new();
        let Self { nomad_refs, .. } = self;

        for nomad_ref in nomad_refs {
            by_host
                .entry(nomad_ref.host.clone())
                .or_default()
                .push(nomad_ref);
        }

        let mut as_vec = by_host
            .into_iter()
            .map(|(host, mut branches)| {
                branches.sort_by(|a, b| a.branch.cmp(&b.branch));
                (host, branches)
            })
            .collect::<Vec<_>>();
        as_vec.sort_by(|(host_a, _), (host_b, _)| host_a.cmp(host_b));

        as_vec
    }
}

#[cfg(test)]
mod tests {
    use std::iter::FromIterator;

    use crate::types::{Host, RemoteNomadRefSet, User};

    use super::{Branch, NomadRef, PruneFrom, Snapshot};

    fn snapshot<'a>(
        user: &'a User,
        local_branches: impl IntoIterator<Item = &'static str>,
    ) -> Snapshot<'a, ()> {
        Snapshot::new(
            user,
            local_branches.into_iter().map(Branch::from).collect(),
            vec![
                NomadRef {
                    user: user.always_borrow(),
                    host: Host::from("host0"),
                    branch: Branch::from("branch0"),
                    ref_: (),
                },
                NomadRef {
                    user: user.always_borrow(),
                    host: Host::from("host0"),
                    branch: Branch::from("branch1"),
                    ref_: (),
                },
                NomadRef {
                    user: user.always_borrow(),
                    host: Host::from("host1"),
                    branch: Branch::from("branch1"),
                    ref_: (),
                },
            ],
        )
    }

    fn remote_nomad_refs(
        collection: impl IntoIterator<Item = (&'static str, &'static str, &'static str)>,
    ) -> RemoteNomadRefSet {
        RemoteNomadRefSet::from_iter(
            collection.into_iter().map(|(user, host, branch)| {
                (User::from(user), Host::from(host), Branch::from(branch))
            }),
        )
    }

    /// Sets up the scenario where:
    ///
    ///     There are local branches
    ///     ... That DO NOT have nomad refs
    ///
    ///     There are local nomad refs from other hosts
    ///     ... That have corresponding remote nomad refs
    ///
    /// In this case, we should prune nothing.
    #[test]
    fn snapshot_prune_does_nothing0() {
        let user = &User::from("user0");
        let prune = snapshot(user, ["branch0", "branch1"]).prune_deleted_branches(
            &Host::from("host0"),
            &remote_nomad_refs([("user0", "host1", "branch1")]),
        );

        assert_eq!(prune, Vec::new());
    }

    /// Sets up the scenario where:
    ///
    ///     There are local branches
    ///     ... That have nomad refs
    ///
    ///     There are local nomad refs from other hosts
    ///     ... That have corresponding remote nomad refs
    ///
    /// In this case, we should prune nothing.
    #[test]
    fn snapshot_prune_does_nothing1() {
        let user = &User::from("user0");
        let prune = snapshot(user, ["branch0", "branch1"]).prune_deleted_branches(
            &Host::from("host0"),
            &remote_nomad_refs([
                ("user0", "host0", "branch0"),
                ("user0", "host0", "branch1"),
                ("user0", "host1", "branch1"),
            ]),
        );

        assert_eq!(prune, Vec::new());
    }

    /// Sets up the scenario where:
    ///
    ///     There are NO local branches
    ///     ... That have nomad refs
    ///
    ///     There are local nomad refs from other hosts
    ///     ... That have corresponding remote nomad refs
    ///
    /// In this case, we should remove the nomad refs for the local branches that no longer exist.
    #[test]
    fn snapshot_prune_removes_local_missing_branches() {
        let user = &User::from("user0");
        let prune = snapshot(
            user,
            [
                "branch0",
                // This branch has been removed
                // "branch1",
            ],
        )
        .prune_deleted_branches(
            &Host::from("host0"),
            &remote_nomad_refs([
                ("user0", "host0", "branch0"),
                ("user0", "host0", "branch1"),
                ("user0", "host1", "branch1"),
            ]),
        );

        assert_eq!(
            prune,
            vec![PruneFrom::LocalAndRemote(NomadRef {
                user: User::from("user0"),
                host: Host::from("host0"),
                branch: Branch::from("branch1"),
                ref_: (),
            })]
        );
    }

    /// Sets up the scenario where:
    ///
    ///     There are local branches
    ///     ... That have nomad refs
    ///
    ///     There are local nomad refs from other hosts
    ///     ... That DO NOT have corresponding remote nomad refs
    ///
    /// In this case, we should remove the local nomad refs from other hosts since the
    /// corresponding remote refs no longer exist.
    #[test]
    fn snapshot_prune_removes_remote_missing_branches() {
        let user = &User::from("user0");
        let prune = snapshot(user, ["branch0", "branch1"]).prune_deleted_branches(
            &Host::from("host0"),
            &remote_nomad_refs([
                ("user0", "host0", "branch0"),
                ("user0", "host0", "branch1"),
                // This remote nomad ref for another host has been removed
                // ("user0", "host1", "branch1"),
            ]),
        );

        assert_eq!(
            prune,
            vec![PruneFrom::LocalOnly(NomadRef {
                user: User::from("user0"),
                host: Host::from("host1"),
                branch: Branch::from("branch1"),
                ref_: (),
            })]
        );
    }

    /// [`Snapshot::prune_all`] should remove all branches.
    #[test]
    fn snapshot_prune_all() {
        let user = &User::from("user0");
        let prune = snapshot(user, ["branch0", "branch1"]).prune_by_hosts(|_h| true);
        assert_eq!(
            prune,
            vec![
                PruneFrom::LocalAndRemote(NomadRef {
                    user: User::from("user0"),
                    host: Host::from("host0"),
                    branch: Branch::from("branch0"),
                    ref_: (),
                }),
                PruneFrom::LocalAndRemote(NomadRef {
                    user: User::from("user0"),
                    host: Host::from("host0"),
                    branch: Branch::from("branch1"),
                    ref_: (),
                }),
                PruneFrom::LocalAndRemote(NomadRef {
                    user: User::from("user0"),
                    host: Host::from("host1"),
                    branch: Branch::from("branch1"),
                    ref_: (),
                }),
            ],
        );
    }

    /// [`Snapshot::prune_all_by_hosts`] should only remove branches for specified hosts.
    #[test]
    fn snapshot_prune_hosts() {
        let user = &User::from("user0");
        let prune =
            snapshot(user, ["branch0", "branch1"]).prune_by_hosts(|h| *h == Host::from("host0"));
        assert_eq!(
            prune,
            vec![
                PruneFrom::LocalAndRemote(NomadRef {
                    user: User::from("user0"),
                    host: Host::from("host0"),
                    branch: Branch::from("branch0"),
                    ref_: (),
                },),
                PruneFrom::LocalAndRemote(NomadRef {
                    user: User::from("user0"),
                    host: Host::from("host0"),
                    branch: Branch::from("branch1"),
                    ref_: (),
                },),
            ],
        );
    }
}