Skip to main content

perforce_cli/cmd/
branches.rs

1use std::{
2    path::{Path, PathBuf},
3    process::{Child, Command, Stdio},
4};
5
6use super::{ExclusiveOption, SubCommand, Unselected};
7
8use crate::global::GlobalOpts;
9use crate::spawn::ParameterizedSpawn;
10
11// ---------------------------------------------------------------------------
12// Name filter (-e / -E)
13// ---------------------------------------------------------------------------
14
15/// The `-e` / `-E` name filter: list only branches whose name matches the
16/// filter pattern.
17///
18/// Created by [`Branches::filter`]; the `case_insensitive` parameter selects
19/// [`Filter::CaseSensitiveMode`] (`-e`) or [`Filter::InCaseSensitiveMode`]
20/// (`-E`).
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub enum Filter {
23    /// `-e`: match the pattern using the server's normal case-sensitivity
24    /// rules.
25    CaseSensitiveMode(String),
26
27    /// `-E`: match the pattern case-insensitively, even on a case-sensitive
28    /// server.
29    InCaseSensitiveMode(String),
30}
31
32impl ExclusiveOption for Filter {
33    fn inject_args(&self, command: &mut Command) {
34        match self {
35            Filter::CaseSensitiveMode(name) => {
36                command.arg("-e").arg(name);
37            }
38            Filter::InCaseSensitiveMode(name) => {
39                command.arg("-E").arg(name);
40            }
41        }
42    }
43}
44
45// ---------------------------------------------------------------------------
46// Owner filter states (-u user / --me)
47// ---------------------------------------------------------------------------
48
49/// The `-u user` / `--me` owner filter: list only branches owned by the
50/// specified user (or the current user).
51///
52#[cfg_attr(
53    feature = "lt2016_1",
54    doc = "Created by [`Branches::user`]. The enum holds exactly one of the two mutually exclusive choices."
55)]
56#[cfg_attr(
57    not(feature = "lt2016_1"),
58    doc = "Created by [`Branches::user`] or [`Branches::filter_me`]; the enum holds exactly one of the two mutually exclusive choices."
59)]
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub enum User {
62    /// `-u user`: list branches owned by the named user; the flag selects
63    /// the `--user-case-insensitive` suboption.
64    Named {
65        name: String,
66
67        #[cfg(not(feature = "lt2024_2"))]
68        case_insensitive: bool,
69    },
70
71    /// `--me`: list branches owned by the current user (equivalent to
72    /// `-u $P4USER`).
73    #[cfg(not(feature = "lt2016_1"))]
74    Me,
75}
76
77impl ExclusiveOption for User {
78    fn inject_args(&self, command: &mut Command) {
79        match self {
80            User::Named {
81                name,
82                #[cfg(not(feature = "lt2024_2"))]
83                case_insensitive,
84            } => {
85                command.arg("-u").arg(name);
86                #[cfg(not(feature = "lt2024_2"))]
87                if *case_insensitive {
88                    command.arg("--user-case-insensitive");
89                }
90            }
91            #[cfg(not(feature = "lt2016_1"))]
92            User::Me => {
93                command.arg("--me");
94            }
95        }
96    }
97}
98
99// ---------------------------------------------------------------------------
100// Command struct
101// ---------------------------------------------------------------------------
102
103#[cfg_attr(
104    feature = "lt2016_1",
105    doc = "`p4 [g-opts] branches [-t] [-u user] [[-e|-E]filter -mmax]`"
106)]
107#[cfg_attr(
108    all(feature = "lt2024_2", not(feature = "lt2016_1")),
109    doc = "`p4 [g-opts] branches [[-e | -E]filter] [-mmax][-t] [-u user | --me]`"
110)]
111#[cfg_attr(
112    not(feature = "lt2024_2"),
113    doc = "`p4 [g-opts] branches [[-e | -E] nameFilter] [-m max][-t] [-u user [--user-case-insensitive] | --me]`"
114)]
115///
116/// List existing branch mappings.
117///
118/// Print the list of all branch mappings currently known to the system.
119///
120/// The `F` type parameter tracks the `-e` / `-E` name filter at compile
121/// time, starting as [`Unselected`]: [`Self::filter`] transitions to the
122/// [`Filter`] state, which carries both the pattern and its case
123/// sensitivity.
124///
125/// The `U` type parameter tracks the owner filter at compile time, starting
126/// as [`Unselected`]:
127#[cfg_attr(feature = "lt2016_1", doc = "[`User`] (entered via [`Self::user`]).")]
128#[cfg_attr(
129    not(feature = "lt2016_1"),
130    doc = "[`User`] (entered via [`Self::user`] or [`Self::filter_me`])."
131)]
132///
133/// Each filter can be set at most once; the remaining options (`-m`, `-t`,
134/// and the other filter) stay available afterwards.
135#[derive(Debug, Clone, Default)]
136pub struct Branches<F = Unselected, U = Unselected> {
137    bin: PathBuf,
138
139    global_opts: GlobalOpts,
140
141    limit: Option<u64>,
142
143    time: bool,
144
145    user_filter: U,
146
147    name_filter: F,
148}
149
150// ---------------------------------------------------------------------------
151// Constructor
152// ---------------------------------------------------------------------------
153
154impl Branches<Unselected, Unselected> {
155    /// Creates a new `p4 branches` command.
156    ///
157    /// `bin` is the path to the Perforce command-line executable.
158    pub fn new(bin: impl Into<PathBuf>, global_opts: GlobalOpts) -> Self {
159        Self {
160            bin: bin.into(),
161            global_opts,
162            ..Default::default()
163        }
164    }
165}
166
167// ---------------------------------------------------------------------------
168// Shared accessors
169// ---------------------------------------------------------------------------
170
171impl<F, U> Branches<F, U> {
172    /// Get the Perforce command path.
173    pub fn get_bin(&self) -> &Path {
174        &self.bin
175    }
176
177    /// Set the Perforce command path.
178    pub fn set_bin(&mut self, bin: impl Into<PathBuf>) -> &mut Self {
179        self.bin = bin.into();
180        self
181    }
182
183    /// Set the Perforce command path.
184    pub fn bin(mut self, bin: impl Into<PathBuf>) -> Self {
185        self.set_bin(bin);
186        self
187    }
188
189    /// # Description
190    ///
191    /// g-opts
192    ///
193    #[cfg_attr(
194        feature = "lt2014_2",
195        doc = "See the [Global Options](GlobalOpts) section."
196    )]
197    #[cfg_attr(
198        all(feature = "lt2015_1", not(feature = "lt2014_2")),
199        doc = "See the [“Global Options”](GlobalOpts) section."
200    )]
201    #[cfg_attr(
202        all(feature = "lt2017_1", not(feature = "lt2015_1")),
203        doc = "See [“Global Options”](GlobalOpts)."
204    )]
205    #[cfg_attr(
206        all(feature = "lt2018_2", not(feature = "lt2017_1")),
207        doc = "See [Global Options](GlobalOpts)."
208    )]
209    #[cfg_attr(not(feature = "lt2018_2"), doc = "See [Global options](GlobalOpts).")]
210    pub fn get_global_opts(&self) -> &GlobalOpts {
211        &self.global_opts
212    }
213
214    /// # Description
215    ///
216    /// g-opts
217    ///
218    #[cfg_attr(
219        feature = "lt2014_2",
220        doc = "See the [Global Options](GlobalOpts) section."
221    )]
222    #[cfg_attr(
223        all(feature = "lt2015_1", not(feature = "lt2014_2")),
224        doc = "See the [“Global Options”](GlobalOpts) section."
225    )]
226    #[cfg_attr(
227        all(feature = "lt2017_1", not(feature = "lt2015_1")),
228        doc = "See [“Global Options”](GlobalOpts)."
229    )]
230    #[cfg_attr(
231        all(feature = "lt2018_2", not(feature = "lt2017_1")),
232        doc = "See [Global Options](GlobalOpts)."
233    )]
234    #[cfg_attr(not(feature = "lt2018_2"), doc = "See [Global options](GlobalOpts).")]
235    pub fn set_global_opts(&mut self, v: GlobalOpts) -> &mut Self {
236        self.global_opts = v;
237        self
238    }
239
240    /// # Description
241    ///
242    /// g-opts
243    ///
244    #[cfg_attr(
245        feature = "lt2014_2",
246        doc = "See the [Global Options](GlobalOpts) section."
247    )]
248    #[cfg_attr(
249        all(feature = "lt2015_1", not(feature = "lt2014_2")),
250        doc = "See the [“Global Options”](GlobalOpts) section."
251    )]
252    #[cfg_attr(
253        all(feature = "lt2017_1", not(feature = "lt2015_1")),
254        doc = "See [“Global Options”](GlobalOpts)."
255    )]
256    #[cfg_attr(
257        all(feature = "lt2018_2", not(feature = "lt2017_1")),
258        doc = "See [Global Options](GlobalOpts)."
259    )]
260    #[cfg_attr(not(feature = "lt2018_2"), doc = "See [Global options](GlobalOpts).")]
261    pub fn global_opts(mut self, v: GlobalOpts) -> Self {
262        self.global_opts = v;
263        self
264    }
265
266    /// # Description
267    ///
268    /// -m max
269    ///
270    /// List only the first `max` branch mappings.
271    pub fn get_limit(&self) -> Option<u64> {
272        self.limit
273    }
274
275    /// # Description
276    ///
277    /// -m max
278    ///
279    /// List only the first `max` branch mappings.
280    pub fn set_limit(&mut self, v: u64) -> &mut Self {
281        self.limit = Some(v);
282        self
283    }
284
285    /// # Description
286    ///
287    /// -m max
288    ///
289    /// List only the first `max` branch mappings.
290    pub fn limit(mut self, v: u64) -> Self {
291        self.limit = Some(v);
292        self
293    }
294
295    /// # Description
296    ///
297    /// -t
298    ///
299    /// Display the time as well as the date of the last update to the branch.
300    pub fn get_display_time(&self) -> bool {
301        self.time
302    }
303
304    /// # Description
305    ///
306    /// -t
307    ///
308    /// Display the time as well as the date of the last update to the branch.
309    pub fn set_display_time(&mut self, v: bool) -> &mut Self {
310        self.time = v;
311        self
312    }
313
314    /// # Description
315    ///
316    /// -t
317    ///
318    /// Display the time as well as the date of the last update to the branch.
319    pub fn display_time(mut self, v: bool) -> Self {
320        self.time = v;
321        self
322    }
323}
324
325// ---------------------------------------------------------------------------
326// Name filter transition
327// ---------------------------------------------------------------------------
328
329impl<U> Branches<Unselected, U> {
330    /// # Description
331    ///
332    #[cfg_attr(feature = "lt2024_2", doc = "-e filter / -E filter")]
333    #[cfg_attr(not(feature = "lt2024_2"), doc = "-e nameFilter / -E nameFilter")]
334    ///
335    /// `v` is the branch name filter pattern; lists only branch specs whose
336    /// name matches it.
337    ///
338    /// When `case_insensitive` is `false` (`-e`), the pattern is matched
339    /// using the server's normal case-sensitivity rules. When
340    /// `case_insensitive` is `true` (`-E`), the pattern is matched
341    /// case-insensitively, even on a case-sensitive server.
342    #[cfg_attr(
343        not(feature = "lt2024_2"),
344        doc = "",
345        doc = "For example:",
346        doc = "",
347        doc = "`p4 branches -e \"svr-dev-rel*\"`"
348    )]
349    ///
350    /// Transitions this command to the [`Filter`] state.
351    pub fn filter(self, v: impl Into<String>, case_insensitive: bool) -> Branches<Filter, U> {
352        Branches {
353            bin: self.bin,
354            global_opts: self.global_opts,
355            limit: self.limit,
356            time: self.time,
357            user_filter: self.user_filter,
358            name_filter: if case_insensitive {
359                Filter::InCaseSensitiveMode(v.into())
360            } else {
361                Filter::CaseSensitiveMode(v.into())
362            },
363        }
364    }
365}
366
367// ---------------------------------------------------------------------------
368// Owner filter transitions
369// ---------------------------------------------------------------------------
370
371impl<F> Branches<F, Unselected> {
372    /// # Description
373    ///
374    /// -u user
375    ///
376    #[cfg_attr(
377        feature = "lt2024_2",
378        doc = "`v` is the owner user name or search pattern."
379    )]
380    #[cfg_attr(
381        not(feature = "lt2024_2"),
382        doc = "`v` is the owner user name or search pattern; `case_insensitive` selects the `--user-case-insensitive` suboption."
383    )]
384    ///
385    #[cfg_attr(feature = "lt2024_2", doc = "List only branches owned by `user`.")]
386    #[cfg_attr(
387        not(feature = "lt2024_2"),
388        doc = "List branch specs owned by the specified user.",
389        doc = "",
390        doc = "This can include `*` wildcards to form a search pattern. If wildcards are used, enclose the search pattern in double quotes (`\"`).",
391        doc = "",
392        doc = "For example:",
393        doc = "",
394        doc = "`p4 branches -u \"*bert\"`",
395        doc = "",
396        doc = "You can also add the `--user-case-insensitive` suboption to indicate that the `user` value is a case-insensitive search pattern, even for a case-sensitive server."
397    )]
398    ///
399    /// Transitions this command to the [`User`] state.
400    pub fn user(self, v: impl Into<String>, case_insensitive: bool) -> Branches<F, User> {
401        let _ = case_insensitive;
402        Branches {
403            bin: self.bin,
404            global_opts: self.global_opts,
405            limit: self.limit,
406            time: self.time,
407            name_filter: self.name_filter,
408            user_filter: User::Named {
409                name: v.into(),
410                #[cfg(not(feature = "lt2024_2"))]
411                case_insensitive,
412            },
413        }
414    }
415
416    /// # Description
417    ///
418    /// --me
419    ///
420    /// Equivalent to `-u $P4USER`.
421    ///
422    /// Transitions this command to the [`User`] state.
423    #[cfg(not(feature = "lt2016_1"))]
424    pub fn filter_me(self) -> Branches<F, User> {
425        Branches {
426            bin: self.bin,
427            global_opts: self.global_opts,
428            limit: self.limit,
429            time: self.time,
430            name_filter: self.name_filter,
431            user_filter: User::Me,
432        }
433    }
434}
435
436// ---------------------------------------------------------------------------
437// SubCommand
438// ---------------------------------------------------------------------------
439
440impl<F: ExclusiveOption, U: ExclusiveOption> SubCommand for Branches<F, U> {
441    fn name(&self) -> &str {
442        "branches"
443    }
444
445    fn inject_local_args(&self, command: &mut Command) {
446        self.name_filter.inject_args(command);
447        if let Some(max) = self.limit {
448            command.arg("-m").arg(max.to_string());
449        }
450        if self.time {
451            command.arg("-t");
452        }
453        self.user_filter.inject_args(command);
454    }
455
456    fn global_opts(&self) -> Option<&GlobalOpts> {
457        Some(&self.global_opts)
458    }
459}
460
461// ---------------------------------------------------------------------------
462// Spawning
463// ---------------------------------------------------------------------------
464
465impl<F: ExclusiveOption, U: ExclusiveOption> ParameterizedSpawn<()> for Branches<F, U> {
466    type Output = Child;
467    type Error = std::io::Error;
468
469    /// Spawns `p4 branches` as a child process with piped standard output
470    /// and error streams; use the returned [`Child`] handle to wait for it
471    /// or interact with it.
472    fn spawn_with(&mut self, (): ()) -> Result<Self::Output, Self::Error> {
473        self.setup_command(&self.bin)
474            .stdout(Stdio::piped())
475            .stderr(Stdio::piped())
476            .spawn()
477    }
478}
479
480#[cfg(test)]
481mod tests {
482    use super::*;
483    use crate::cmd::args_of;
484
485    #[test]
486    fn bin_accessors_update_executable_path() {
487        let mut command = Branches::new("p4", GlobalOpts::new());
488        assert_eq!(command.get_bin(), Path::new("p4"));
489
490        command.set_bin("/usr/local/bin/p4");
491        assert_eq!(command.get_bin(), Path::new("/usr/local/bin/p4"));
492
493        let command = command.bin("p4.exe");
494        assert_eq!(command.get_bin(), Path::new("p4.exe"));
495    }
496
497    // Compile-time rejection: -e and -E are mutually exclusive by
498    // construction (the Filter enum holds exactly one variant).
499    // Compile-time rejection: -u and --me are mutually exclusive by
500    // construction (the User enum holds exactly one variant).
501    // Compile-time rejection: filter can be set only once (no transition or
502    // accessor exists on Branches<Filter, U>).
503    // Compile-time rejection: user/filter_me can be set only once (no
504    // transition or accessor exists on Branches<F, User>).
505    // Compile-time rejection: --user-case-insensitive is passed as an
506    // argument to user(), never settable on its own.
507    // Each filter can be set at most once; limit, display_time, and the
508    // other filter stay available afterwards.
509
510    #[test]
511    fn without_options() {
512        let branches = Branches::new("p4", GlobalOpts::new());
513        assert_eq!(args_of(&branches.setup_command("p4")), ["branches"]);
514    }
515
516    #[test]
517    fn limit() {
518        let branches = Branches::new("p4", GlobalOpts::new()).limit(5);
519        assert_eq!(
520            args_of(&branches.setup_command("p4")),
521            ["branches", "-m", "5"]
522        );
523    }
524
525    #[test]
526    fn display_time() {
527        let branches = Branches::new("p4", GlobalOpts::new()).display_time(true);
528        assert_eq!(args_of(&branches.setup_command("p4")), ["branches", "-t"]);
529    }
530
531    #[test]
532    fn display_time_can_be_unset() {
533        let branches = Branches::new("p4", GlobalOpts::new()).display_time(false);
534        assert_eq!(args_of(&branches.setup_command("p4")), ["branches"]);
535    }
536
537    #[test]
538    fn filter_case_sensitive() {
539        let branches = Branches::new("p4", GlobalOpts::new()).filter("svr-dev-rel*", false);
540        assert_eq!(
541            args_of(&branches.setup_command("p4")),
542            ["branches", "-e", "svr-dev-rel*"]
543        );
544    }
545
546    #[test]
547    fn filter_case_insensitive() {
548        let branches = Branches::new("p4", GlobalOpts::new()).filter("SVR-DEV-REL*", true);
549        assert_eq!(
550            args_of(&branches.setup_command("p4")),
551            ["branches", "-E", "SVR-DEV-REL*"]
552        );
553    }
554
555    #[test]
556    fn user() {
557        let branches = Branches::new("p4", GlobalOpts::new()).user("*bert", false);
558        assert_eq!(
559            args_of(&branches.setup_command("p4")),
560            ["branches", "-u", "*bert"]
561        );
562    }
563
564    #[cfg(not(feature = "lt2016_1"))]
565    #[test]
566    fn filter_me() {
567        let branches = Branches::new("p4", GlobalOpts::new()).filter_me();
568        assert_eq!(args_of(&branches.setup_command("p4")), ["branches", "--me"]);
569    }
570
571    #[cfg(not(feature = "lt2024_2"))]
572    #[test]
573    fn user_case_insensitive() {
574        let branches = Branches::new("p4", GlobalOpts::new()).user("*bert", true);
575        assert_eq!(
576            args_of(&branches.setup_command("p4")),
577            ["branches", "-u", "*bert", "--user-case-insensitive"]
578        );
579    }
580
581    #[test]
582    fn filter_transitions_preserve_owner_filter() {
583        let branches = Branches::new("p4", GlobalOpts::new())
584            .user("*bert", false)
585            .filter("svr-dev-rel*", false);
586        assert_eq!(
587            args_of(&branches.setup_command("p4")),
588            ["branches", "-e", "svr-dev-rel*", "-u", "*bert"]
589        );
590
591        #[cfg(not(feature = "lt2016_1"))]
592        {
593            let branches = Branches::new("p4", GlobalOpts::new())
594                .filter("SVR*", true)
595                .filter_me();
596            assert_eq!(
597                args_of(&branches.setup_command("p4")),
598                ["branches", "-E", "SVR*", "--me"]
599            );
600        }
601    }
602
603    #[test]
604    fn setters_update_limit_and_display_time() {
605        let mut branches = Branches::new("p4", GlobalOpts::new()).filter("svr-dev*", false);
606        assert_eq!(branches.get_limit(), None);
607        branches.set_limit(10);
608        assert_eq!(branches.get_limit(), Some(10));
609        assert!(!branches.get_display_time());
610        branches.set_display_time(true);
611        assert!(branches.get_display_time());
612    }
613
614    #[test]
615    fn all_options_order() {
616        let branches = Branches::new("p4", GlobalOpts::new())
617            .filter("svr-dev-rel*", false)
618            .limit(5)
619            .display_time(true)
620            .user("*bert", false);
621        assert_eq!(
622            args_of(&branches.setup_command("p4")),
623            [
624                "branches",
625                "-e",
626                "svr-dev-rel*",
627                "-m",
628                "5",
629                "-t",
630                "-u",
631                "*bert"
632            ]
633        );
634    }
635
636    #[test]
637    fn global_opts_are_injected_once() {
638        let branches = Branches::new("p4", GlobalOpts::new().port("localhost:1666")).limit(1);
639        assert_eq!(
640            args_of(&branches.setup_command("p4")),
641            ["-p", "localhost:1666", "branches", "-m", "1"]
642        );
643    }
644}