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