Skip to main content

perforce_cli/cmd/
export.rs

1use std::path::{Path, PathBuf};
2use std::process::{Child, Command, Stdio};
3
4use super::{ExclusiveOption, SubCommand, Unselected};
5
6use crate::global::GlobalOpts;
7use crate::spawn::ParameterizedSpawn;
8
9/// The `-f`/`-l` output-format state of `p4 export`.
10///
11/// Selected with the `format_non_text` (`-f`) or `limit` (`-l`) builder
12/// before choosing a checkpoint or journal. These options apply to both
13/// checkpoint and journal exports, but not to raw journal output (`-r`).
14#[derive(Debug, Clone, Copy, Default)]
15pub struct Format {
16    format_non_text: bool,
17
18    limit: Option<u64>,
19}
20
21/// The `-r` raw-journal state of `p4 export`.
22///
23/// Selected with the `raw_journal` builder. Raw output applies to journals
24/// only, so this state must be followed by a journal selection (`-j`) before
25/// the command can be spawned.
26#[derive(Debug, Clone, Copy, Default)]
27pub struct RawJournal;
28
29/// Checkpoint selection (`-c token`) of `p4 export`.
30///
31/// Wraps the output-format state `M` ([`Unselected`] or [`Format`]). Only
32/// commands in this state, or in the [`Journal`] state, can be spawned.
33#[derive(Debug, Clone, Default)]
34pub struct CheckPoint<M = Unselected> {
35    token: String,
36
37    mode: M,
38}
39
40/// Journal selection (`-j token`) of `p4 export`.
41///
42/// Wraps the output-format state `M` ([`Unselected`], [`Format`], or
43/// [`RawJournal`]). Only commands in this state, or in the [`CheckPoint`]
44/// state, can be spawned.
45#[derive(Debug, Clone, Default)]
46pub struct Journal<M = Unselected> {
47    token: String,
48
49    mode: M,
50}
51
52/// Type-safe builder for `p4 export`.
53///
54/// # Syntax
55///
56/// ```text
57/// p4 [g-opts] export -c token [-J prefix] [-f] [-l lines] [-F filter]
58/// [-T tableexcludelist] [-P filterpattern]
59///
60/// p4 [g-opts] export -j token [-J prefix] [-f] [-l lines] [-F filter]
61/// [-T tableexcludelist] [-P filterpattern]
62///
63/// p4 [g-opts] export -j token [-J prefix] -r [-F filter]
64/// [-T tableexcludelist] [-P filterpattern]
65/// ```
66///
67/// Extract journal or checkpoint records.
68///
69#[cfg_attr(
70    feature = "lt2017_1",
71    doc = "This command reports checkpoint and journal metadata from a Perforce server. With no options, the records are reported in tagged form."
72)]
73#[cfg_attr(
74    all(feature = "lt2017_2", not(feature = "lt2017_1")),
75    doc = "This command reports checkpoint and journal metadata from a Helix Core server. With no options, the records are reported in tagged form."
76)]
77#[cfg_attr(
78    all(feature = "lt2019_1", not(feature = "lt2017_2")),
79    doc = "This command reports checkpoint and journal metadata from a Helix Server server. With no options, the records are reported in tagged form."
80)]
81#[cfg_attr(
82    all(feature = "lt2021_1", not(feature = "lt2019_1")),
83    doc = "This command reports checkpoint and journal metadata from a Helix server server. With no options, the records are reported in tagged form."
84)]
85#[cfg_attr(
86    all(feature = "lt2024_1", not(feature = "lt2021_1")),
87    doc = "This command reports checkpoint and journal metadata from a Helix Server server. With no options, the records are reported in tagged form."
88)]
89#[cfg_attr(
90    all(feature = "lt2024_2", not(feature = "lt2024_1")),
91    doc = "This command reports checkpoint and journal metadata from a Helix Core Server server. With no options, the records are reported in tagged form."
92)]
93#[cfg_attr(
94    not(feature = "lt2024_2"),
95    doc = "This command reports checkpoint and journal metadata from a P4 Server server. With no options, the records are reported in tagged form."
96)]
97///
98/// Some fields are added to the tagged output to indicate either
99/// transactional consistency, or to indicate the end of the journal.
100///
101#[cfg_attr(
102    feature = "lt2014_2",
103    doc = "To filter database tables out of the exported data, use the `-T` flag with a list of tables whose data you wish to exclude. To exclude data from multiple tables, separate the table names by spaces or commas. The table names must begin with \"db.\", following the naming convention used for database files in the server root directory. If you separate the table exclusion list with spaces, you must enclose the list in quotes."
104)]
105#[cfg_attr(
106    not(feature = "lt2014_2"),
107    doc = "To filter database tables out of the exported data, use the `-T` option with a list of tables whose data you wish to exclude. To exclude data from multiple tables, separate the table names by spaces or commas. The table names must begin with \"db.\", following the naming convention used for database files in the server root directory. If you separate the table exclusion list with spaces, you must enclose the list in quotes."
108)]
109///
110#[cfg_attr(feature = "lt2024_1", doc = "# Usage Notes")]
111#[cfg_attr(not(feature = "lt2024_1"), doc = "# Usage notes")]
112///
113/// Can File Arguments Use Revision Specifier? N/A
114///
115/// Can File Arguments Use Revision Range? N/A
116///
117/// Minimal Access Level Required: `super`
118#[cfg_attr(not(feature = "lt2022_2"), doc = "available to an service user")]
119///
120/// Compressed journals or checkpoints are not supported.
121///
122/// The `M` type parameter tracks the option state at compile time.
123/// [`Unselected`] selects neither `-c` nor `-j`; `format_non_text` (`-f`) and
124/// `limit` (`-l`) enter the [`Format`] state, and `raw_journal` (`-r`)
125/// enters the [`RawJournal`] state. Only `checkpoint` (`-c`) and `journal`
126/// (`-j`) enter the [`CheckPoint`] and [`Journal`] states, which are the
127/// only states implementing [`ParameterizedSpawn`], so a partially
128/// configured command cannot be spawned.
129#[derive(Debug, Clone, Default)]
130pub struct Export<M = Unselected> {
131    bin: PathBuf,
132
133    global_opts: GlobalOpts,
134
135    prefix: Option<String>,
136
137    filter: Option<String>,
138
139    excluded_tables: Option<Vec<String>>,
140
141    filter_patterns: Option<Vec<String>>,
142
143    mode: M,
144}
145
146// ---------------------------------------------------------------------------
147// Mode selection
148// ---------------------------------------------------------------------------
149
150impl Export<Unselected> {
151    /// Creates a new `p4 export` command.
152    ///
153    /// `bin` is the path to the Perforce command-line executable. The
154    /// resulting command has neither `-c` nor `-j` selected and cannot be
155    /// spawned until a checkpoint or journal is selected.
156    pub fn new(bin: impl Into<PathBuf>, global_opts: GlobalOpts) -> Self {
157        Self {
158            bin: bin.into(),
159            global_opts,
160            prefix: None,
161            filter: None,
162            excluded_tables: None,
163            filter_patterns: None,
164            mode: Unselected,
165        }
166    }
167
168    /// # Description
169    ///
170    /// `-c token`
171    ///
172    /// Specifies a checkpoint number or position token of the form
173    /// `checkpointnum#byteoffset`.
174    ///
175    /// Transitions this command to the [`CheckPoint`] state, which spawns.
176    pub fn checkpoint(self, token: impl Into<String>) -> Export<CheckPoint<Unselected>> {
177        self.map_mode(|mode| CheckPoint {
178            token: token.into(),
179            mode,
180        })
181    }
182
183    /// # Description
184    ///
185    /// `-j token`
186    ///
187    /// Specify a journal number or position token of the form
188    /// `journalnum/byteoffset`.
189    ///
190    /// Transitions this command to the [`Journal`] state, which spawns.
191    pub fn journal(self, token: impl Into<String>) -> Export<Journal<Unselected>> {
192        self.map_mode(|mode| Journal {
193            token: token.into(),
194            mode,
195        })
196    }
197
198    /// # Description
199    ///
200    /// `-f`
201    ///
202    /// Format the output so that non-textual datatypes are formatted
203    /// appropriately.
204    ///
205    /// Transitions this command to the [`Format`] state; a checkpoint or
206    /// journal must still be selected before spawning.
207    pub fn format_non_text(self) -> Export<Format> {
208        self.with_mode(Format {
209            format_non_text: true,
210            limit: None,
211        })
212    }
213
214    /// # Description
215    ///
216    /// `-l lines`
217    ///
218    /// Limit output to the specified number of lines of journal records.
219    ///
220    /// Transitions this command to the [`Format`] state; a checkpoint or
221    /// journal must still be selected before spawning.
222    pub fn limit(self, lines: u64) -> Export<Format> {
223        self.with_mode(Format {
224            format_non_text: false,
225            limit: Some(lines),
226        })
227    }
228
229    /// # Description
230    ///
231    /// `-r`
232    ///
233    /// Display raw journal output; this argument applies to journals only.
234    ///
235    /// Transitions this command to the [`RawJournal`] state; a journal must
236    /// still be selected with `journal` (`-j`) before spawning.
237    pub fn raw_journal(self) -> Export<RawJournal> {
238        self.with_mode(RawJournal)
239    }
240}
241
242impl Export<Format> {
243    /// # Description
244    ///
245    /// `-f`
246    ///
247    /// Format the output so that non-textual datatypes are formatted
248    /// appropriately.
249    pub fn get_format_non_text(&self) -> bool {
250        self.mode.format_non_text
251    }
252
253    /// # Description
254    ///
255    /// `-f`
256    ///
257    /// Format the output so that non-textual datatypes are formatted
258    /// appropriately.
259    pub fn set_format_non_text(&mut self, v: bool) -> &mut Self {
260        self.mode.format_non_text = v;
261        self
262    }
263
264    /// # Description
265    ///
266    /// `-f`
267    ///
268    /// Format the output so that non-textual datatypes are formatted
269    /// appropriately.
270    pub fn format_non_text(mut self, v: bool) -> Self {
271        self.mode.format_non_text = v;
272        self
273    }
274
275    /// # Description
276    ///
277    /// `-l lines`
278    ///
279    /// Limit output to the specified number of lines of journal records.
280    pub fn get_limit(&self) -> Option<u64> {
281        self.mode.limit
282    }
283
284    /// # Description
285    ///
286    /// `-l lines`
287    ///
288    /// Limit output to the specified number of lines of journal records.
289    pub fn set_limit(&mut self, v: Option<u64>) -> &mut Self {
290        self.mode.limit = v;
291        self
292    }
293
294    /// # Description
295    ///
296    /// `-l lines`
297    ///
298    /// Limit output to the specified number of lines of journal records.
299    pub fn limit(mut self, v: u64) -> Self {
300        self.mode.limit = Some(v);
301        self
302    }
303
304    /// # Description
305    ///
306    /// `-c token`
307    ///
308    /// Specifies a checkpoint number or position token of the form
309    /// `checkpointnum#byteoffset`.
310    ///
311    /// Transitions this command to the [`CheckPoint`] state, which spawns.
312    pub fn checkpoint(self, token: impl Into<String>) -> Export<CheckPoint<Format>> {
313        self.map_mode(|mode| CheckPoint {
314            token: token.into(),
315            mode,
316        })
317    }
318
319    /// # Description
320    ///
321    /// `-j token`
322    ///
323    /// Specify a journal number or position token of the form
324    /// `journalnum/byteoffset`.
325    ///
326    /// Transitions this command to the [`Journal`] state, which spawns.
327    pub fn journal(self, token: impl Into<String>) -> Export<Journal<Format>> {
328        self.map_mode(|mode| Journal {
329            token: token.into(),
330            mode,
331        })
332    }
333}
334
335impl Export<RawJournal> {
336    /// # Description
337    ///
338    /// `-j token`
339    ///
340    /// Specify a journal number or position token of the form
341    /// `journalnum/byteoffset`.
342    ///
343    /// Transitions this command to the [`Journal`] state, which spawns.
344    pub fn journal(self, token: impl Into<String>) -> Export<Journal<RawJournal>> {
345        self.map_mode(|mode| Journal {
346            token: token.into(),
347            mode,
348        })
349    }
350}
351
352// ---------------------------------------------------------------------------
353// Common options, command path, and state helpers
354// ---------------------------------------------------------------------------
355
356impl<M> Export<M> {
357    fn with_mode<N>(self, mode: N) -> Export<N> {
358        Export {
359            bin: self.bin,
360            global_opts: self.global_opts,
361            prefix: self.prefix,
362            filter: self.filter,
363            excluded_tables: self.excluded_tables,
364            filter_patterns: self.filter_patterns,
365            mode,
366        }
367    }
368
369    fn map_mode<N>(self, f: impl FnOnce(M) -> N) -> Export<N> {
370        Export {
371            bin: self.bin,
372            global_opts: self.global_opts,
373            prefix: self.prefix,
374            filter: self.filter,
375            excluded_tables: self.excluded_tables,
376            filter_patterns: self.filter_patterns,
377            mode: f(self.mode),
378        }
379    }
380
381    /// Get the Perforce command path.
382    pub fn get_bin(&self) -> &Path {
383        &self.bin
384    }
385
386    /// Set the Perforce command path.
387    pub fn set_bin(&mut self, bin: impl Into<PathBuf>) -> &mut Self {
388        self.bin = bin.into();
389        self
390    }
391
392    /// Set the Perforce command path.
393    pub fn bin(mut self, bin: impl Into<PathBuf>) -> Self {
394        self.set_bin(bin);
395        self
396    }
397
398    /// # Description
399    ///
400    /// `-J prefix`
401    ///
402    /// Specifies a filename prefix for the journal, such as that used with
403    /// `p4d -jc prefix`.
404    pub fn get_prefix(&self) -> Option<&str> {
405        self.prefix.as_deref()
406    }
407
408    /// # Description
409    ///
410    /// `-J prefix`
411    ///
412    /// Specifies a filename prefix for the journal, such as that used with
413    /// `p4d -jc prefix`.
414    pub fn set_prefix(&mut self, v: impl Into<String>) -> &mut Self {
415        self.prefix = Some(v.into());
416        self
417    }
418
419    /// # Description
420    ///
421    /// `-J prefix`
422    ///
423    /// Specifies a filename prefix for the journal, such as that used with
424    /// `p4d -jc prefix`.
425    pub fn prefix(mut self, v: impl Into<String>) -> Self {
426        self.set_prefix(v);
427        self
428    }
429
430    /// # Description
431    ///
432    /// `-F filter`
433    ///
434    /// Limit output to records that match the specified filter pattern. For
435    /// example, `-F "table = db.configure"`.
436    pub fn get_filter(&self) -> Option<&str> {
437        self.filter.as_deref()
438    }
439
440    /// # Description
441    ///
442    /// `-F filter`
443    ///
444    /// Limit output to records that match the specified filter pattern. For
445    /// example, `-F "table = db.configure"`.
446    pub fn set_filter(&mut self, v: impl Into<String>) -> &mut Self {
447        self.filter = Some(v.into());
448        self
449    }
450
451    /// # Description
452    ///
453    /// `-F filter`
454    ///
455    /// Limit output to records that match the specified filter pattern. For
456    /// example, `-F "table = db.configure"`.
457    pub fn filter(mut self, v: impl Into<String>) -> Self {
458        self.set_filter(v);
459        self
460    }
461
462    /// # Description
463    ///
464    /// `-T tableexcludelist`
465    ///
466    /// Supply a list of database tables (for example, `db.have` and
467    /// `db.client`) to exclude from export. Limit output to records that
468    /// match the specified filter pattern. For example,
469    /// `-T db.have,db.client` or `-T "db.have db.client"`.
470    pub fn get_excluded_tables(&self) -> Option<&[String]> {
471        self.excluded_tables.as_deref()
472    }
473
474    /// # Description
475    ///
476    /// `-T tableexcludelist`
477    ///
478    /// Supply a list of database tables (for example, `db.have` and
479    /// `db.client`) to exclude from export. Limit output to records that
480    /// match the specified filter pattern. For example,
481    /// `-T db.have,db.client` or `-T "db.have db.client"`.
482    pub fn set_excluded_tables(&mut self, v: Vec<String>) -> &mut Self {
483        self.excluded_tables = Some(v);
484        self
485    }
486
487    /// # Description
488    ///
489    /// `-T tableexcludelist`
490    ///
491    /// Supply a list of database tables (for example, `db.have` and
492    /// `db.client`) to exclude from export. Limit output to records that
493    /// match the specified filter pattern. For example,
494    /// `-T db.have,db.client` or `-T "db.have db.client"`.
495    pub fn excluded_tables(mut self, v: Vec<String>) -> Self {
496        self.set_excluded_tables(v);
497        self
498    }
499
500    /// # Description
501    ///
502    /// `-P filterpattern`
503    ///
504    /// Limit output to records that match the specified filter pattern.
505    #[cfg_attr(
506        feature = "lt2014_2",
507        doc = "Multiple filter patterns can be specified with multiple `-P` flags."
508    )]
509    #[cfg_attr(
510        not(feature = "lt2014_2"),
511        doc = "Multiple filter patterns can be specified with multiple `-P` options."
512    )]
513    ///
514    /// Each `filterpattern` begins with two characters and a colon, and
515    /// specifies either a client filter or a depot filter, as well as whether
516    /// the pattern is to be included or excluded, using the syntax:
517    ///
518    /// ```text
519    /// -Pic://client/pattern - client records to include
520    /// -Pxc://client/pattern - client records to exclude
521    /// -Pif://depot/pattern - depot records to include
522    /// -Pxf://depot/pattern - depot records to exclude
523    /// ```
524    ///
525    /// The first character specifies whether the records are included or
526    /// excluded (`i` or `x`), the second character specifies whether the
527    /// records are client workspace-related or depot-file related (`c` or
528    /// `f`), the colon is a separator, and the remainder of the
529    /// `filterpattern` denotes either a client workspace view or a depot file
530    /// path.
531    #[cfg_attr(
532        feature = "lt2024_1",
533        doc = "The mechanism by which this filtering is implemented is the same as that which is used by the `ClientDataFilter:` and `RevisionDataFilter:` fields in the `p4 server` form."
534    )]
535    #[cfg_attr(
536        not(feature = "lt2024_1"),
537        doc = "The mechanism by which this filtering is implemented is the same as that which is used by the `ClientDataFilter:` and `RevisionDataFilter` fields in the `p4 server` form."
538    )]
539    pub fn get_filter_patterns(&self) -> Option<&[String]> {
540        self.filter_patterns.as_deref()
541    }
542
543    /// # Description
544    ///
545    /// `-P filterpattern`
546    ///
547    /// Limit output to records that match the specified filter pattern.
548    /// This option can be specified more than once; each call appends
549    /// another pattern.
550    ///
551    /// See `get_filter_patterns` for the pattern syntax.
552    pub fn set_filter_pattern(&mut self, v: impl Into<String>) -> &mut Self {
553        self.filter_patterns
554            .get_or_insert_with(Vec::new)
555            .push(v.into());
556        self
557    }
558
559    /// # Description
560    ///
561    /// `-P filterpattern`
562    ///
563    /// Limit output to records that match the specified filter pattern.
564    /// This option can be specified more than once; each call appends
565    /// another pattern.
566    ///
567    /// See `get_filter_patterns` for the pattern syntax.
568    pub fn filter_pattern(mut self, v: impl Into<String>) -> Self {
569        self.set_filter_pattern(v);
570        self
571    }
572}
573
574impl<M> Export<CheckPoint<M>> {
575    /// Get the checkpoint number or position token.
576    pub fn get_token(&self) -> &str {
577        &self.mode.token
578    }
579
580    /// Set the checkpoint number or position token.
581    pub fn set_token(&mut self, v: impl Into<String>) -> &mut Self {
582        self.mode.token = v.into();
583        self
584    }
585
586    /// Set the checkpoint number or position token.
587    pub fn token(mut self, v: impl Into<String>) -> Self {
588        self.set_token(v);
589        self
590    }
591}
592
593impl<M> Export<Journal<M>> {
594    /// Get the journal number or position token.
595    pub fn get_token(&self) -> &str {
596        &self.mode.token
597    }
598
599    /// Set the journal number or position token.
600    pub fn set_token(&mut self, v: impl Into<String>) -> &mut Self {
601        self.mode.token = v.into();
602        self
603    }
604
605    /// Set the journal number or position token.
606    pub fn token(mut self, v: impl Into<String>) -> Self {
607        self.set_token(v);
608        self
609    }
610}
611
612// ---------------------------------------------------------------------------
613// Argument injection
614// ---------------------------------------------------------------------------
615
616impl ExclusiveOption for Format {
617    fn inject_args(&self, command: &mut Command) {
618        if self.format_non_text {
619            command.arg("-f");
620        }
621
622        if let Some(lines) = self.limit {
623            command.arg("-l").arg(lines.to_string());
624        }
625    }
626}
627
628impl ExclusiveOption for RawJournal {
629    fn inject_args(&self, command: &mut Command) {
630        command.arg("-r");
631    }
632}
633
634impl<M: ExclusiveOption> ExclusiveOption for CheckPoint<M> {
635    fn inject_args(&self, command: &mut Command) {
636        command.arg("-c").arg(&self.token);
637        self.mode.inject_args(command);
638    }
639}
640
641impl<M: ExclusiveOption> ExclusiveOption for Journal<M> {
642    fn inject_args(&self, command: &mut Command) {
643        command.arg("-j").arg(&self.token);
644        self.mode.inject_args(command);
645    }
646}
647
648impl<M: ExclusiveOption> SubCommand for Export<M> {
649    fn name(&self) -> &str {
650        "export"
651    }
652
653    fn inject_local_args(&self, command: &mut Command) {
654        self.mode.inject_args(command);
655
656        if let Some(prefix) = &self.prefix {
657            command.arg("-J").arg(prefix);
658        }
659
660        if let Some(filter) = &self.filter {
661            command.arg("-F").arg(filter);
662        }
663
664        if let Some(tables) = &self.excluded_tables {
665            command.arg("-T").arg(tables.join(","));
666        }
667
668        if let Some(patterns) = &self.filter_patterns {
669            for pattern in patterns {
670                command.arg("-P").arg(pattern);
671            }
672        }
673    }
674
675    fn global_opts(&self) -> Option<&GlobalOpts> {
676        Some(&self.global_opts)
677    }
678}
679
680// ---------------------------------------------------------------------------
681// Spawning
682// ---------------------------------------------------------------------------
683
684impl<M: ExclusiveOption> ParameterizedSpawn<()> for Export<CheckPoint<M>> {
685    type Output = Child;
686    type Error = std::io::Error;
687
688    /// Spawns `p4 export -c token` as a child process with piped standard
689    /// output and error streams; use the returned [`Child`] handle to wait
690    /// for it or interact with it.
691    fn spawn_with(&mut self, (): ()) -> Result<Self::Output, Self::Error> {
692        self.setup_command(&self.bin)
693            .stdout(Stdio::piped())
694            .stderr(Stdio::piped())
695            .spawn()
696    }
697}
698
699impl<M: ExclusiveOption> ParameterizedSpawn<()> for Export<Journal<M>> {
700    type Output = Child;
701    type Error = std::io::Error;
702
703    /// Spawns `p4 export -j token` as a child process with piped standard
704    /// output and error streams; use the returned [`Child`] handle to wait
705    /// for it or interact with it.
706    fn spawn_with(&mut self, (): ()) -> Result<Self::Output, Self::Error> {
707        self.setup_command(&self.bin)
708            .stdout(Stdio::piped())
709            .stderr(Stdio::piped())
710            .spawn()
711    }
712}
713
714// ---------------------------------------------------------------------------
715// Global options
716// ---------------------------------------------------------------------------
717
718impl<M: ExclusiveOption> Export<M> {
719    /// # Description
720    ///
721    /// g-opts
722    ///
723    #[cfg_attr(
724        feature = "lt2014_2",
725        doc = "See the [Global Options](GlobalOpts) section."
726    )]
727    #[cfg_attr(
728        all(feature = "lt2015_1", not(feature = "lt2014_2")),
729        doc = "See the [“Global Options”](GlobalOpts) section."
730    )]
731    #[cfg_attr(
732        all(feature = "lt2017_1", not(feature = "lt2015_1")),
733        doc = "See [“Global Options”](GlobalOpts)."
734    )]
735    #[cfg_attr(
736        all(feature = "lt2018_2", not(feature = "lt2017_1")),
737        doc = "See [Global Options](GlobalOpts)."
738    )]
739    #[cfg_attr(not(feature = "lt2018_2"), doc = "See [Global options](GlobalOpts).")]
740    pub fn get_global_opts(&self) -> &GlobalOpts {
741        &self.global_opts
742    }
743
744    /// # Description
745    ///
746    /// g-opts
747    ///
748    #[cfg_attr(
749        feature = "lt2014_2",
750        doc = "See the [Global Options](GlobalOpts) section."
751    )]
752    #[cfg_attr(
753        all(feature = "lt2015_1", not(feature = "lt2014_2")),
754        doc = "See the [“Global Options”](GlobalOpts) section."
755    )]
756    #[cfg_attr(
757        all(feature = "lt2017_1", not(feature = "lt2015_1")),
758        doc = "See [“Global Options”](GlobalOpts)."
759    )]
760    #[cfg_attr(
761        all(feature = "lt2018_2", not(feature = "lt2017_1")),
762        doc = "See [Global Options](GlobalOpts)."
763    )]
764    #[cfg_attr(not(feature = "lt2018_2"), doc = "See [Global options](GlobalOpts).")]
765    pub fn set_global_opts(&mut self, v: GlobalOpts) -> &mut Self {
766        self.global_opts = v;
767        self
768    }
769
770    /// # Description
771    ///
772    /// g-opts
773    ///
774    #[cfg_attr(
775        feature = "lt2014_2",
776        doc = "See the [Global Options](GlobalOpts) section."
777    )]
778    #[cfg_attr(
779        all(feature = "lt2015_1", not(feature = "lt2014_2")),
780        doc = "See the [“Global Options”](GlobalOpts) section."
781    )]
782    #[cfg_attr(
783        all(feature = "lt2017_1", not(feature = "lt2015_1")),
784        doc = "See [“Global Options”](GlobalOpts)."
785    )]
786    #[cfg_attr(
787        all(feature = "lt2018_2", not(feature = "lt2017_1")),
788        doc = "See [Global Options](GlobalOpts)."
789    )]
790    #[cfg_attr(not(feature = "lt2018_2"), doc = "See [Global options](GlobalOpts).")]
791    pub fn global_opts(mut self, v: GlobalOpts) -> Self {
792        self.set_global_opts(v);
793        self
794    }
795}
796
797#[cfg(test)]
798mod tests {
799    use super::*;
800    use crate::cmd::args_of;
801
802    fn args(cmd: &impl SubCommand) -> Vec<String> {
803        args_of(&cmd.setup_command("p4"))
804    }
805
806    /// Dry-run checks of the assembled `p4 export` command line; no process
807    /// is spawned.
808    #[test]
809    fn without_selection_has_no_options() {
810        let cmd = Export::new("p4", GlobalOpts::new());
811
812        assert_eq!(args(&cmd), ["export"]);
813    }
814
815    #[test]
816    fn format_state_injects_flags_before_selection() {
817        assert_eq!(
818            args(&Export::new("p4", GlobalOpts::new()).format_non_text()),
819            ["export", "-f"]
820        );
821        assert_eq!(
822            args(&Export::new("p4", GlobalOpts::new()).limit(12)),
823            ["export", "-l", "12"]
824        );
825    }
826
827    #[test]
828    fn raw_journal_state_injects_flag_before_selection() {
829        assert_eq!(
830            args(&Export::new("p4", GlobalOpts::new()).raw_journal()),
831            ["export", "-r"]
832        );
833    }
834
835    #[test]
836    fn bare_checkpoint_and_journal() {
837        assert_eq!(
838            args(&Export::new("p4", GlobalOpts::new()).checkpoint("3")),
839            ["export", "-c", "3"]
840        );
841        assert_eq!(
842            args(&Export::new("p4", GlobalOpts::new()).journal("7")),
843            ["export", "-j", "7"]
844        );
845    }
846
847    #[test]
848    fn checkpoint_with_all_options() {
849        let cmd = Export::new("p4", GlobalOpts::new())
850            .prefix("backup")
851            .format_non_text()
852            .limit(10)
853            .filter("table = db.configure")
854            .excluded_tables(vec!["db.have".to_string(), "db.client".to_string()])
855            .filter_pattern("ic://client/depot/main")
856            .filter_pattern("xf://depot/secret")
857            .checkpoint("3");
858
859        assert_eq!(
860            args(&cmd),
861            [
862                "export",
863                "-c",
864                "3",
865                "-f",
866                "-l",
867                "10",
868                "-J",
869                "backup",
870                "-F",
871                "table = db.configure",
872                "-T",
873                "db.have,db.client",
874                "-P",
875                "ic://client/depot/main",
876                "-P",
877                "xf://depot/secret",
878            ]
879        );
880    }
881
882    #[test]
883    fn raw_journal_with_options() {
884        let cmd = Export::new("p4", GlobalOpts::new())
885            .prefix("backup")
886            .excluded_tables(vec!["db.have".to_string()])
887            .filter_pattern("if://depot/main")
888            .raw_journal()
889            .journal("7");
890
891        assert_eq!(
892            args(&cmd),
893            [
894                "export",
895                "-j",
896                "7",
897                "-r",
898                "-J",
899                "backup",
900                "-T",
901                "db.have",
902                "-P",
903                "if://depot/main",
904            ]
905        );
906    }
907
908    #[test]
909    fn global_opts_are_injected_once() {
910        let cmd = Export::new(
911            "p4",
912            GlobalOpts::new().port("localhost:1666").quiet_mode(true),
913        )
914        .journal("7");
915
916        assert_eq!(
917            args(&cmd),
918            ["-p", "localhost:1666", "-q", "export", "-j", "7"]
919        );
920    }
921
922    #[test]
923    fn token_accessors_update_selection() {
924        let mut cmd = Export::new("p4", GlobalOpts::new()).checkpoint("3");
925        assert_eq!(cmd.get_token(), "3");
926
927        cmd.set_token("12#4");
928        assert_eq!(cmd.get_token(), "12#4");
929        assert_eq!(args(&cmd), ["export", "-c", "12#4"]);
930
931        let cmd = cmd.token("5");
932        assert_eq!(args(&cmd), ["export", "-c", "5"]);
933    }
934
935    #[test]
936    fn format_accessors_update_options() {
937        let mut cmd = Export::new("p4", GlobalOpts::new()).format_non_text();
938        assert!(cmd.get_format_non_text());
939        assert_eq!(cmd.get_limit(), None);
940
941        cmd.set_format_non_text(false);
942        cmd.set_limit(Some(5));
943        assert!(!cmd.get_format_non_text());
944        assert_eq!(cmd.get_limit(), Some(5));
945        assert_eq!(args(&cmd), ["export", "-l", "5"]);
946
947        let cmd = cmd.limit(9).format_non_text(true);
948        assert_eq!(args(&cmd), ["export", "-f", "-l", "9"]);
949    }
950
951    #[test]
952    fn bin_accessors_update_executable_path() {
953        let mut cmd = Export::new("p4", GlobalOpts::new()).journal("7");
954        assert_eq!(cmd.get_bin(), Path::new("p4"));
955
956        cmd.set_bin("/usr/local/bin/p4");
957        assert_eq!(cmd.get_bin(), Path::new("/usr/local/bin/p4"));
958
959        let cmd = cmd.bin("p4.exe");
960        assert_eq!(cmd.get_bin(), Path::new("p4.exe"));
961    }
962}