Skip to main content

perforce_cli/
cmd.rs

1pub mod add;
2pub mod admin;
3#[cfg(not(feature = "lt2016_1"))]
4pub mod aliases;
5pub mod annotate;
6pub mod archive;
7pub mod attribute;
8#[cfg(not(feature = "lt2017_2"))]
9pub mod bgtask;
10pub mod branch;
11pub mod branches;
12pub mod cachepurge;
13pub mod change;
14pub mod changes;
15pub mod clean;
16pub mod client;
17pub mod clients;
18#[cfg(not(feature = "lt2015_1"))]
19pub mod clone;
20pub mod configure;
21pub mod copy;
22pub mod counter;
23pub mod counters;
24pub mod cstat;
25pub mod dbschema;
26pub mod dbstat;
27pub mod dbverify;
28pub mod delete;
29pub mod depot;
30pub mod depots;
31pub mod describe;
32#[cfg(not(feature = "lt2024_2"))]
33pub mod diagnostics;
34pub mod diff;
35pub mod diff2;
36pub mod dirs;
37pub mod diskspace;
38pub mod edit;
39pub mod export;
40#[cfg(not(feature = "lt2019_1"))]
41pub mod extension;
42pub mod filelog;
43pub mod print;
44pub mod sync;
45pub mod r#where;
46
47pub use add::Add;
48pub use admin::AdminEntry;
49#[cfg(not(feature = "lt2016_1"))]
50pub use aliases::Aliases;
51pub use annotate::Annotate;
52pub use archive::Archive;
53pub use attribute::Attribute;
54#[cfg(not(feature = "lt2017_2"))]
55pub use bgtask::BackGroundTask;
56pub use branch::Branch;
57pub use branches::Branches;
58pub use cachepurge::CachePurge;
59pub use change::Change;
60pub use changes::Changes;
61pub use clean::Clean;
62pub use client::Client;
63pub use clients::Clients;
64#[cfg(not(feature = "lt2015_1"))]
65pub use clone::Clone;
66pub use configure::Configure;
67pub use copy::Copy;
68pub use counter::Counter;
69pub use counters::Counters;
70pub use cstat::CStat;
71pub use dbschema::DBSchema;
72pub use dbstat::DBStat;
73pub use dbverify::DBVerify;
74pub use delete::Delete;
75pub use depot::Depot;
76#[cfg(not(feature = "lt2015_2"))]
77pub use depot::DepotType;
78pub use depots::Depots;
79pub use describe::Describe;
80#[cfg(not(feature = "lt2024_2"))]
81pub use diagnostics::Diagnostics;
82pub use diff::Diff;
83pub use diff::DisplayOptions;
84pub use diff2::Diff2;
85pub use dirs::Dirs;
86#[cfg(not(feature = "lt2022_2"))]
87pub use dirs::StreamView;
88pub use dirs::WorkspaceView;
89pub use diskspace::DiskSpace;
90pub use diskspace::P4Journal;
91pub use diskspace::P4Log;
92pub use diskspace::P4Root;
93pub use diskspace::Temp;
94pub use edit::Edit;
95pub use export::CheckPoint;
96pub use export::Export;
97pub use export::Format;
98pub use export::Journal;
99pub use export::RawJournal;
100#[cfg(not(feature = "lt2019_1"))]
101pub use extension::ExtensionEntry;
102pub use filelog::FileLog;
103pub use print::Print;
104pub use sync::Sync;
105pub use r#where::Where;
106
107use std::{ffi::OsStr, process::Command};
108
109use crate::global::GlobalOpts;
110
111/// Long output mode for changelist descriptions shared by commands such as
112/// `p4 changes` and `p4 filelog`.
113///
114/// By default, only the first 30 (or 31) characters of the description are
115/// shown.
116#[derive(Debug, Clone, Copy, PartialEq, Eq)]
117pub enum LongOutput {
118    /// Show the full text of each changelist description (`-l`).
119    Default,
120    /// Show the full text truncated at 250 characters (`-L`).
121    Truncated,
122}
123
124impl LongOutput {
125    /// Returns the command-line flag for this long output mode.
126    pub fn as_str(&self) -> &'static str {
127        match self {
128            LongOutput::Default => "-l",
129            LongOutput::Truncated => "-L",
130        }
131    }
132}
133
134/// Output format of the diff routine passed via `-doptions`.
135///
136/// This is one of two orthogonal dimensions of [`DiffOptions`] (the other
137/// being [`WhitespaceHandling`]). Exactly one format may be selected; the
138/// [`Default`](DiffFormat::Default) variant corresponds to no format flag.
139#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
140pub enum DiffFormat {
141    /// Default diff output format (no format flag).
142    #[default]
143    Default,
144    /// Context output format (`-dc[num]`), showing `num` lines of context
145    /// around the changes.
146    Context(Option<u32>),
147    /// RCS output format (`-dn`), showing additions and deletions with
148    /// associated line ranges.
149    Rcs,
150    /// Summary output format (`-ds`), showing only the number of chunks and
151    /// lines added, deleted, or changed.
152    Summary,
153    /// Unified output format (`-du[num]`), showing added and deleted lines
154    /// with `num` lines of context, in a form compatible with `patch(1)`.
155    Unified(Option<u32>),
156}
157
158/// Whitespace handling of the diff routine passed via `-doptions`.
159///
160/// This is one of two orthogonal dimensions of [`DiffOptions`] (the other
161/// being [`DiffFormat`]). The
162/// [`IgnoreChangesWithinWhitespace`](WhitespaceHandling::IgnoreChangesWithinWhitespace)
163/// and [`IgnoreAllWhitespace`](WhitespaceHandling::IgnoreAllWhitespace)
164/// variants each imply
165/// [`IgnoreLineEndings`](WhitespaceHandling::IgnoreLineEndings).
166#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
167pub enum WhitespaceHandling {
168    /// No whitespace handling.
169    #[default]
170    None,
171    /// Ignore line-ending (CR/LF) convention when finding diffs (`-dl`).
172    IgnoreLineEndings,
173    /// Ignore changes made within whitespace (`-db`); implies `-dl`.
174    IgnoreChangesWithinWhitespace,
175    /// Ignore whitespace altogether (`-dw`); implies `-dl`.
176    IgnoreAllWhitespace,
177}
178
179/// Diff routine options passed via `-doptions`, shared by commands such as
180/// `p4 diff`, `p4 diff2`, `p4 describe`, and `p4 annotate`.
181///
182/// The structured ([`Typed`](DiffOptions::Typed)) options split into two
183/// orthogonal dimensions — [`DiffFormat`] (output format) and
184/// [`WhitespaceHandling`] — each of which is internally mutually exclusive.
185/// All options are assembled with a [`DiffOptionsBuilder`], whose mode type
186/// parameter tracks at compile time whether structured or raw options are
187/// being built; both builder states convert into this type via [`From`], and
188/// command methods accept `impl Into<DiffOptions>` so a builder can be
189/// passed directly.
190///
191/// # Examples
192///
193/// ```
194/// use perforce_cli::cmd::{DiffOptions, DiffOptionsBuilder};
195///
196/// // `-dub`: unified format, ignore changes within whitespace
197/// let opts = DiffOptions::from(
198///     DiffOptionsBuilder::unified(None).ignore_changes_within_whitespace(),
199/// );
200///
201/// // `-dc3`: context format with 3 lines of context
202/// let opts = DiffOptions::from(DiffOptionsBuilder::context(Some(3)));
203///
204/// // `-d-C 25`: pass `-C 25` straight to an external diff program
205/// let opts = DiffOptions::from(DiffOptionsBuilder::raw("-C 25"));
206/// ```
207#[derive(Debug, Clone, PartialEq, Eq)]
208pub enum DiffOptions {
209    /// Structured diff options (the documented subset of the standard UNIX
210    /// diff flags).
211    Typed {
212        format: DiffFormat,
213        whitespace: WhitespaceHandling,
214    },
215    /// Raw option string passed directly to the underlying diff routine
216    /// (useful with an external diff program configured via `P4DIFF`).
217    Raw(String),
218}
219
220impl Default for DiffOptions {
221    fn default() -> Self {
222        DiffOptions::Typed {
223            format: DiffFormat::Default,
224            whitespace: WhitespaceHandling::None,
225        }
226    }
227}
228
229impl DiffOptions {
230    /// Returns the selected output format, or `None` if this is a
231    /// [`Raw`](DiffOptions::Raw) value.
232    pub fn format(&self) -> Option<DiffFormat> {
233        match self {
234            DiffOptions::Typed { format, .. } => Some(*format),
235            DiffOptions::Raw(_) => None,
236        }
237    }
238
239    /// Returns the selected whitespace handling, or `None` if this is a
240    /// [`Raw`](DiffOptions::Raw) value.
241    pub fn whitespace_handling(&self) -> Option<WhitespaceHandling> {
242        match self {
243            DiffOptions::Typed { whitespace, .. } => Some(*whitespace),
244            DiffOptions::Raw(_) => None,
245        }
246    }
247
248    /// Returns the raw option string, or `None` if this is a
249    /// [`Typed`](DiffOptions::Typed) value.
250    pub fn raw_str(&self) -> Option<&str> {
251        match self {
252            DiffOptions::Typed { .. } => None,
253            DiffOptions::Raw(s) => Some(s),
254        }
255    }
256
257    /// Injects the `-doptions` argument into `command`.
258    ///
259    /// If this is a [`Typed`](DiffOptions::Typed) value with both the format
260    /// and whitespace handling at their defaults, no `-d` argument is emitted.
261    pub fn inject_arg(&self, command: &mut Command) {
262        use DiffFormat::*;
263        use WhitespaceHandling::*;
264
265        let (format, whitespace) = match self {
266            DiffOptions::Typed { format, whitespace } => (*format, *whitespace),
267            DiffOptions::Raw(s) => {
268                command.arg(format!("-d{s}"));
269                return;
270            }
271        };
272
273        if matches!(format, Default) && matches!(whitespace, None) {
274            return;
275        }
276
277        let mut s = String::from("-d");
278
279        match format {
280            Default => {}
281            Context(num) => {
282                s.push('c');
283                if let Some(n) = num {
284                    s.push_str(&n.to_string());
285                }
286            }
287            Rcs => s.push('n'),
288            Summary => s.push('s'),
289            Unified(num) => {
290                s.push('u');
291                if let Some(n) = num {
292                    s.push_str(&n.to_string());
293                }
294            }
295        }
296
297        match whitespace {
298            None => {}
299            IgnoreLineEndings => s.push('l'),
300            IgnoreChangesWithinWhitespace => s.push('b'),
301            IgnoreAllWhitespace => s.push('w'),
302        }
303
304        command.arg(s);
305    }
306}
307
308impl From<String> for DiffOptions {
309    fn from(s: String) -> Self {
310        DiffOptions::Raw(s)
311    }
312}
313
314/// The structured ([`Typed`](DiffOptions::Typed)) state of a
315/// [`DiffOptionsBuilder`], holding the selected [`DiffFormat`] and
316/// [`WhitespaceHandling`].
317#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
318pub struct DiffOptionsTypedMode {
319    format: DiffFormat,
320    whitespace: WhitespaceHandling,
321}
322
323/// The raw ([`Raw`](DiffOptions::Raw)) state of a [`DiffOptionsBuilder`],
324/// holding the option string passed verbatim to the underlying diff routine.
325#[derive(Debug, Clone, PartialEq, Eq)]
326pub struct DiffOptionsRawMode {
327    raw: String,
328}
329
330/// Builder for [`DiffOptions`], shared by commands such as `p4 diff`,
331/// `p4 diff2`, `p4 describe`, and `p4 annotate`.
332///
333/// The mode type parameter tracks at compile time which kind of options are
334/// being assembled. The format constructors ([`DiffOptionsBuilder::context`],
335/// [`DiffOptionsBuilder::rcs`], [`DiffOptionsBuilder::summary`],
336/// [`DiffOptionsBuilder::unified`], and [`DiffOptionsBuilder::new`]) produce
337/// the [`DiffOptionsTypedMode`] state, where the whitespace builders
338/// ([`DiffOptionsBuilder::ignore_line_endings`],
339/// [`DiffOptionsBuilder::ignore_changes_within_whitespace`],
340/// [`DiffOptionsBuilder::ignore_all_whitespace`]) become available;
341/// [`DiffOptionsBuilder::raw`] produces the [`DiffOptionsRawMode`] state,
342/// which offers no further options — the two states never mix.
343///
344/// Both states convert into [`DiffOptions`] via [`From`], so command methods
345/// that accept `impl Into<DiffOptions>` take a builder directly.
346///
347/// # Examples
348///
349/// ```
350/// use perforce_cli::cmd::DiffOptionsBuilder;
351///
352/// // `-dub`: unified format, ignore changes within whitespace
353/// let builder =
354///     DiffOptionsBuilder::unified(None).ignore_changes_within_whitespace();
355///
356/// // `-dc3`: context format with 3 lines of context
357/// let builder = DiffOptionsBuilder::context(Some(3));
358///
359/// // `-d-C 25`: pass `-C 25` straight to an external diff program
360/// let builder = DiffOptionsBuilder::raw("-C 25");
361/// ```
362#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
363pub struct DiffOptionsBuilder<M> {
364    mode: M,
365}
366
367impl DiffOptionsBuilder<DiffOptionsTypedMode> {
368    /// Creates a new builder in the [`DiffOptionsTypedMode`] state with the
369    /// default format and no whitespace handling; the resulting
370    /// [`DiffOptions`] emits no `-d` flag.
371    pub fn new() -> Self {
372        Self {
373            mode: DiffOptionsTypedMode::default(),
374        }
375    }
376
377    /// `-dc[num]`: context output format with `num` lines of context.
378    pub fn context(num: Option<u32>) -> Self {
379        Self {
380            mode: DiffOptionsTypedMode {
381                format: DiffFormat::Context(num),
382                whitespace: WhitespaceHandling::None,
383            },
384        }
385    }
386
387    /// `-dn`: RCS output format.
388    pub fn rcs() -> Self {
389        Self {
390            mode: DiffOptionsTypedMode {
391                format: DiffFormat::Rcs,
392                whitespace: WhitespaceHandling::None,
393            },
394        }
395    }
396
397    /// `-ds`: summary output format.
398    pub fn summary() -> Self {
399        Self {
400            mode: DiffOptionsTypedMode {
401                format: DiffFormat::Summary,
402                whitespace: WhitespaceHandling::None,
403            },
404        }
405    }
406
407    /// `-du[num]`: unified output format with `num` lines of context.
408    pub fn unified(num: Option<u32>) -> Self {
409        Self {
410            mode: DiffOptionsTypedMode {
411                format: DiffFormat::Unified(num),
412                whitespace: WhitespaceHandling::None,
413            },
414        }
415    }
416
417    /// `-dl`: ignore line-ending (CR/LF) convention when finding diffs.
418    pub fn ignore_line_endings(mut self) -> Self {
419        self.mode.whitespace = WhitespaceHandling::IgnoreLineEndings;
420        self
421    }
422
423    /// `-db`: ignore changes made within whitespace (implies `-dl`).
424    pub fn ignore_changes_within_whitespace(mut self) -> Self {
425        self.mode.whitespace = WhitespaceHandling::IgnoreChangesWithinWhitespace;
426        self
427    }
428
429    /// `-dw`: ignore whitespace altogether (implies `-dl`).
430    pub fn ignore_all_whitespace(mut self) -> Self {
431        self.mode.whitespace = WhitespaceHandling::IgnoreAllWhitespace;
432        self
433    }
434}
435
436impl DiffOptionsBuilder<DiffOptionsRawMode> {
437    /// Passes an arbitrary option string directly to the underlying diff
438    /// routine (for use with an external diff program).
439    ///
440    /// The string is appended to `-d` verbatim. For example,
441    /// `DiffOptionsBuilder::raw("-C 25")` produces `-d-C 25`.
442    pub fn raw(s: impl Into<String>) -> Self {
443        Self {
444            mode: DiffOptionsRawMode { raw: s.into() },
445        }
446    }
447}
448
449impl From<DiffOptionsBuilder<DiffOptionsTypedMode>> for DiffOptions {
450    fn from(builder: DiffOptionsBuilder<DiffOptionsTypedMode>) -> Self {
451        DiffOptions::Typed {
452            format: builder.mode.format,
453            whitespace: builder.mode.whitespace,
454        }
455    }
456}
457
458impl From<DiffOptionsBuilder<DiffOptionsRawMode>> for DiffOptions {
459    fn from(builder: DiffOptionsBuilder<DiffOptionsRawMode>) -> Self {
460        DiffOptions::Raw(builder.mode.raw)
461    }
462}
463
464/// The default "no option selected" variant, shared by every
465/// [`ExclusiveOption`] group.
466///
467/// It is a zero-sized type whose [`ExclusiveOption::inject_args`] is a no-op,
468/// so any mutually exclusive option group can use it as its default type
469/// parameter instead of defining its own empty variant.
470#[derive(Debug, Clone, Copy, Default)]
471pub struct Unselected;
472
473impl ExclusiveOption for Unselected {
474    fn inject_args(&self, _: &mut Command) {}
475}
476
477/// Marker trait for a mutually exclusive option group.
478///
479/// Some Perforce commands accept a set of options where only one may be
480/// selected at a time (for example `p4 admin checkpoint [-z | -Z]` or
481/// `p4 admin updatespecdepot [-a | -s type]`). Each variant of such a group
482/// implements this trait to inject its own CLI arguments; the selected
483/// variant is encoded in a type parameter so that the alternatives are
484/// unavailable at compile time.
485///
486/// Variants may carry their own data (for example the `type` argument of
487/// `-s type`) and inject any number of arguments, keeping the trait open to
488/// option groups more complex than a single flag.
489pub trait ExclusiveOption {
490    #[allow(unused_variables)]
491    /// Inject the CLI arguments corresponding to this selection into
492    /// `command`.
493    fn inject_args(&self, command: &mut Command) {}
494}
495
496pub trait SubCommand {
497    fn name(&self) -> &str;
498
499    fn inject_local_args(&self, command: &mut Command);
500
501    fn global_opts(&self) -> Option<&GlobalOpts> {
502        None
503    }
504
505    fn inject_args(&self, command: &mut Command) {
506        // inject global opts
507        if let Some(global_opts) = self.global_opts() {
508            global_opts.setup_args(command);
509        };
510        // inject local opts
511        self.inject_local_args(command.arg(self.name()));
512    }
513
514    fn setup_command<S: AsRef<OsStr>>(&self, bin: S) -> Command {
515        let mut cmd = Command::new(bin);
516
517        self.inject_args(&mut cmd);
518        cmd
519    }
520}
521
522/// Test-only helper: collects the arguments assembled on a [`Command`] as
523/// strings for easy comparison.
524#[cfg(test)]
525pub(crate) fn args_of(command: &Command) -> Vec<String> {
526    command
527        .get_args()
528        .map(|arg| arg.to_string_lossy().into_owned())
529        .collect()
530}
531
532#[cfg(test)]
533mod diff_options_tests {
534    use super::*;
535
536    fn injected(opts: impl Into<DiffOptions>) -> Vec<String> {
537        let mut cmd = Command::new("p4");
538        opts.into().inject_arg(&mut cmd);
539        args_of(&cmd)
540    }
541
542    #[test]
543    fn default_emits_nothing() {
544        assert!(injected(DiffOptionsBuilder::new()).is_empty());
545        assert!(injected(DiffOptions::default()).is_empty());
546    }
547
548    #[test]
549    fn unified_format() {
550        assert_eq!(injected(DiffOptionsBuilder::unified(None)), ["-du"]);
551    }
552
553    #[test]
554    fn unified_format_with_context() {
555        assert_eq!(injected(DiffOptionsBuilder::unified(Some(3))), ["-du3"]);
556    }
557
558    #[test]
559    fn context_format() {
560        assert_eq!(injected(DiffOptionsBuilder::context(None)), ["-dc"]);
561        assert_eq!(injected(DiffOptionsBuilder::context(Some(5))), ["-dc5"]);
562    }
563
564    #[test]
565    fn rcs_format() {
566        assert_eq!(injected(DiffOptionsBuilder::rcs()), ["-dn"]);
567    }
568
569    #[test]
570    fn summary_format() {
571        assert_eq!(injected(DiffOptionsBuilder::summary()), ["-ds"]);
572    }
573
574    #[test]
575    fn whitespace_only() {
576        assert_eq!(
577            injected(DiffOptionsBuilder::new().ignore_line_endings()),
578            ["-dl"]
579        );
580    }
581
582    #[test]
583    fn unified_with_ignore_changes_within_whitespace() {
584        assert_eq!(
585            injected(DiffOptionsBuilder::unified(None).ignore_changes_within_whitespace()),
586            ["-dub"]
587        );
588    }
589
590    #[test]
591    fn context_with_ignore_all_whitespace() {
592        assert_eq!(
593            injected(DiffOptionsBuilder::context(Some(2)).ignore_all_whitespace()),
594            ["-dc2w"]
595        );
596    }
597
598    #[test]
599    fn raw_passthrough() {
600        assert_eq!(injected(DiffOptionsBuilder::raw("-C 25")), ["-d-C 25"]);
601        assert_eq!(injected(DiffOptionsBuilder::raw("--brief")), ["-d--brief"]);
602    }
603
604    #[test]
605    fn getters_reflect_variant() {
606        let typed = DiffOptions::from(DiffOptionsBuilder::unified(Some(3)).ignore_line_endings());
607        assert_eq!(typed.format(), Some(DiffFormat::Unified(Some(3))));
608        assert_eq!(
609            typed.whitespace_handling(),
610            Some(WhitespaceHandling::IgnoreLineEndings)
611        );
612        assert_eq!(typed.raw_str(), None);
613
614        let raw = DiffOptions::from(DiffOptionsBuilder::raw("abc"));
615        assert_eq!(raw.format(), None);
616        assert_eq!(raw.whitespace_handling(), None);
617        assert_eq!(raw.raw_str(), Some("abc"));
618    }
619}