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