Skip to main content

perforce_cli/cmd/
counter.rs

1use std::{
2    ffi::OsStr,
3    path::{Path, PathBuf},
4    process::{Child, Command, Stdio},
5};
6
7use super::{ExclusiveOption, SubCommand, Unselected};
8
9use crate::global::GlobalOpts;
10use crate::spawn::ParameterizedSpawn;
11
12// ---------------------------------------------------------------------------
13// Mode structs
14// ---------------------------------------------------------------------------
15
16/// The `-v` (show previous) state of the set and increment forms.
17///
18/// When selected, the previous value of the counter is displayed after the
19/// counter has been set or incremented.
20#[cfg(not(feature = "lt2016_1"))]
21#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
22pub struct ShowPrevious;
23
24#[cfg_attr(
25    feature = "lt2016_1",
26    doc = "The set form: `p4 [g-opts] counter [-f] countername value`."
27)]
28#[cfg_attr(
29    not(feature = "lt2016_1"),
30    doc = "The set form: `p4 [g-opts] counter [-f -v] countername value`."
31)]
32///
33/// Sets the value of `countername`, creating the counter if it does not
34/// already exist.
35#[cfg_attr(
36    feature = "lt2016_1",
37    doc = "The `B` type parameter only ever takes [`Unselected`]; `-v` is not available in this version."
38)]
39#[cfg_attr(
40    not(feature = "lt2016_1"),
41    doc = "The `B` type parameter tracks whether `-v` has been supplied: [`Unselected`] does not display the previous value; [`ShowPrevious`] does."
42)]
43#[derive(Debug, Clone, Default, PartialEq, Eq)]
44pub struct SetMode<B = Unselected> {
45    force: bool,
46    show_previous: B,
47}
48
49impl ExclusiveOption for SetMode<Unselected> {
50    fn inject_args(&self, command: &mut Command) {
51        if self.force {
52            command.arg("-f");
53        }
54    }
55}
56
57#[cfg(not(feature = "lt2016_1"))]
58impl ExclusiveOption for SetMode<ShowPrevious> {
59    fn inject_args(&self, command: &mut Command) {
60        if self.force {
61            command.arg("-f");
62        }
63        command.arg("-v");
64    }
65}
66
67/// The delete form: `p4 [g-opts] counter [-f] -d countername`.
68///
69/// Deletes `countername`, which has the same effect as setting the counter
70/// to zero.
71#[derive(Debug, Clone, Default, PartialEq, Eq)]
72pub struct DeleteMode {
73    force: bool,
74}
75
76impl ExclusiveOption for DeleteMode {
77    fn inject_args(&self, command: &mut Command) {
78        if self.force {
79            command.arg("-f");
80        }
81        command.arg("-d");
82    }
83}
84
85/// The increment form: `p4 [g-opts] counter [-f -v] -i countername`.
86///
87#[cfg_attr(
88    feature = "lt2016_1",
89    doc = "The increment form: `p4 [g-opts] counter [-f] -i countername`."
90)]
91#[cfg_attr(
92    not(feature = "lt2016_1"),
93    doc = "The increment form: `p4 [g-opts] counter [-f -v] -i countername`."
94)]
95///
96/// Increments `countername` by one and returns the new value.
97#[cfg_attr(
98    feature = "lt2016_1",
99    doc = "The `B` type parameter only ever takes [`Unselected`]; `-v` is not available in this version."
100)]
101#[cfg_attr(
102    not(feature = "lt2016_1"),
103    doc = "The `B` type parameter tracks whether `-v` has been supplied: [`Unselected`] does not display the previous value; [`ShowPrevious`] does."
104)]
105#[derive(Debug, Clone, Default, PartialEq, Eq)]
106pub struct IncrementMode<B = Unselected> {
107    force: bool,
108    show_previous: B,
109}
110
111impl ExclusiveOption for IncrementMode<Unselected> {
112    fn inject_args(&self, command: &mut Command) {
113        if self.force {
114            command.arg("-f");
115        }
116        command.arg("-i");
117    }
118}
119
120#[cfg(not(feature = "lt2016_1"))]
121impl ExclusiveOption for IncrementMode<ShowPrevious> {
122    fn inject_args(&self, command: &mut Command) {
123        if self.force {
124            command.arg("-f");
125        }
126        command.arg("-v");
127        command.arg("-i");
128    }
129}
130
131/// The multi form: `p4 [g-opts] counter [-f] -m [pair list]`.
132///
133/// Performs a list of operations in a single invocation. To set a counter,
134/// use a name and value pair; to delete a counter, use a `-` (hyphen)
135/// followed by the name.
136#[derive(Debug, Clone, Default, PartialEq, Eq)]
137pub struct MultiMode {
138    force: bool,
139}
140
141impl ExclusiveOption for MultiMode {
142    fn inject_args(&self, command: &mut Command) {
143        if self.force {
144            command.arg("-f");
145        }
146        command.arg("-m");
147    }
148}
149
150/// The compare-and-set form: `p4 [g-opts] counter --from oldvalue --to
151/// newvalue countername`.
152///
153/// Sets `countername` to `newvalue` only if its current value is `oldvalue`.
154/// A counter that has never been set or that has been deleted cannot be set
155/// using this form.
156#[cfg(not(feature = "lt2016_1"))]
157#[derive(Debug, Clone, Default, PartialEq, Eq)]
158pub struct CASMode {
159    old_value: String,
160    new_value: String,
161}
162
163#[cfg(not(feature = "lt2016_1"))]
164impl ExclusiveOption for CASMode {
165    fn inject_args(&self, command: &mut Command) {
166        command
167            .arg("--from")
168            .arg(&self.old_value)
169            .arg("--to")
170            .arg(&self.new_value);
171    }
172}
173
174// ---------------------------------------------------------------------------
175// Command struct
176// ---------------------------------------------------------------------------
177
178/// Type-safe builder for `p4 counter`.
179///
180/// Access, set, increment, or delete a persistent variable.
181///
182/// Counters provide long-term variable storage for scripts. Querying a
183/// counter that does not exist returns zero; counter names are not stored in
184/// the database until set to a nonzero value. Deleting a counter has the same
185/// effect as setting it to zero.
186#[cfg_attr(
187    not(feature = "lt2016_1"),
188    doc = "The compare-and-set form can be used as a building block for higher-level tools and processes."
189)]
190///
191/// # Syntax
192///
193/// ```text
194/// p4 [g-opts] counter countername
195#[cfg_attr(
196    feature = "lt2016_1",
197    doc = "p4 [g-opts] counter [-f] countername value"
198)]
199#[cfg_attr(
200    not(feature = "lt2016_1"),
201    doc = "p4 [g-opts] counter [-f -v] countername value"
202)]
203/// p4 [g-opts] counter [-f] -d countername
204#[cfg_attr(feature = "lt2016_1", doc = "p4 [g-opts] counter [-f] -i countername")]
205#[cfg_attr(
206    not(feature = "lt2016_1"),
207    doc = "p4 [g-opts] counter [-f -v] -i countername"
208)]
209/// p4 [g-opts] counter [-f] -m [pair list]
210#[cfg_attr(
211    not(feature = "lt2016_1"),
212    doc = "p4 [g-opts] counter --from oldvalue --to newvalue countername"
213)]
214/// ```
215///
216/// The `M` type parameter tracks the command form at compile time, starting
217/// as [`Unselected`] from [`Counter::new`], which is the bare query form
218/// `p4 counter countername`: spawn it with the counter name to read the
219/// value. Enter another form with one of [`Self::set`], [`Self::force`],
220#[cfg_attr(
221    feature = "lt2016_1",
222    doc = "[`Self::delete`], [`Self::increment`], or [`Self::multi`]:"
223)]
224#[cfg_attr(
225    not(feature = "lt2016_1"),
226    doc = "[`Self::show_previous`], [`Self::delete`], [`Self::increment`], [`Self::multi`], or [`Self::cas`]:"
227)]
228#[cfg_attr(
229    feature = "lt2016_1",
230    doc = "- [`SetMode`] (entered via [`Self::set`] or [`Self::force`]): set or create the counter; can transition to [`DeleteMode`], [`IncrementMode`], or [`MultiMode`] preserving `-f`."
231)]
232#[cfg_attr(
233    not(feature = "lt2016_1"),
234    doc = "- [`SetMode`] (entered via [`Self::set`], [`Self::force`], or [`Self::show_previous`]): set or create the counter; can transition to [`DeleteMode`], [`IncrementMode`], or [`MultiMode`] preserving `-f`, and `Counter::show_previous` supplies `-v` by transitioning to the [`ShowPrevious`] state."
235)]
236/// - [`DeleteMode`] (`-d`, entered via [`Self::delete`]): delete the counter.
237/// - [`IncrementMode`] (`-i`, entered via [`Self::increment`]): increment the
238///   counter by one and return the new value.
239/// - [`MultiMode`] (`-m`, entered via [`Self::multi`]): perform a list of
240///   operations in a single invocation.
241#[cfg_attr(
242    not(feature = "lt2016_1"),
243    doc = "- [`CASMode`] (`--from oldvalue --to newvalue`, entered via [`Self::cas`]): set the counter only if its current value matches."
244)]
245///
246#[cfg_attr(
247    not(feature = "lt2016_1"),
248    doc = "`-v` cannot be combined with `-d` or `-m`: [`DeleteMode`] and [`MultiMode`] are only reachable from [`SetMode`] while it is in the [`Unselected`] state."
249)]
250#[derive(Debug, Clone, Default)]
251pub struct Counter<M = Unselected> {
252    bin: PathBuf,
253
254    global_opts: GlobalOpts,
255
256    mode: M,
257}
258
259// ---------------------------------------------------------------------------
260// Constructor
261// ---------------------------------------------------------------------------
262
263impl Counter<Unselected> {
264    /// Creates a new `p4 counter` command in the bare query form
265    /// `p4 counter countername`.
266    ///
267    /// `bin` is the path to the Perforce command-line executable. In this
268    /// state, spawn with the counter name via [`ParameterizedSpawn::spawn_with`]
269    /// to read its value; use one of the builder methods to select another
270    /// form.
271    pub fn new(bin: impl Into<PathBuf>, global_opts: GlobalOpts) -> Self {
272        Self {
273            bin: bin.into(),
274            global_opts,
275            ..Default::default()
276        }
277    }
278
279    /// Enters the set form: `p4 counter [-f -v] countername value`.
280    ///
281    /// Spawn the returned builder with the counter name and the value to
282    /// assign.
283    #[cfg_attr(feature = "lt2016_1", doc = "Use `Counter::force` to supply `-f`.")]
284    #[cfg_attr(
285        not(feature = "lt2016_1"),
286        doc = "Use `Counter::force` to supply `-f`, or `Counter::show_previous` to supply `-v`."
287    )]
288    pub fn set(self) -> Counter<SetMode<Unselected>> {
289        Counter {
290            bin: self.bin,
291            global_opts: self.global_opts,
292            mode: SetMode::default(),
293        }
294    }
295
296    /// Enters the set form with `-f` preset.
297    ///
298    /// `v` sets the initial state of the `-f` flag, which permits setting or
299    /// deleting counters reserved for use by P4 Server. Spawn the returned
300    /// builder with the counter name and the value to assign, or transition
301    /// to the delete or increment form.
302    pub fn force(self, v: bool) -> Counter<SetMode<Unselected>> {
303        Counter {
304            bin: self.bin,
305            global_opts: self.global_opts,
306            mode: SetMode {
307                force: v,
308                show_previous: Unselected,
309            },
310        }
311    }
312
313    /// Enters the set form with `-v` supplied, displaying the previous value
314    /// after the set.
315    ///
316    /// Spawn the returned builder with the counter name and the value to
317    /// assign, or transition to the increment form.
318    #[cfg(not(feature = "lt2016_1"))]
319    pub fn show_previous(self) -> Counter<SetMode<ShowPrevious>> {
320        Counter {
321            bin: self.bin,
322            global_opts: self.global_opts,
323            mode: SetMode {
324                force: false,
325                show_previous: ShowPrevious,
326            },
327        }
328    }
329
330    /// Enters the delete form: `p4 counter [-f] -d countername`.
331    ///
332    /// Spawn the returned builder with the counter name to delete.
333    pub fn delete(self) -> Counter<DeleteMode> {
334        Counter {
335            bin: self.bin,
336            global_opts: self.global_opts,
337            mode: DeleteMode::default(),
338        }
339    }
340
341    /// Enters the increment form: `p4 counter [-f -v] -i countername`.
342    ///
343    /// Spawn the returned builder with the counter name to increment.
344    pub fn increment(self) -> Counter<IncrementMode<Unselected>> {
345        Counter {
346            bin: self.bin,
347            global_opts: self.global_opts,
348            mode: IncrementMode::default(),
349        }
350    }
351
352    /// Enters the multi form: `p4 counter [-f] -m [pair list]`.
353    ///
354    /// Spawn the returned builder with the list of name/value pairs and
355    /// `-`-prefixed names to delete. Use `Counter::force` on the returned
356    /// builder to supply `-f`; transitioning from the set form preserves an
357    /// already selected `-f`.
358    pub fn multi(self) -> Counter<MultiMode> {
359        Counter {
360            bin: self.bin,
361            global_opts: self.global_opts,
362            mode: MultiMode::default(),
363        }
364    }
365
366    /// Enters the compare-and-set form: `p4 counter --from oldvalue --to
367    /// newvalue countername`.
368    ///
369    /// `old_value` is the value the counter must currently hold; `new_value`
370    /// is the value to assign when it matches. Spawn the returned builder
371    /// with the counter name.
372    #[cfg(not(feature = "lt2016_1"))]
373    pub fn cas(
374        self,
375        old_value: impl Into<String>,
376        new_value: impl Into<String>,
377    ) -> Counter<CASMode> {
378        Counter {
379            bin: self.bin,
380            global_opts: self.global_opts,
381            mode: CASMode {
382                old_value: old_value.into(),
383                new_value: new_value.into(),
384            },
385        }
386    }
387}
388
389// ---------------------------------------------------------------------------
390// Shared accessors (available in every mode)
391// ---------------------------------------------------------------------------
392
393impl<M> Counter<M> {
394    /// Get the Perforce command path.
395    pub fn get_bin(&self) -> &Path {
396        &self.bin
397    }
398
399    /// Set the Perforce command path.
400    pub fn set_bin(&mut self, bin: impl Into<PathBuf>) -> &mut Self {
401        self.bin = bin.into();
402        self
403    }
404
405    /// Set the Perforce command path.
406    pub fn bin(mut self, bin: impl Into<PathBuf>) -> Self {
407        self.set_bin(bin);
408        self
409    }
410
411    /// # Description
412    ///
413    /// g-opts
414    ///
415    #[cfg_attr(
416        feature = "lt2014_2",
417        doc = "See the [Global Options](GlobalOpts) section."
418    )]
419    #[cfg_attr(
420        all(feature = "lt2015_1", not(feature = "lt2014_2")),
421        doc = "See the [“Global Options”](GlobalOpts) section."
422    )]
423    #[cfg_attr(
424        all(feature = "lt2017_1", not(feature = "lt2015_1")),
425        doc = "See [“Global Options”](GlobalOpts)."
426    )]
427    #[cfg_attr(
428        all(feature = "lt2018_2", not(feature = "lt2017_1")),
429        doc = "See [Global Options](GlobalOpts)."
430    )]
431    #[cfg_attr(not(feature = "lt2018_2"), doc = "See [Global options](GlobalOpts).")]
432    pub fn get_global_opts(&self) -> &GlobalOpts {
433        &self.global_opts
434    }
435
436    /// # Description
437    ///
438    /// g-opts
439    ///
440    #[cfg_attr(
441        feature = "lt2014_2",
442        doc = "See the [Global Options](GlobalOpts) section."
443    )]
444    #[cfg_attr(
445        all(feature = "lt2015_1", not(feature = "lt2014_2")),
446        doc = "See the [“Global Options”](GlobalOpts) section."
447    )]
448    #[cfg_attr(
449        all(feature = "lt2017_1", not(feature = "lt2015_1")),
450        doc = "See [“Global Options”](GlobalOpts)."
451    )]
452    #[cfg_attr(
453        all(feature = "lt2018_2", not(feature = "lt2017_1")),
454        doc = "See [Global Options](GlobalOpts)."
455    )]
456    #[cfg_attr(not(feature = "lt2018_2"), doc = "See [Global options](GlobalOpts).")]
457    pub fn set_global_opts(&mut self, v: GlobalOpts) -> &mut Self {
458        self.global_opts = v;
459        self
460    }
461
462    /// # Description
463    ///
464    /// g-opts
465    ///
466    #[cfg_attr(
467        feature = "lt2014_2",
468        doc = "See the [Global Options](GlobalOpts) section."
469    )]
470    #[cfg_attr(
471        all(feature = "lt2015_1", not(feature = "lt2014_2")),
472        doc = "See the [“Global Options”](GlobalOpts) section."
473    )]
474    #[cfg_attr(
475        all(feature = "lt2017_1", not(feature = "lt2015_1")),
476        doc = "See [“Global Options”](GlobalOpts)."
477    )]
478    #[cfg_attr(
479        all(feature = "lt2018_2", not(feature = "lt2017_1")),
480        doc = "See [Global Options](GlobalOpts)."
481    )]
482    #[cfg_attr(not(feature = "lt2018_2"), doc = "See [Global options](GlobalOpts).")]
483    pub fn global_opts(mut self, v: GlobalOpts) -> Self {
484        self.global_opts = v;
485        self
486    }
487}
488
489// ---------------------------------------------------------------------------
490// SetMode<Unselected>: force accessor + transitions
491// ---------------------------------------------------------------------------
492
493impl Counter<SetMode<Unselected>> {
494    /// # Description
495    ///
496    /// -f
497    ///
498    /// Set or delete counters that are reserved for use by P4 Server (listed
499    /// in `p4 help counters`). Never set the change counter to a value that
500    /// is lower than its current value.
501    #[cfg_attr(
502        all(feature = "lt2021_2", not(feature = "lt2016_1")),
503        doc = "Only operators or super users can use this flag."
504    )]
505    pub fn get_force(&self) -> bool {
506        self.mode.force
507    }
508
509    /// # Description
510    ///
511    /// -f
512    ///
513    /// Set or delete counters that are reserved for use by P4 Server (listed
514    /// in `p4 help counters`). Never set the change counter to a value that
515    /// is lower than its current value.
516    #[cfg_attr(
517        all(feature = "lt2021_2", not(feature = "lt2016_1")),
518        doc = "Only operators or super users can use this flag."
519    )]
520    pub fn set_force(&mut self, v: bool) -> &mut Self {
521        self.mode.force = v;
522        self
523    }
524
525    /// # Description
526    ///
527    /// -f
528    ///
529    /// Set or delete counters that are reserved for use by P4 Server (listed
530    /// in `p4 help counters`). Never set the change counter to a value that
531    /// is lower than its current value.
532    #[cfg_attr(
533        all(feature = "lt2021_2", not(feature = "lt2016_1")),
534        doc = "Only operators or super users can use this flag."
535    )]
536    pub fn force(mut self, v: bool) -> Self {
537        self.mode.force = v;
538        self
539    }
540
541    /// # Description
542    ///
543    /// -v
544    ///
545    /// Display the previous value of the specified counter after the counter
546    /// has been set.
547    ///
548    /// Transitions this command to the [`ShowPrevious`] state, which also
549    /// permits transitioning to the increment form (`-v` is valid with `-i`
550    /// but not with `-d`).
551    #[cfg(not(feature = "lt2016_1"))]
552    pub fn show_previous(self) -> Counter<SetMode<ShowPrevious>> {
553        Counter {
554            bin: self.bin,
555            global_opts: self.global_opts,
556            mode: SetMode {
557                force: self.mode.force,
558                show_previous: ShowPrevious,
559            },
560        }
561    }
562
563    /// Transitions to the delete form (`-d`), preserving the `-f` flag.
564    ///
565    #[cfg_attr(
566        not(feature = "lt2016_1"),
567        doc = "This transition is unavailable from the [`ShowPrevious`] state because `-v` cannot be combined with `-d`."
568    )]
569    pub fn delete(self) -> Counter<DeleteMode> {
570        Counter {
571            bin: self.bin,
572            global_opts: self.global_opts,
573            mode: DeleteMode {
574                force: self.mode.force,
575            },
576        }
577    }
578
579    /// Transitions to the increment form (`-i`), preserving the `-f` flag.
580    pub fn increment(self) -> Counter<IncrementMode<Unselected>> {
581        Counter {
582            bin: self.bin,
583            global_opts: self.global_opts,
584            mode: IncrementMode {
585                force: self.mode.force,
586                show_previous: Unselected,
587            },
588        }
589    }
590
591    /// Transitions to the multi form (`-m`), preserving the `-f` flag.
592    ///
593    #[cfg_attr(
594        not(feature = "lt2016_1"),
595        doc = "This transition is unavailable from the [`ShowPrevious`] state because `-v` cannot be combined with `-m`."
596    )]
597    pub fn multi(self) -> Counter<MultiMode> {
598        Counter {
599            bin: self.bin,
600            global_opts: self.global_opts,
601            mode: MultiMode {
602                force: self.mode.force,
603            },
604        }
605    }
606}
607
608// ---------------------------------------------------------------------------
609// SetMode<ShowPrevious>: force accessor + transition
610// ---------------------------------------------------------------------------
611
612#[cfg(not(feature = "lt2016_1"))]
613impl Counter<SetMode<ShowPrevious>> {
614    /// # Description
615    ///
616    /// -f
617    ///
618    /// Set or delete counters that are reserved for use by P4 Server (listed
619    /// in `p4 help counters`). Never set the change counter to a value that
620    /// is lower than its current value.
621    #[cfg_attr(
622        all(feature = "lt2021_2", not(feature = "lt2016_1")),
623        doc = "Only operators or super users can use this flag."
624    )]
625    pub fn get_force(&self) -> bool {
626        self.mode.force
627    }
628
629    /// # Description
630    ///
631    /// -f
632    ///
633    /// Set or delete counters that are reserved for use by P4 Server (listed
634    /// in `p4 help counters`). Never set the change counter to a value that
635    /// is lower than its current value.
636    #[cfg_attr(
637        all(feature = "lt2021_2", not(feature = "lt2016_1")),
638        doc = "Only operators or super users can use this flag."
639    )]
640    pub fn set_force(&mut self, v: bool) -> &mut Self {
641        self.mode.force = v;
642        self
643    }
644
645    /// # Description
646    ///
647    /// -f
648    ///
649    /// Set or delete counters that are reserved for use by P4 Server (listed
650    /// in `p4 help counters`). Never set the change counter to a value that
651    /// is lower than its current value.
652    #[cfg_attr(
653        all(feature = "lt2021_2", not(feature = "lt2016_1")),
654        doc = "Only operators or super users can use this flag."
655    )]
656    pub fn force(mut self, v: bool) -> Self {
657        self.mode.force = v;
658        self
659    }
660
661    /// Transitions to the increment form (`-i`), preserving the `-f` and `-v`
662    /// flags.
663    pub fn increment(self) -> Counter<IncrementMode<ShowPrevious>> {
664        Counter {
665            bin: self.bin,
666            global_opts: self.global_opts,
667            mode: IncrementMode {
668                force: self.mode.force,
669                show_previous: ShowPrevious,
670            },
671        }
672    }
673}
674
675// ---------------------------------------------------------------------------
676// DeleteMode: force accessor
677// ---------------------------------------------------------------------------
678
679impl Counter<DeleteMode> {
680    /// # Description
681    ///
682    /// -f
683    ///
684    /// Set or delete counters that are reserved for use by P4 Server (listed
685    /// in `p4 help counters`). Never set the change counter to a value that
686    /// is lower than its current value.
687    #[cfg_attr(
688        all(feature = "lt2021_2", not(feature = "lt2016_1")),
689        doc = "Only operators or super users can use this flag."
690    )]
691    pub fn get_force(&self) -> bool {
692        self.mode.force
693    }
694
695    /// # Description
696    ///
697    /// -f
698    ///
699    /// Set or delete counters that are reserved for use by P4 Server (listed
700    /// in `p4 help counters`). Never set the change counter to a value that
701    /// is lower than its current value.
702    #[cfg_attr(
703        all(feature = "lt2021_2", not(feature = "lt2016_1")),
704        doc = "Only operators or super users can use this flag."
705    )]
706    pub fn set_force(&mut self, v: bool) -> &mut Self {
707        self.mode.force = v;
708        self
709    }
710
711    /// # Description
712    ///
713    /// -f
714    ///
715    /// Set or delete counters that are reserved for use by P4 Server (listed
716    /// in `p4 help counters`). Never set the change counter to a value that
717    /// is lower than its current value.
718    #[cfg_attr(
719        all(feature = "lt2021_2", not(feature = "lt2016_1")),
720        doc = "Only operators or super users can use this flag."
721    )]
722    pub fn force(mut self, v: bool) -> Self {
723        self.mode.force = v;
724        self
725    }
726}
727
728// ---------------------------------------------------------------------------
729// IncrementMode: force accessor
730// ---------------------------------------------------------------------------
731
732impl<B> Counter<IncrementMode<B>> {
733    /// # Description
734    ///
735    /// -f
736    ///
737    /// Set or delete counters that are reserved for use by P4 Server (listed
738    /// in `p4 help counters`). Never set the change counter to a value that
739    /// is lower than its current value.
740    #[cfg_attr(
741        all(feature = "lt2021_2", not(feature = "lt2016_1")),
742        doc = "Only operators or super users can use this flag."
743    )]
744    pub fn get_force(&self) -> bool {
745        self.mode.force
746    }
747
748    /// # Description
749    ///
750    /// -f
751    ///
752    /// Set or delete counters that are reserved for use by P4 Server (listed
753    /// in `p4 help counters`). Never set the change counter to a value that
754    /// is lower than its current value.
755    #[cfg_attr(
756        all(feature = "lt2021_2", not(feature = "lt2016_1")),
757        doc = "Only operators or super users can use this flag."
758    )]
759    pub fn set_force(&mut self, v: bool) -> &mut Self {
760        self.mode.force = v;
761        self
762    }
763
764    /// # Description
765    ///
766    /// -f
767    ///
768    /// Set or delete counters that are reserved for use by P4 Server (listed
769    /// in `p4 help counters`). Never set the change counter to a value that
770    /// is lower than its current value.
771    #[cfg_attr(
772        all(feature = "lt2021_2", not(feature = "lt2016_1")),
773        doc = "Only operators or super users can use this flag."
774    )]
775    pub fn force(mut self, v: bool) -> Self {
776        self.mode.force = v;
777        self
778    }
779}
780
781impl Counter<IncrementMode<Unselected>> {
782    /// # Description
783    ///
784    /// -v
785    ///
786    /// Display the previous value of the specified counter after the counter
787    /// has been incremented.
788    ///
789    /// Transitions this command to the [`ShowPrevious`] state.
790    #[cfg(not(feature = "lt2016_1"))]
791    pub fn show_previous(self) -> Counter<IncrementMode<ShowPrevious>> {
792        Counter {
793            bin: self.bin,
794            global_opts: self.global_opts,
795            mode: IncrementMode {
796                force: self.mode.force,
797                show_previous: ShowPrevious,
798            },
799        }
800    }
801}
802
803// ---------------------------------------------------------------------------
804// MultiMode: force accessor
805// ---------------------------------------------------------------------------
806
807impl Counter<MultiMode> {
808    /// # Description
809    ///
810    /// -f
811    ///
812    /// Set or delete counters that are reserved for use by P4 Server (listed
813    /// in `p4 help counters`). Never set the change counter to a value that
814    /// is lower than its current value.
815    #[cfg_attr(
816        all(feature = "lt2021_2", not(feature = "lt2016_1")),
817        doc = "Only operators or super users can use this flag."
818    )]
819    pub fn get_force(&self) -> bool {
820        self.mode.force
821    }
822
823    /// # Description
824    ///
825    /// -f
826    ///
827    /// Set or delete counters that are reserved for use by P4 Server (listed
828    /// in `p4 help counters`). Never set the change counter to a value that
829    /// is lower than its current value.
830    #[cfg_attr(
831        all(feature = "lt2021_2", not(feature = "lt2016_1")),
832        doc = "Only operators or super users can use this flag."
833    )]
834    pub fn set_force(&mut self, v: bool) -> &mut Self {
835        self.mode.force = v;
836        self
837    }
838
839    /// # Description
840    ///
841    /// -f
842    ///
843    /// Set or delete counters that are reserved for use by P4 Server (listed
844    /// in `p4 help counters`). Never set the change counter to a value that
845    /// is lower than its current value.
846    #[cfg_attr(
847        all(feature = "lt2021_2", not(feature = "lt2016_1")),
848        doc = "Only operators or super users can use this flag."
849    )]
850    pub fn force(mut self, v: bool) -> Self {
851        self.mode.force = v;
852        self
853    }
854}
855
856// ---------------------------------------------------------------------------
857// CASMode: old and new value accessors
858// ---------------------------------------------------------------------------
859
860#[cfg(not(feature = "lt2016_1"))]
861impl Counter<CASMode> {
862    /// # Description
863    ///
864    /// --from oldvalue
865    ///
866    /// The value the counter must currently hold for the new value to be
867    /// assigned.
868    pub fn get_old_value(&self) -> &str {
869        &self.mode.old_value
870    }
871
872    /// # Description
873    ///
874    /// --from oldvalue
875    ///
876    /// The value the counter must currently hold for the new value to be
877    /// assigned.
878    pub fn set_old_value(&mut self, v: impl Into<String>) -> &mut Self {
879        self.mode.old_value = v.into();
880        self
881    }
882
883    /// # Description
884    ///
885    /// --from oldvalue
886    ///
887    /// The value the counter must currently hold for the new value to be
888    /// assigned.
889    pub fn old_value(mut self, v: impl Into<String>) -> Self {
890        self.mode.old_value = v.into();
891        self
892    }
893
894    /// # Description
895    ///
896    /// --to newvalue
897    ///
898    /// The value to assign to the counter when its current value matches
899    /// `oldvalue`.
900    pub fn get_new_value(&self) -> &str {
901        &self.mode.new_value
902    }
903
904    /// # Description
905    ///
906    /// --to newvalue
907    ///
908    /// The value to assign to the counter when its current value matches
909    /// `oldvalue`.
910    pub fn set_new_value(&mut self, v: impl Into<String>) -> &mut Self {
911        self.mode.new_value = v.into();
912        self
913    }
914
915    /// # Description
916    ///
917    /// --to newvalue
918    ///
919    /// The value to assign to the counter when its current value matches
920    /// `oldvalue`.
921    pub fn new_value(mut self, v: impl Into<String>) -> Self {
922        self.mode.new_value = v.into();
923        self
924    }
925}
926
927// ---------------------------------------------------------------------------
928// SubCommand
929// ---------------------------------------------------------------------------
930
931impl<M: ExclusiveOption> SubCommand for Counter<M> {
932    fn name(&self) -> &str {
933        "counter"
934    }
935
936    fn inject_local_args(&self, command: &mut Command) {
937        self.mode.inject_args(command);
938    }
939
940    fn global_opts(&self) -> Option<&GlobalOpts> {
941        Some(&self.global_opts)
942    }
943}
944
945// ---------------------------------------------------------------------------
946// Spawning
947// ---------------------------------------------------------------------------
948
949// Query form: exactly 1 countername.
950impl<I: AsRef<OsStr>> ParameterizedSpawn<(I,)> for Counter<Unselected> {
951    type Output = Child;
952    type Error = std::io::Error;
953
954    /// Spawns `p4 counter countername` with the given counter name as a child
955    /// process with piped standard output and error streams; use the returned
956    /// [`Child`] handle to wait for it or interact with it.
957    fn spawn_with(&mut self, (countername,): (I,)) -> Result<Self::Output, Self::Error> {
958        self.setup_command(&self.bin)
959            .arg(countername)
960            .stdout(Stdio::piped())
961            .stderr(Stdio::piped())
962            .spawn()
963    }
964}
965
966// Set form: countername and value.
967impl<S, A, B> ParameterizedSpawn<(A, B)> for Counter<SetMode<S>>
968where
969    SetMode<S>: ExclusiveOption,
970    A: AsRef<OsStr>,
971    B: AsRef<OsStr>,
972{
973    type Output = Child;
974    type Error = std::io::Error;
975
976    /// Spawns `p4 counter [-f -v] countername value` with the given counter
977    /// name and value as a child process with piped standard output and error
978    /// streams; use the returned [`Child`] handle to wait for it or interact
979    /// with it.
980    fn spawn_with(&mut self, (countername, value): (A, B)) -> Result<Self::Output, Self::Error> {
981        self.setup_command(&self.bin)
982            .arg(countername)
983            .arg(value)
984            .stdout(Stdio::piped())
985            .stderr(Stdio::piped())
986            .spawn()
987    }
988}
989
990// Delete form: exactly 1 countername.
991impl<I: AsRef<OsStr>> ParameterizedSpawn<(I,)> for Counter<DeleteMode> {
992    type Output = Child;
993    type Error = std::io::Error;
994
995    /// Spawns `p4 counter [-f] -d countername` with the given counter name as
996    /// a child process with piped standard output and error streams; use the
997    /// returned [`Child`] handle to wait for it or interact with it.
998    fn spawn_with(&mut self, (countername,): (I,)) -> Result<Self::Output, Self::Error> {
999        self.setup_command(&self.bin)
1000            .arg(countername)
1001            .stdout(Stdio::piped())
1002            .stderr(Stdio::piped())
1003            .spawn()
1004    }
1005}
1006
1007// Increment form: exactly 1 countername.
1008impl<S, I> ParameterizedSpawn<(I,)> for Counter<IncrementMode<S>>
1009where
1010    IncrementMode<S>: ExclusiveOption,
1011    I: AsRef<OsStr>,
1012{
1013    type Output = Child;
1014    type Error = std::io::Error;
1015
1016    /// Spawns `p4 counter [-f -v] -i countername` with the given counter name
1017    /// as a child process with piped standard output and error streams; use
1018    /// the returned [`Child`] handle to wait for it or interact with it.
1019    fn spawn_with(&mut self, (countername,): (I,)) -> Result<Self::Output, Self::Error> {
1020        self.setup_command(&self.bin)
1021            .arg(countername)
1022            .stdout(Stdio::piped())
1023            .stderr(Stdio::piped())
1024            .spawn()
1025    }
1026}
1027
1028// Multi form: the pair list.
1029impl<S, I> ParameterizedSpawn<(S,)> for Counter<MultiMode>
1030where
1031    S: IntoIterator<Item = I>,
1032    I: AsRef<OsStr>,
1033{
1034    type Output = Child;
1035    type Error = std::io::Error;
1036
1037    /// Spawns `p4 counter [-f] -m` with the given pair list as a child
1038    /// process with piped standard output and error streams; use the returned
1039    /// [`Child`] handle to wait for it or interact with it.
1040    fn spawn_with(&mut self, (pairs,): (S,)) -> Result<Self::Output, Self::Error> {
1041        self.setup_command(&self.bin)
1042            .args(pairs)
1043            .stdout(Stdio::piped())
1044            .stderr(Stdio::piped())
1045            .spawn()
1046    }
1047}
1048
1049// Compare-and-set form: exactly 1 countername.
1050#[cfg(not(feature = "lt2016_1"))]
1051impl<I: AsRef<OsStr>> ParameterizedSpawn<(I,)> for Counter<CASMode> {
1052    type Output = Child;
1053    type Error = std::io::Error;
1054
1055    /// Spawns `p4 counter --from oldvalue --to newvalue countername` with the
1056    /// given counter name as a child process with piped standard output and
1057    /// error streams; use the returned [`Child`] handle to wait for it or
1058    /// interact with it.
1059    fn spawn_with(&mut self, (countername,): (I,)) -> Result<Self::Output, Self::Error> {
1060        self.setup_command(&self.bin)
1061            .arg(countername)
1062            .stdout(Stdio::piped())
1063            .stderr(Stdio::piped())
1064            .spawn()
1065    }
1066}
1067
1068#[cfg(test)]
1069mod tests {
1070    use super::*;
1071    use crate::cmd::args_of;
1072
1073    #[test]
1074    fn bin_accessors_update_executable_path() {
1075        let mut command = Counter::new("p4", GlobalOpts::new());
1076        assert_eq!(command.get_bin(), Path::new("p4"));
1077
1078        command.set_bin("/usr/local/bin/p4");
1079        assert_eq!(command.get_bin(), Path::new("/usr/local/bin/p4"));
1080
1081        let command = command.bin("p4.exe");
1082        assert_eq!(command.get_bin(), Path::new("p4.exe"));
1083    }
1084
1085    // Compile-time rejection: Counter<SetMode<ShowPrevious>> has no
1086    // `delete()` method (-v cannot be combined with -d).
1087    // Compile-time rejection: Counter<CASMode> and Counter<DeleteMode> have
1088    // no `force()`/`show_previous()` method.
1089
1090    /// Dry-run checks of the assembled `p4 counter` command line; no process
1091    /// is spawned.
1092    #[test]
1093    fn query_form_without_options() {
1094        let counter = Counter::new("p4", GlobalOpts::new());
1095        assert_eq!(args_of(&counter.setup_command("p4")), ["counter"]);
1096    }
1097
1098    #[test]
1099    fn set_form_from_unselected() {
1100        let counter = Counter::new("p4", GlobalOpts::new()).set();
1101        assert_eq!(args_of(&counter.setup_command("p4")), ["counter"]);
1102    }
1103
1104    #[test]
1105    fn set_form_with_force() {
1106        let counter = Counter::new("p4", GlobalOpts::new()).force(true);
1107        assert_eq!(args_of(&counter.setup_command("p4")), ["counter", "-f"]);
1108    }
1109
1110    #[cfg(not(feature = "lt2016_1"))]
1111    #[test]
1112    fn set_form_with_show_previous() {
1113        let counter = Counter::new("p4", GlobalOpts::new()).show_previous();
1114        assert_eq!(args_of(&counter.setup_command("p4")), ["counter", "-v"]);
1115    }
1116
1117    #[cfg(not(feature = "lt2016_1"))]
1118    #[test]
1119    fn set_form_with_force_and_show_previous() {
1120        let counter = Counter::new("p4", GlobalOpts::new())
1121            .set()
1122            .force(true)
1123            .show_previous();
1124        assert_eq!(
1125            args_of(&counter.setup_command("p4")),
1126            ["counter", "-f", "-v"]
1127        );
1128    }
1129
1130    #[test]
1131    fn delete_form_from_unselected() {
1132        let counter = Counter::new("p4", GlobalOpts::new()).delete();
1133        assert_eq!(args_of(&counter.setup_command("p4")), ["counter", "-d"]);
1134    }
1135
1136    #[test]
1137    fn delete_form_preserves_force_from_set() {
1138        let counter = Counter::new("p4", GlobalOpts::new()).force(true).delete();
1139        assert_eq!(
1140            args_of(&counter.setup_command("p4")),
1141            ["counter", "-f", "-d"]
1142        );
1143    }
1144
1145    #[test]
1146    fn delete_form_force_can_be_set_directly() {
1147        let counter = Counter::new("p4", GlobalOpts::new()).delete().force(true);
1148        assert_eq!(
1149            args_of(&counter.setup_command("p4")),
1150            ["counter", "-f", "-d"]
1151        );
1152    }
1153
1154    #[test]
1155    fn increment_form_from_unselected() {
1156        let counter = Counter::new("p4", GlobalOpts::new()).increment();
1157        assert_eq!(args_of(&counter.setup_command("p4")), ["counter", "-i"]);
1158    }
1159
1160    #[test]
1161    fn increment_form_preserves_force_from_set() {
1162        let counter = Counter::new("p4", GlobalOpts::new())
1163            .force(true)
1164            .increment();
1165        assert_eq!(
1166            args_of(&counter.setup_command("p4")),
1167            ["counter", "-f", "-i"]
1168        );
1169    }
1170
1171    #[cfg(not(feature = "lt2016_1"))]
1172    #[test]
1173    fn increment_form_preserves_force_and_show_previous() {
1174        let counter = Counter::new("p4", GlobalOpts::new())
1175            .show_previous()
1176            .force(true)
1177            .increment();
1178        assert_eq!(
1179            args_of(&counter.setup_command("p4")),
1180            ["counter", "-f", "-v", "-i"]
1181        );
1182    }
1183
1184    #[cfg(not(feature = "lt2016_1"))]
1185    #[test]
1186    fn increment_form_show_previous_can_be_set_directly() {
1187        let counter = Counter::new("p4", GlobalOpts::new())
1188            .increment()
1189            .show_previous();
1190        assert_eq!(
1191            args_of(&counter.setup_command("p4")),
1192            ["counter", "-v", "-i"]
1193        );
1194    }
1195
1196    #[test]
1197    fn multi_form_without_force() {
1198        let counter = Counter::new("p4", GlobalOpts::new()).multi();
1199        assert_eq!(args_of(&counter.setup_command("p4")), ["counter", "-m"]);
1200    }
1201
1202    #[test]
1203    fn multi_form_preserves_force_from_set() {
1204        let counter = Counter::new("p4", GlobalOpts::new()).force(true).multi();
1205        assert_eq!(
1206            args_of(&counter.setup_command("p4")),
1207            ["counter", "-f", "-m"]
1208        );
1209    }
1210
1211    #[test]
1212    fn multi_form_with_force() {
1213        let counter = Counter::new("p4", GlobalOpts::new()).multi().force(true);
1214        assert_eq!(
1215            args_of(&counter.setup_command("p4")),
1216            ["counter", "-f", "-m"]
1217        );
1218    }
1219
1220    #[cfg(not(feature = "lt2016_1"))]
1221    #[test]
1222    fn cas_form_injects_from_and_to_before_the_name() {
1223        let counter = Counter::new("p4", GlobalOpts::new()).cas("3", "4");
1224        assert_eq!(
1225            args_of(&counter.setup_command("p4")),
1226            ["counter", "--from", "3", "--to", "4"]
1227        );
1228    }
1229
1230    #[cfg(not(feature = "lt2016_1"))]
1231    #[test]
1232    fn cas_value_accessors_replace_values() {
1233        let mut counter = Counter::new("p4", GlobalOpts::new()).cas("3", "4");
1234        assert_eq!(counter.get_old_value(), "3");
1235        assert_eq!(counter.get_new_value(), "4");
1236
1237        counter.set_old_value("5").set_new_value("6");
1238        assert_eq!(
1239            args_of(&counter.setup_command("p4")),
1240            ["counter", "--from", "5", "--to", "6"]
1241        );
1242
1243        let counter = counter.old_value("7").new_value("8");
1244        assert_eq!(
1245            args_of(&counter.setup_command("p4")),
1246            ["counter", "--from", "7", "--to", "8"]
1247        );
1248    }
1249
1250    #[test]
1251    fn global_opts_are_injected_once() {
1252        let global_opts = GlobalOpts::new().port("localhost:1666").quiet_mode(true);
1253
1254        let counter = Counter::new("p4", global_opts.clone()).delete();
1255        assert_eq!(
1256            args_of(&counter.setup_command("p4")),
1257            ["-p", "localhost:1666", "-q", "counter", "-d"]
1258        );
1259
1260        let counter = Counter::new("p4", global_opts.clone()).multi().force(true);
1261        assert_eq!(
1262            args_of(&counter.setup_command("p4")),
1263            ["-p", "localhost:1666", "-q", "counter", "-f", "-m"]
1264        );
1265
1266        #[cfg(not(feature = "lt2016_1"))]
1267        let counter = Counter::new("p4", global_opts).cas("3", "4");
1268        #[cfg(not(feature = "lt2016_1"))]
1269        assert_eq!(
1270            args_of(&counter.setup_command("p4")),
1271            [
1272                "-p",
1273                "localhost:1666",
1274                "-q",
1275                "counter",
1276                "--from",
1277                "3",
1278                "--to",
1279                "4"
1280            ]
1281        );
1282    }
1283
1284    #[test]
1285    fn global_opts_accessors_replace_the_stored_options() {
1286        let mut counter = Counter::new("p4", GlobalOpts::new());
1287        counter.set_global_opts(GlobalOpts::new().port("localhost:1666"));
1288
1289        assert_eq!(
1290            args_of(&counter.setup_command("p4")),
1291            ["-p", "localhost:1666", "counter"]
1292        );
1293
1294        let counter = counter.global_opts(GlobalOpts::new().quiet_mode(true));
1295        assert_eq!(args_of(&counter.setup_command("p4")), ["-q", "counter"]);
1296    }
1297}