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