Skip to main content

perforce_cli/cmd/
clients.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 client workspaces whose name
16/// matches the filter pattern.
17///
18/// Created by [`Clients::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` state: list only client workspaces owned by the named user.
50///
51#[cfg_attr(feature = "lt2024_2", doc = "Created by [`Clients::user`].")]
52#[cfg_attr(
53    not(feature = "lt2024_2"),
54    doc = "Created by [`Clients::user`]; call [`Clients::case_insensitive`] on the entered state to add the `--user-case-insensitive` suboption."
55)]
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct User {
58    user: String,
59
60    #[cfg(not(feature = "lt2024_2"))]
61    case_insensitive: bool,
62}
63
64impl ExclusiveOption for User {
65    fn inject_args(&self, command: &mut Command) {
66        command.arg("-u").arg(&self.user);
67        #[cfg(not(feature = "lt2024_2"))]
68        if self.case_insensitive {
69            command.arg("--user-case-insensitive");
70        }
71    }
72}
73
74/// The `--me` state: list only client workspaces owned by the current user
75/// (equivalent to `-u $P4USER`).
76///
77/// Created by [`Clients::filter_me`].
78#[cfg(not(feature = "lt2016_1"))]
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub struct Me {}
81
82#[cfg(not(feature = "lt2016_1"))]
83impl ExclusiveOption for Me {
84    fn inject_args(&self, command: &mut Command) {
85        command.arg("--me");
86    }
87}
88
89// ---------------------------------------------------------------------------
90// List category states (-a / -s serverID)
91// ---------------------------------------------------------------------------
92
93/// The `-a` state: list all client workspaces, not just workspaces bound to
94/// this server.
95///
96/// Created by [`Clients::all`].
97#[derive(Debug, Clone, PartialEq, Eq)]
98pub struct ListAll {}
99
100impl ExclusiveOption for ListAll {
101    fn inject_args(&self, command: &mut Command) {
102        command.arg("-a");
103    }
104}
105
106/// The `-s serverID` state: list only client workspaces bound to the
107/// specified server.
108///
109/// Created by [`Clients::server_id`].
110#[derive(Debug, Clone, PartialEq, Eq)]
111pub struct ListSpecified {
112    server_id: String,
113}
114
115impl ExclusiveOption for ListSpecified {
116    fn inject_args(&self, command: &mut Command) {
117        command.arg("-s").arg(&self.server_id);
118    }
119}
120
121// ---------------------------------------------------------------------------
122// Mode structs
123// ---------------------------------------------------------------------------
124
125/// The regular listing form: `p4 clients [-t] [-u user | --me] [[-e|-E]
126/// filter] [-m max] [-S stream] [-a | -s serverID]`.
127///
128/// Entered from [`Clients<Unselected>`](Clients) by setting any regular
129/// option or filter, for example [`Clients::display_time`],
130/// [`Clients::filter`], or [`Clients::user`].
131///
132/// The `F`, `U`, and `C` type parameters track the mutually exclusive option
133/// groups at compile time, each starting as [`Unselected`]:
134/// - `F`: the `-e` / `-E` name filter, entered via [`Clients::filter`]
135///   ([`Filter`]).
136#[cfg_attr(
137    feature = "lt2016_1",
138    doc = "- `U`: the `-u user` owner filter, entered via [`Clients::user`] ([`User`])."
139)]
140#[cfg_attr(
141    not(feature = "lt2016_1"),
142    doc = "- `U`: the `-u user` / `--me` owner filter, entered via [`Clients::user`]",
143    doc = "  ([`User`]) or [`Clients::filter_me`] ([`Me`])."
144)]
145/// - `C`: the `-a` / `-s serverID` list category, entered via
146///   [`Clients::all`] ([`ListAll`]) or [`Clients::server_id`]
147///   ([`ListSpecified`]).
148///
149/// Each group can be set at most once; the remaining options stay available
150/// afterwards.
151#[derive(Debug, Clone)]
152pub struct RegularMode<F = Unselected, U = Unselected, C = Unselected> {
153    display_time: bool,
154
155    limit: Option<u64>,
156
157    stream: Option<String>,
158
159    name_filter: F,
160
161    user_filter: U,
162
163    list_category: C,
164}
165
166/// The unloaded listing form: `p4 clients -U`.
167///
168/// List only client workspaces unloaded with `p4 unload`. This form is
169/// entered via [`Clients::unloaded`] and accepts no other options.
170#[derive(Debug, Clone, Default)]
171pub struct UnloadedMode {}
172
173// ---------------------------------------------------------------------------
174// Command struct
175// ---------------------------------------------------------------------------
176
177#[cfg_attr(
178    feature = "lt2015_1",
179    doc = "`p4 [g-opts] clients [-t] [ -u user ] [ [-e|-E] filter -m max ] -S stream [-a | -s serverID]`"
180)]
181#[cfg_attr(
182    all(feature = "lt2016_1", not(feature = "lt2015_1")),
183    doc = "`p4 [g-opts] clients [-t] [-u user] [[-e|-E] filter] [-m max] [-S stream] [-a | -s serverID]`"
184)]
185#[cfg_attr(
186    all(feature = "lt2024_2", not(feature = "lt2016_1")),
187    doc = "`p4 [g-opts] clients [-t] [-u user | --me] [[-e|-E] filter] [-m max] [-S stream] [-a | -s serverID]`"
188)]
189#[cfg_attr(
190    not(feature = "lt2024_2"),
191    doc = "`p4 [g-opts] clients [-t] [-u user [--user-case-insensitive] | --me] [[-e|-E] filter] [-m max] [-S stream] [-a | -s serverID]`"
192)]
193///
194/// `p4 [g-opts] clients -U`
195///
196/// List all client workspaces currently known to the system.
197///
198/// The command `p4 workspaces` is an alias for `p4 clients`.
199///
200/// The `M` type parameter tracks the command form at compile time, starting
201/// as [`Unselected`] from [`Clients::new`], which spawns the bare `p4
202/// clients` report. Set any regular option or filter (for example
203/// [`Self::display_time`], [`Self::filter`], or [`Self::user`]) to enter
204/// [`RegularMode`], or call [`Self::unloaded`] (`-U`) to enter
205/// [`UnloadedMode`].
206#[derive(Debug, Clone, Default)]
207pub struct Clients<M = Unselected> {
208    bin: PathBuf,
209
210    global_opts: GlobalOpts,
211
212    mode: M,
213}
214
215// ---------------------------------------------------------------------------
216// Constructor
217// ---------------------------------------------------------------------------
218
219impl Clients<Unselected> {
220    /// Creates a new `p4 clients` command with no option selected.
221    ///
222    /// `bin` is the path to the Perforce command-line executable. The
223    /// command spawns the bare `p4 clients` report as is; set any regular
224    /// option or filter to enter [`RegularMode`], or call
225    /// [`Self::unloaded`] to enter [`UnloadedMode`].
226    pub fn new(bin: impl Into<PathBuf>, global_opts: GlobalOpts) -> Self {
227        Self {
228            bin: bin.into(),
229            global_opts,
230            ..Default::default()
231        }
232    }
233
234    /// # Description
235    ///
236    /// -U
237    ///
238    /// List only client workspaces unloaded with `p4 unload`.
239    ///
240    /// This is a standalone syntax form (`p4 clients -U`) that accepts no
241    /// other options.
242    ///
243    /// Transitions this command to the [`UnloadedMode`] state.
244    pub fn unloaded(self) -> Clients<UnloadedMode> {
245        Clients {
246            bin: self.bin,
247            global_opts: self.global_opts,
248            mode: UnloadedMode {},
249        }
250    }
251
252    /// # Description
253    ///
254    /// -t
255    ///
256    /// Display the time as well as the date of the last update to the
257    /// workspace.
258    ///
259    /// Transitions this command to the [`RegularMode`] state.
260    pub fn display_time(self, v: bool) -> Clients<RegularMode> {
261        Clients {
262            bin: self.bin,
263            global_opts: self.global_opts,
264            mode: RegularMode {
265                display_time: v,
266                limit: None,
267                stream: None,
268                name_filter: Unselected,
269                user_filter: Unselected,
270                list_category: Unselected,
271            },
272        }
273    }
274
275    /// # Description
276    ///
277    /// -m max
278    ///
279    /// List only the first `max` client workspaces.
280    ///
281    /// Transitions this command to the [`RegularMode`] state.
282    pub fn limit(self, v: u64) -> Clients<RegularMode> {
283        Clients {
284            bin: self.bin,
285            global_opts: self.global_opts,
286            mode: RegularMode {
287                display_time: false,
288                limit: Some(v),
289                stream: None,
290                name_filter: Unselected,
291                user_filter: Unselected,
292                list_category: Unselected,
293            },
294        }
295    }
296
297    /// # Description
298    ///
299    /// -S stream
300    ///
301    /// List client workspaces associated with the specified stream.
302    ///
303    /// Transitions this command to the [`RegularMode`] state.
304    pub fn stream(self, v: impl Into<String>) -> Clients<RegularMode> {
305        Clients {
306            bin: self.bin,
307            global_opts: self.global_opts,
308            mode: RegularMode {
309                display_time: false,
310                limit: None,
311                stream: Some(v.into()),
312                name_filter: Unselected,
313                user_filter: Unselected,
314                list_category: Unselected,
315            },
316        }
317    }
318
319    /// # Description
320    ///
321    /// -e filter / -E filter
322    ///
323    /// `v` is the client workspace name filter pattern; lists only client
324    /// workspaces whose name matches it.
325    ///
326    /// When `case_insensitive` is `false` (`-e`), the pattern is matched
327    /// using the server's normal case-sensitivity rules. When
328    /// `case_insensitive` is `true` (`-E`), the pattern is matched
329    /// case-insensitively, even on a case-sensitive server.
330    #[cfg_attr(
331        not(feature = "lt2024_2"),
332        doc = "",
333        doc = "`--client-case-insensitive` is equivalent to `-E`."
334    )]
335    ///
336    /// Transitions this command to the [`Filter`] state.
337    pub fn filter(
338        self,
339        v: impl Into<String>,
340        case_insensitive: bool,
341    ) -> Clients<RegularMode<Filter, Unselected, Unselected>> {
342        Clients {
343            bin: self.bin,
344            global_opts: self.global_opts,
345            mode: RegularMode {
346                display_time: false,
347                limit: None,
348                stream: None,
349                name_filter: if case_insensitive {
350                    Filter::InCaseSensitiveMode(v.into())
351                } else {
352                    Filter::CaseSensitiveMode(v.into())
353                },
354                user_filter: Unselected,
355                list_category: Unselected,
356            },
357        }
358    }
359
360    /// # Description
361    ///
362    #[cfg_attr(feature = "lt2024_2", doc = "-u user")]
363    #[cfg_attr(not(feature = "lt2024_2"), doc = "-u user [--user-case-insensitive]")]
364    ///
365    #[cfg_attr(
366        feature = "lt2024_2",
367        doc = "List only client workspaces owned by `v`."
368    )]
369    #[cfg_attr(
370        not(feature = "lt2024_2"),
371        doc = "List client workspaces that are owned by `v`. This can include `*` wildcards to form a search pattern. If wildcards are used, enclose the search pattern in double quotes (`\"`).",
372        doc = "",
373        doc = "For example:",
374        doc = "",
375        doc = "`p4 clients -u \"O*hara\"`",
376        doc = "",
377        doc = "Call [`Clients::case_insensitive`] on the entered state to add the `--user-case-insensitive` suboption."
378    )]
379    ///
380    /// Transitions this command to the [`User`] state.
381    pub fn user(self, v: impl Into<String>) -> Clients<RegularMode<Unselected, User, Unselected>> {
382        Clients {
383            bin: self.bin,
384            global_opts: self.global_opts,
385            mode: RegularMode {
386                display_time: false,
387                limit: None,
388                stream: None,
389                name_filter: Unselected,
390                user_filter: User {
391                    user: v.into(),
392                    #[cfg(not(feature = "lt2024_2"))]
393                    case_insensitive: false,
394                },
395                list_category: Unselected,
396            },
397        }
398    }
399
400    /// # Description
401    ///
402    /// --me
403    ///
404    /// Equivalent to `-u $P4USER`.
405    ///
406    /// Transitions this command to the [`Me`] state.
407    #[cfg(not(feature = "lt2016_1"))]
408    pub fn filter_me(self) -> Clients<RegularMode<Unselected, Me, Unselected>> {
409        Clients {
410            bin: self.bin,
411            global_opts: self.global_opts,
412            mode: RegularMode {
413                display_time: false,
414                limit: None,
415                stream: None,
416                name_filter: Unselected,
417                user_filter: Me {},
418                list_category: Unselected,
419            },
420        }
421    }
422
423    /// # Description
424    ///
425    /// -a
426    ///
427    /// List all client workspaces, not just workspaces bound to this server.
428    ///
429    /// Transitions this command to the [`ListAll`] state.
430    pub fn all(self) -> Clients<RegularMode<Unselected, Unselected, ListAll>> {
431        Clients {
432            bin: self.bin,
433            global_opts: self.global_opts,
434            mode: RegularMode {
435                display_time: false,
436                limit: None,
437                stream: None,
438                name_filter: Unselected,
439                user_filter: Unselected,
440                list_category: ListAll {},
441            },
442        }
443    }
444
445    /// # Description
446    ///
447    /// -s serverID
448    ///
449    /// List only client workspaces bound to the specified `serverID`. On an
450    /// edge server, the `-s` option defaults to the edge server's serverID.
451    ///
452    /// Transitions this command to the [`ListSpecified`] state.
453    pub fn server_id(
454        self,
455        v: impl Into<String>,
456    ) -> Clients<RegularMode<Unselected, Unselected, ListSpecified>> {
457        Clients {
458            bin: self.bin,
459            global_opts: self.global_opts,
460            mode: RegularMode {
461                display_time: false,
462                limit: None,
463                stream: None,
464                name_filter: Unselected,
465                user_filter: Unselected,
466                list_category: ListSpecified {
467                    server_id: v.into(),
468                },
469            },
470        }
471    }
472}
473
474// ---------------------------------------------------------------------------
475// Shared accessors
476// ---------------------------------------------------------------------------
477
478impl<M> Clients<M> {
479    /// Get the Perforce command path.
480    pub fn get_bin(&self) -> &Path {
481        &self.bin
482    }
483
484    /// Set the Perforce command path.
485    pub fn set_bin(&mut self, bin: impl Into<PathBuf>) -> &mut Self {
486        self.bin = bin.into();
487        self
488    }
489
490    /// Set the Perforce command path.
491    pub fn bin(mut self, bin: impl Into<PathBuf>) -> Self {
492        self.set_bin(bin);
493        self
494    }
495
496    /// # Description
497    ///
498    /// g-opts
499    ///
500    #[cfg_attr(
501        feature = "lt2014_2",
502        doc = "See the [Global Options](GlobalOpts) section."
503    )]
504    #[cfg_attr(
505        all(feature = "lt2015_1", not(feature = "lt2014_2")),
506        doc = "See the [“Global Options”](GlobalOpts) section."
507    )]
508    #[cfg_attr(
509        all(feature = "lt2017_1", not(feature = "lt2015_1")),
510        doc = "See [“Global Options”](GlobalOpts)."
511    )]
512    #[cfg_attr(
513        all(feature = "lt2018_2", not(feature = "lt2017_1")),
514        doc = "See [Global Options](GlobalOpts)."
515    )]
516    #[cfg_attr(not(feature = "lt2018_2"), doc = "See [Global options](GlobalOpts).")]
517    pub fn get_global_opts(&self) -> &GlobalOpts {
518        &self.global_opts
519    }
520
521    /// # Description
522    ///
523    /// g-opts
524    ///
525    #[cfg_attr(
526        feature = "lt2014_2",
527        doc = "See the [Global Options](GlobalOpts) section."
528    )]
529    #[cfg_attr(
530        all(feature = "lt2015_1", not(feature = "lt2014_2")),
531        doc = "See the [“Global Options”](GlobalOpts) section."
532    )]
533    #[cfg_attr(
534        all(feature = "lt2017_1", not(feature = "lt2015_1")),
535        doc = "See [“Global Options”](GlobalOpts)."
536    )]
537    #[cfg_attr(
538        all(feature = "lt2018_2", not(feature = "lt2017_1")),
539        doc = "See [Global Options](GlobalOpts)."
540    )]
541    #[cfg_attr(not(feature = "lt2018_2"), doc = "See [Global options](GlobalOpts).")]
542    pub fn set_global_opts(&mut self, v: GlobalOpts) -> &mut Self {
543        self.global_opts = v;
544        self
545    }
546
547    /// # Description
548    ///
549    /// g-opts
550    ///
551    #[cfg_attr(
552        feature = "lt2014_2",
553        doc = "See the [Global Options](GlobalOpts) section."
554    )]
555    #[cfg_attr(
556        all(feature = "lt2015_1", not(feature = "lt2014_2")),
557        doc = "See the [“Global Options”](GlobalOpts) section."
558    )]
559    #[cfg_attr(
560        all(feature = "lt2017_1", not(feature = "lt2015_1")),
561        doc = "See [“Global Options”](GlobalOpts)."
562    )]
563    #[cfg_attr(
564        all(feature = "lt2018_2", not(feature = "lt2017_1")),
565        doc = "See [Global Options](GlobalOpts)."
566    )]
567    #[cfg_attr(not(feature = "lt2018_2"), doc = "See [Global options](GlobalOpts).")]
568    pub fn global_opts(mut self, v: GlobalOpts) -> Self {
569        self.global_opts = v;
570        self
571    }
572}
573
574// ---------------------------------------------------------------------------
575// Regular form accessors
576// ---------------------------------------------------------------------------
577
578impl<F, U, C> Clients<RegularMode<F, U, C>> {
579    /// # Description
580    ///
581    /// -m max
582    ///
583    /// List only the first `max` client workspaces.
584    pub fn get_limit(&self) -> Option<u64> {
585        self.mode.limit
586    }
587
588    /// # Description
589    ///
590    /// -m max
591    ///
592    /// List only the first `max` client workspaces.
593    pub fn set_limit(&mut self, v: u64) -> &mut Self {
594        self.mode.limit = Some(v);
595        self
596    }
597
598    /// # Description
599    ///
600    /// -m max
601    ///
602    /// List only the first `max` client workspaces.
603    pub fn limit(mut self, v: u64) -> Self {
604        self.mode.limit = Some(v);
605        self
606    }
607
608    /// # Description
609    ///
610    /// -t
611    ///
612    /// Display the time as well as the date of the last update to the
613    /// workspace.
614    pub fn get_display_time(&self) -> bool {
615        self.mode.display_time
616    }
617
618    /// # Description
619    ///
620    /// -t
621    ///
622    /// Display the time as well as the date of the last update to the
623    /// workspace.
624    pub fn set_display_time(&mut self, v: bool) -> &mut Self {
625        self.mode.display_time = v;
626        self
627    }
628
629    /// # Description
630    ///
631    /// -t
632    ///
633    /// Display the time as well as the date of the last update to the
634    /// workspace.
635    pub fn display_time(mut self, v: bool) -> Self {
636        self.mode.display_time = v;
637        self
638    }
639
640    /// # Description
641    ///
642    /// -S stream
643    ///
644    /// List client workspaces associated with the specified stream.
645    pub fn get_stream(&self) -> Option<&String> {
646        self.mode.stream.as_ref()
647    }
648
649    /// # Description
650    ///
651    /// -S stream
652    ///
653    /// List client workspaces associated with the specified stream.
654    pub fn set_stream(&mut self, v: impl Into<String>) -> &mut Self {
655        self.mode.stream = Some(v.into());
656        self
657    }
658
659    /// # Description
660    ///
661    /// -S stream
662    ///
663    /// List client workspaces associated with the specified stream.
664    pub fn stream(mut self, v: impl Into<String>) -> Self {
665        self.mode.stream = Some(v.into());
666        self
667    }
668}
669
670// ---------------------------------------------------------------------------
671// Name filter transitions
672// ---------------------------------------------------------------------------
673
674impl<U, C> Clients<RegularMode<Unselected, U, C>> {
675    /// # Description
676    ///
677    /// -e filter / -E filter
678    ///
679    /// `v` is the client workspace name filter pattern; lists only client
680    /// workspaces whose name matches it.
681    ///
682    /// When `case_insensitive` is `false` (`-e`), the pattern is matched
683    /// using the server's normal case-sensitivity rules. When
684    /// `case_insensitive` is `true` (`-E`), the pattern is matched
685    /// case-insensitively, even on a case-sensitive server.
686    #[cfg_attr(
687        not(feature = "lt2024_2"),
688        doc = "",
689        doc = "`--client-case-insensitive` is equivalent to `-E`."
690    )]
691    ///
692    /// Transitions this command to the [`Filter`] state.
693    pub fn filter(
694        self,
695        v: impl Into<String>,
696        case_insensitive: bool,
697    ) -> Clients<RegularMode<Filter, U, C>> {
698        Clients {
699            bin: self.bin,
700            global_opts: self.global_opts,
701            mode: RegularMode {
702                display_time: self.mode.display_time,
703                limit: self.mode.limit,
704                stream: self.mode.stream,
705                user_filter: self.mode.user_filter,
706                list_category: self.mode.list_category,
707                name_filter: if case_insensitive {
708                    Filter::InCaseSensitiveMode(v.into())
709                } else {
710                    Filter::CaseSensitiveMode(v.into())
711                },
712            },
713        }
714    }
715}
716
717// ---------------------------------------------------------------------------
718// Owner filter transitions
719// ---------------------------------------------------------------------------
720
721impl<F, C> Clients<RegularMode<F, Unselected, C>> {
722    /// # Description
723    ///
724    #[cfg_attr(feature = "lt2024_2", doc = "-u user")]
725    #[cfg_attr(not(feature = "lt2024_2"), doc = "-u user [--user-case-insensitive]")]
726    ///
727    #[cfg_attr(
728        feature = "lt2024_2",
729        doc = "List only client workspaces owned by `v`."
730    )]
731    #[cfg_attr(
732        not(feature = "lt2024_2"),
733        doc = "List client workspaces that are owned by `v`. This can include `*` wildcards to form a search pattern. If wildcards are used, enclose the search pattern in double quotes (`\"`).",
734        doc = "",
735        doc = "For example:",
736        doc = "",
737        doc = "`p4 clients -u \"O*hara\"`",
738        doc = "",
739        doc = "Call [`Clients::case_insensitive`] on the entered state to add the `--user-case-insensitive` suboption."
740    )]
741    ///
742    /// Transitions this command to the [`User`] state.
743    pub fn user(self, v: impl Into<String>) -> Clients<RegularMode<F, User, C>> {
744        Clients {
745            bin: self.bin,
746            global_opts: self.global_opts,
747            mode: RegularMode {
748                display_time: self.mode.display_time,
749                limit: self.mode.limit,
750                stream: self.mode.stream,
751                name_filter: self.mode.name_filter,
752                list_category: self.mode.list_category,
753                user_filter: User {
754                    user: v.into(),
755                    #[cfg(not(feature = "lt2024_2"))]
756                    case_insensitive: false,
757                },
758            },
759        }
760    }
761
762    /// # Description
763    ///
764    /// --me
765    ///
766    /// Equivalent to `-u $P4USER`.
767    ///
768    /// Transitions this command to the [`Me`] state.
769    #[cfg(not(feature = "lt2016_1"))]
770    pub fn filter_me(self) -> Clients<RegularMode<F, Me, C>> {
771        Clients {
772            bin: self.bin,
773            global_opts: self.global_opts,
774            mode: RegularMode {
775                display_time: self.mode.display_time,
776                limit: self.mode.limit,
777                stream: self.mode.stream,
778                name_filter: self.mode.name_filter,
779                list_category: self.mode.list_category,
780                user_filter: Me {},
781            },
782        }
783    }
784}
785
786impl<F, C> Clients<RegularMode<F, User, C>> {
787    /// # Description
788    ///
789    /// --user-case-insensitive
790    ///
791    /// Indicates that the `-u` user value is a case-insensitive search
792    /// pattern, even on a case-sensitive server.
793    ///
794    /// For example:
795    ///
796    /// `p4 clients -u "O*hara" --user-case-insensitive`
797    #[cfg(not(feature = "lt2024_2"))]
798    pub fn case_insensitive(self) -> Clients<RegularMode<F, User, C>> {
799        Clients {
800            bin: self.bin,
801            global_opts: self.global_opts,
802            mode: RegularMode {
803                display_time: self.mode.display_time,
804                limit: self.mode.limit,
805                stream: self.mode.stream,
806                name_filter: self.mode.name_filter,
807                list_category: self.mode.list_category,
808                user_filter: User {
809                    user: self.mode.user_filter.user,
810                    case_insensitive: true,
811                },
812            },
813        }
814    }
815}
816
817// ---------------------------------------------------------------------------
818// List category transitions
819// ---------------------------------------------------------------------------
820
821impl<F, U> Clients<RegularMode<F, U, Unselected>> {
822    /// # Description
823    ///
824    /// -a
825    ///
826    /// List all client workspaces, not just workspaces bound to this server.
827    ///
828    /// Transitions this command to the [`ListAll`] state.
829    pub fn all(self) -> Clients<RegularMode<F, U, ListAll>> {
830        Clients {
831            bin: self.bin,
832            global_opts: self.global_opts,
833            mode: RegularMode {
834                display_time: self.mode.display_time,
835                limit: self.mode.limit,
836                stream: self.mode.stream,
837                name_filter: self.mode.name_filter,
838                user_filter: self.mode.user_filter,
839                list_category: ListAll {},
840            },
841        }
842    }
843
844    /// # Description
845    ///
846    /// -s serverID
847    ///
848    /// List only client workspaces bound to the specified `serverID`. On an
849    /// edge server, the `-s` option defaults to the edge server's serverID.
850    ///
851    /// Transitions this command to the [`ListSpecified`] state.
852    pub fn server_id(self, v: impl Into<String>) -> Clients<RegularMode<F, U, ListSpecified>> {
853        Clients {
854            bin: self.bin,
855            global_opts: self.global_opts,
856            mode: RegularMode {
857                display_time: self.mode.display_time,
858                limit: self.mode.limit,
859                stream: self.mode.stream,
860                name_filter: self.mode.name_filter,
861                user_filter: self.mode.user_filter,
862                list_category: ListSpecified {
863                    server_id: v.into(),
864                },
865            },
866        }
867    }
868}
869
870// ---------------------------------------------------------------------------
871// SubCommand
872// ---------------------------------------------------------------------------
873
874impl SubCommand for Clients<Unselected> {
875    fn name(&self) -> &str {
876        "clients"
877    }
878
879    fn inject_local_args(&self, _: &mut Command) {}
880
881    fn global_opts(&self) -> Option<&GlobalOpts> {
882        Some(&self.global_opts)
883    }
884}
885
886impl<F: ExclusiveOption, U: ExclusiveOption, C: ExclusiveOption> SubCommand
887    for Clients<RegularMode<F, U, C>>
888{
889    fn name(&self) -> &str {
890        "clients"
891    }
892
893    fn inject_local_args(&self, command: &mut Command) {
894        if self.mode.display_time {
895            command.arg("-t");
896        }
897        self.mode.user_filter.inject_args(command);
898        self.mode.name_filter.inject_args(command);
899        if let Some(max) = self.mode.limit {
900            command.arg("-m").arg(max.to_string());
901        }
902        if let Some(ref stream) = self.mode.stream {
903            command.arg("-S").arg(stream);
904        }
905        self.mode.list_category.inject_args(command);
906    }
907
908    fn global_opts(&self) -> Option<&GlobalOpts> {
909        Some(&self.global_opts)
910    }
911}
912
913impl SubCommand for Clients<UnloadedMode> {
914    fn name(&self) -> &str {
915        "clients"
916    }
917
918    fn inject_local_args(&self, command: &mut Command) {
919        command.arg("-U");
920    }
921
922    fn global_opts(&self) -> Option<&GlobalOpts> {
923        Some(&self.global_opts)
924    }
925}
926
927// ---------------------------------------------------------------------------
928// Spawning
929// ---------------------------------------------------------------------------
930
931impl ParameterizedSpawn<()> for Clients<Unselected> {
932    type Output = Child;
933    type Error = std::io::Error;
934
935    /// Spawns `p4 clients` as a child process with piped standard output
936    /// and error streams; use the returned [`Child`] handle to wait for it
937    /// or interact with it.
938    fn spawn_with(&mut self, (): ()) -> Result<Self::Output, Self::Error> {
939        self.setup_command(&self.bin)
940            .stdout(Stdio::piped())
941            .stderr(Stdio::piped())
942            .spawn()
943    }
944}
945
946impl<F: ExclusiveOption, U: ExclusiveOption, C: ExclusiveOption> ParameterizedSpawn<()>
947    for Clients<RegularMode<F, U, C>>
948{
949    type Output = Child;
950    type Error = std::io::Error;
951
952    /// Spawns `p4 clients` as a child process with piped standard output
953    /// and error streams; use the returned [`Child`] handle to wait for it
954    /// or interact with it.
955    fn spawn_with(&mut self, (): ()) -> Result<Self::Output, Self::Error> {
956        self.setup_command(&self.bin)
957            .stdout(Stdio::piped())
958            .stderr(Stdio::piped())
959            .spawn()
960    }
961}
962
963impl ParameterizedSpawn<()> for Clients<UnloadedMode> {
964    type Output = Child;
965    type Error = std::io::Error;
966
967    /// Spawns `p4 clients -U` as a child process with piped standard output
968    /// and error streams; use the returned [`Child`] handle to wait for it
969    /// or interact with it.
970    fn spawn_with(&mut self, (): ()) -> Result<Self::Output, Self::Error> {
971        self.setup_command(&self.bin)
972            .stdout(Stdio::piped())
973            .stderr(Stdio::piped())
974            .spawn()
975    }
976}
977
978#[cfg(test)]
979mod tests {
980    use super::*;
981    use crate::cmd::args_of;
982
983    #[test]
984    fn bin_accessors_update_executable_path() {
985        let mut command = Clients::new("p4", GlobalOpts::new());
986        assert_eq!(command.get_bin(), Path::new("p4"));
987
988        command.set_bin("/usr/local/bin/p4");
989        assert_eq!(command.get_bin(), Path::new("/usr/local/bin/p4"));
990
991        let command = command.bin("p4.exe");
992        assert_eq!(command.get_bin(), Path::new("p4.exe"));
993    }
994
995    // Compile-time rejection: -e and -E are mutually exclusive by
996    // construction (the Filter enum holds exactly one variant, and no
997    // transition exists on Clients<RegularMode<Filter, ..>>).
998    // Compile-time rejection: -u and --me are mutually exclusive (user and
999    // filter_me exist only on the Unselected owner-filter state).
1000    // Compile-time rejection: case_insensitive exists only on the User
1001    // state, never on Me or Unselected.
1002    // Compile-time rejection: -a and -s are mutually exclusive (all and
1003    // server_id exist only on the Unselected list-category state).
1004    // Compile-time rejection: -U is only reachable from Clients<Unselected>,
1005    // and Clients<UnloadedMode> offers no other options.
1006    // Each filter can be set at most once; limit, display_time, stream, and
1007    // the other filters stay available afterwards.
1008
1009    #[test]
1010    fn without_options() {
1011        let clients = Clients::new("p4", GlobalOpts::new());
1012        assert_eq!(args_of(&clients.setup_command("p4")), ["clients"]);
1013    }
1014
1015    #[test]
1016    fn limit() {
1017        let clients = Clients::new("p4", GlobalOpts::new()).limit(5);
1018        assert_eq!(
1019            args_of(&clients.setup_command("p4")),
1020            ["clients", "-m", "5"]
1021        );
1022    }
1023
1024    #[test]
1025    fn display_time() {
1026        let clients = Clients::new("p4", GlobalOpts::new()).display_time(true);
1027        assert_eq!(args_of(&clients.setup_command("p4")), ["clients", "-t"]);
1028    }
1029
1030    #[test]
1031    fn display_time_can_be_unset() {
1032        let clients = Clients::new("p4", GlobalOpts::new()).display_time(false);
1033        assert_eq!(args_of(&clients.setup_command("p4")), ["clients"]);
1034    }
1035
1036    #[test]
1037    fn stream() {
1038        let clients = Clients::new("p4", GlobalOpts::new()).stream("//stream/main");
1039        assert_eq!(
1040            args_of(&clients.setup_command("p4")),
1041            ["clients", "-S", "//stream/main"]
1042        );
1043    }
1044
1045    #[test]
1046    fn filter_case_sensitive() {
1047        let clients = Clients::new("p4", GlobalOpts::new()).filter("p4vBeta*", false);
1048        assert_eq!(
1049            args_of(&clients.setup_command("p4")),
1050            ["clients", "-e", "p4vBeta*"]
1051        );
1052    }
1053
1054    #[test]
1055    fn filter_case_insensitive() {
1056        let clients = Clients::new("p4", GlobalOpts::new()).filter("*Us*rs", true);
1057        assert_eq!(
1058            args_of(&clients.setup_command("p4")),
1059            ["clients", "-E", "*Us*rs"]
1060        );
1061    }
1062
1063    #[test]
1064    fn user() {
1065        let clients = Clients::new("p4", GlobalOpts::new()).user("O*hara");
1066        assert_eq!(
1067            args_of(&clients.setup_command("p4")),
1068            ["clients", "-u", "O*hara"]
1069        );
1070    }
1071
1072    #[cfg(not(feature = "lt2024_2"))]
1073    #[test]
1074    fn user_case_insensitive() {
1075        let clients = Clients::new("p4", GlobalOpts::new())
1076            .user("O*hara")
1077            .case_insensitive();
1078        assert_eq!(
1079            args_of(&clients.setup_command("p4")),
1080            ["clients", "-u", "O*hara", "--user-case-insensitive"]
1081        );
1082    }
1083
1084    #[cfg(not(feature = "lt2016_1"))]
1085    #[test]
1086    fn filter_me() {
1087        let clients = Clients::new("p4", GlobalOpts::new()).filter_me();
1088        assert_eq!(args_of(&clients.setup_command("p4")), ["clients", "--me"]);
1089    }
1090
1091    #[test]
1092    fn all() {
1093        let clients = Clients::new("p4", GlobalOpts::new()).all();
1094        assert_eq!(args_of(&clients.setup_command("p4")), ["clients", "-a"]);
1095    }
1096
1097    #[test]
1098    fn server_id() {
1099        let clients = Clients::new("p4", GlobalOpts::new()).server_id("edge1");
1100        assert_eq!(
1101            args_of(&clients.setup_command("p4")),
1102            ["clients", "-s", "edge1"]
1103        );
1104    }
1105
1106    #[test]
1107    fn unloaded() {
1108        let clients = Clients::new("p4", GlobalOpts::new()).unloaded();
1109        assert_eq!(args_of(&clients.setup_command("p4")), ["clients", "-U"]);
1110    }
1111
1112    #[test]
1113    fn transitions_preserve_other_options() {
1114        let clients = Clients::new("p4", GlobalOpts::new())
1115            .user("O*hara")
1116            .filter("p4v*", false)
1117            .limit(5)
1118            .display_time(true)
1119            .stream("//stream/main")
1120            .all();
1121        assert_eq!(
1122            args_of(&clients.setup_command("p4")),
1123            [
1124                "clients",
1125                "-t",
1126                "-u",
1127                "O*hara",
1128                "-e",
1129                "p4v*",
1130                "-m",
1131                "5",
1132                "-S",
1133                "//stream/main",
1134                "-a"
1135            ]
1136        );
1137
1138        let clients = Clients::new("p4", GlobalOpts::new())
1139            .server_id("edge1")
1140            .filter("*Us*rs", true);
1141        assert_eq!(
1142            args_of(&clients.setup_command("p4")),
1143            ["clients", "-E", "*Us*rs", "-s", "edge1"]
1144        );
1145    }
1146
1147    #[test]
1148    fn setters_update_regular_options() {
1149        let mut clients = Clients::new("p4", GlobalOpts::new()).filter("p4v*", false);
1150        assert_eq!(clients.get_limit(), None);
1151        clients.set_limit(10);
1152        assert_eq!(clients.get_limit(), Some(10));
1153        assert!(!clients.get_display_time());
1154        clients.set_display_time(true);
1155        assert!(clients.get_display_time());
1156        assert_eq!(clients.get_stream(), None);
1157        clients.set_stream("//stream/dev");
1158        assert_eq!(clients.get_stream(), Some(&"//stream/dev".to_string()));
1159    }
1160
1161    #[test]
1162    fn all_options_order() {
1163        let clients = Clients::new("p4", GlobalOpts::new())
1164            .display_time(true)
1165            .user("O*hara")
1166            .filter("*Us*rs", true)
1167            .limit(5)
1168            .stream("//stream/main")
1169            .server_id("edge1");
1170        assert_eq!(
1171            args_of(&clients.setup_command("p4")),
1172            [
1173                "clients",
1174                "-t",
1175                "-u",
1176                "O*hara",
1177                "-E",
1178                "*Us*rs",
1179                "-m",
1180                "5",
1181                "-S",
1182                "//stream/main",
1183                "-s",
1184                "edge1"
1185            ]
1186        );
1187    }
1188
1189    #[test]
1190    fn global_opts_are_injected_once() {
1191        let clients = Clients::new("p4", GlobalOpts::new().port("localhost:1666"));
1192        assert_eq!(
1193            args_of(&clients.setup_command("p4")),
1194            ["-p", "localhost:1666", "clients"]
1195        );
1196
1197        let clients = Clients::new("p4", GlobalOpts::new().port("localhost:1666")).limit(1);
1198        assert_eq!(
1199            args_of(&clients.setup_command("p4")),
1200            ["-p", "localhost:1666", "clients", "-m", "1"]
1201        );
1202
1203        let clients = Clients::new("p4", GlobalOpts::new().port("localhost:1666")).unloaded();
1204        assert_eq!(
1205            args_of(&clients.setup_command("p4")),
1206            ["-p", "localhost:1666", "clients", "-U"]
1207        );
1208    }
1209}