Skip to main content

perforce_cli/cmd/
clone.rs

1use std::path::{Path, PathBuf};
2use std::process::{Child, Command, Stdio};
3
4use super::{ExclusiveOption, SubCommand, Unselected};
5
6use crate::spawn::ParameterizedSpawn;
7
8// ---------------------------------------------------------------------------
9// Clone target: `-r remotespec` vs `-f filespec`
10// ---------------------------------------------------------------------------
11
12/// The `-r remotespec` target state: use the remote spec named `remotespec`,
13/// installed on the remote server, as a template for the clone and stream
14/// setup.
15///
16/// Entered with [`Clone::remote`]; mutually exclusive with
17/// [`FileSpecMode`].
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct RemoteSpecMode {
20    source: String,
21}
22
23/// The `-f filespec` target state: use the *filespec* in the remote server as
24/// the path to clone.
25///
26/// Entered with [`Clone::file`]; mutually exclusive with
27/// [`RemoteSpecMode`].
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct FileSpecMode {
30    source: String,
31}
32
33impl ExclusiveOption for RemoteSpecMode {
34    fn inject_args(&self, command: &mut Command) {
35        command.arg("-r").arg(&self.source);
36    }
37}
38
39impl ExclusiveOption for FileSpecMode {
40    fn inject_args(&self, command: &mut Command) {
41        command.arg("-f").arg(&self.source);
42    }
43}
44
45/// Marker for a selected clone target: either [`RemoteSpecMode`] (`-r`) or
46/// [`FileSpecMode`] (`-f`).
47///
48/// Exactly one of `-r` / `-f` is required, so the command can only be
49/// assembled and spawned once [`struct@Clone`] has transitioned into one of these
50/// states.
51pub trait CloneTarget: ExclusiveOption {}
52
53impl CloneTarget for RemoteSpecMode {}
54impl CloneTarget for FileSpecMode {}
55
56// ---------------------------------------------------------------------------
57// Remote port: `-p port`
58// ---------------------------------------------------------------------------
59
60/// The `-p port` state: the address (`P4PORT`) of the remote server to clone
61/// from, modelled as an ordinary option because `p4 clone` does not accept
62/// the global options.
63///
64/// Entered with [`Clone::port`].
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct Port {
67    port: String,
68}
69
70// ---------------------------------------------------------------------------
71// Command struct
72// ---------------------------------------------------------------------------
73
74/// Type-safe builder for `p4 clone`.
75///
76#[cfg_attr(
77    feature = "lt2017_1",
78    doc = "Clone a new local Perforce server from a remote server."
79)]
80#[cfg_attr(
81    all(feature = "lt2017_2", not(feature = "lt2017_1")),
82    doc = "Clone a new local Helix Core server from a remote server."
83)]
84#[cfg_attr(
85    all(feature = "lt2019_1", not(feature = "lt2017_2")),
86    doc = "Clone a new local Helix Server from a remote server."
87)]
88#[cfg_attr(
89    all(feature = "lt2021_1", not(feature = "lt2019_1")),
90    doc = "Clone a new local Helix server from a remote server."
91)]
92#[cfg_attr(
93    all(feature = "lt2024_1", not(feature = "lt2021_1")),
94    doc = "Clone a new local Helix Server from a remote server."
95)]
96#[cfg_attr(
97    all(feature = "lt2024_2", not(feature = "lt2024_1")),
98    doc = "Clone a new local Helix Core Server from a remote server."
99)]
100#[cfg_attr(
101    not(feature = "lt2024_2"),
102    doc = "Clone a new local P4 Server from a remote server."
103)]
104///
105/// When you clone from a remote server, you copy the portion of its contents
106/// that you want to work with into your local server.
107///
108/// Unlike most commands, `p4 clone` does not accept the full set of global
109/// options: only `-u user`, `-d dir`, and `-c client` are recognized before
110/// the subcommand, so they are modelled as ordinary options here rather than
111/// through [`GlobalOpts`](crate::global::GlobalOpts).
112///
113/// # Syntax
114///
115/// ```text
116/// p4 [-u user] [-d dir] [-c client] clone [-m depth] [-v] -p port -r remote
117/// p4 [-u user] [-d dir] [-c client] clone [-m depth] [-v] -p port -f filespec
118/// ```
119///
120/// The `P` type parameter tracks the remote port (`-p`) at compile time and
121/// the `M` type parameter tracks the clone target (`-r` / `-f`); both start
122/// as [`Unselected`], in which the command cannot be assembled. Select a port
123/// with [`Self::port`] and exactly one target with [`Self::remote`] or
124/// [`Self::file`] before assembling the command.
125#[derive(Debug, Clone)]
126pub struct Clone<P = Unselected, M = Unselected> {
127    bin: PathBuf,
128
129    /// `-u user`
130    user: Option<String>,
131
132    /// `-d dir`
133    dir: Option<PathBuf>,
134
135    /// `-c client`
136    client: Option<String>,
137
138    /// `-m depth`
139    depth: Option<u64>,
140
141    /// `-v`
142    verbose: bool,
143
144    port: P,
145
146    mode: M,
147}
148
149// ---------------------------------------------------------------------------
150// Construction
151// ---------------------------------------------------------------------------
152
153impl Clone<Unselected, Unselected> {
154    /// Creates a new `p4 clone` command with no remote port and no clone
155    /// target selected.
156    ///
157    /// `bin` is the path to the Perforce command-line executable. The command
158    /// cannot be assembled in this state; select a remote port with
159    /// [`Self::port`] (`-p`) and exactly one target with
160    /// [`Self::remote`] (`-r`) or [`Self::file`] (`-f`) first.
161    pub fn new(bin: impl Into<PathBuf>) -> Self {
162        Self {
163            bin: bin.into(),
164            user: None,
165            dir: None,
166            client: None,
167            depth: None,
168            verbose: false,
169            port: Unselected,
170            mode: Unselected,
171        }
172    }
173}
174
175// ---------------------------------------------------------------------------
176// Common options: available in every state
177// ---------------------------------------------------------------------------
178
179impl<P, M> Clone<P, M> {
180    /// Returns the path to the Perforce command-line executable.
181    pub fn get_bin(&self) -> &Path {
182        self.bin.as_path()
183    }
184
185    /// Sets the path to the Perforce command-line executable.
186    pub fn set_bin(&mut self, bin: impl Into<PathBuf>) -> &mut Self {
187        self.bin = bin.into();
188        self
189    }
190
191    /// Sets the path to the Perforce command-line executable.
192    pub fn bin(mut self, bin: impl Into<PathBuf>) -> Self {
193        self.bin = bin.into();
194        self
195    }
196
197    /// Returns the value of `-u user`, if set.
198    ///
199    /// This is one of the few options that `p4 clone` recognizes *before* the
200    /// subcommand, in place of the full set of global options.
201    pub fn get_user(&self) -> Option<&str> {
202        self.user.as_deref()
203    }
204
205    /// Sets the value of `-u user`.
206    pub fn set_user(&mut self, v: impl Into<String>) -> &mut Self {
207        self.user = Some(v.into());
208        self
209    }
210
211    /// Sets `-u user`.
212    ///
213    /// # Description
214    ///
215    /// -u user
216    ///
217    #[cfg_attr(feature = "lt2017_2", doc = "Specifies the Perforce user.")]
218    #[cfg_attr(
219        all(feature = "lt2019_1", not(feature = "lt2017_2")),
220        doc = "Specifies the Helix Server user."
221    )]
222    #[cfg_attr(
223        all(feature = "lt2021_1", not(feature = "lt2019_1")),
224        doc = "Specifies the Helix server user."
225    )]
226    #[cfg_attr(
227        all(feature = "lt2024_1", not(feature = "lt2021_1")),
228        doc = "Specifies the Helix Server user."
229    )]
230    #[cfg_attr(
231        all(feature = "lt2024_2", not(feature = "lt2024_1")),
232        doc = "Specifies the Helix Core Server user."
233    )]
234    #[cfg_attr(not(feature = "lt2024_2"), doc = "Specifies the P4 Server user.")]
235    pub fn user(mut self, v: impl Into<String>) -> Self {
236        self.user = Some(v.into());
237        self
238    }
239
240    /// Returns the value of `-d dir`, if set.
241    ///
242    /// This is one of the few options that `p4 clone` recognizes *before* the
243    /// subcommand, in place of the full set of global options.
244    pub fn get_dir(&self) -> Option<&Path> {
245        self.dir.as_deref()
246    }
247
248    /// Sets the value of `-d dir`.
249    pub fn set_dir(&mut self, v: impl Into<PathBuf>) -> &mut Self {
250        self.dir = Some(v.into());
251        self
252    }
253
254    /// Sets `-d dir`.
255    ///
256    /// # Description
257    ///
258    /// -d dir
259    ///
260    #[cfg_attr(
261        feature = "lt2017_1",
262        doc = "Specifies the directory in which the new Perforce server is initialized. If not specified, defaults to the current directory."
263    )]
264    #[cfg_attr(
265        all(feature = "lt2017_2", not(feature = "lt2017_1")),
266        doc = "Specifies the directory in which the new Helix Core server is initialized. If not specified, defaults to the current directory."
267    )]
268    #[cfg_attr(
269        all(feature = "lt2019_1", not(feature = "lt2017_2")),
270        doc = "Specifies the directory in which the new Helix Server is initialized. If not specified, defaults to the current directory."
271    )]
272    #[cfg_attr(
273        all(feature = "lt2021_1", not(feature = "lt2019_1")),
274        doc = "Specifies the directory in which the new Helix server is initialized. If not specified, defaults to the current directory."
275    )]
276    #[cfg_attr(
277        all(feature = "lt2024_1", not(feature = "lt2021_1")),
278        doc = "Specifies the directory in which the new Helix Server is initialized. If not specified, defaults to the current directory."
279    )]
280    #[cfg_attr(
281        all(feature = "lt2024_2", not(feature = "lt2024_1")),
282        doc = "Specifies the directory in which the new Helix Core Server is initialized. If not specified, defaults to the current directory."
283    )]
284    #[cfg_attr(
285        not(feature = "lt2024_2"),
286        doc = "Specifies the directory in which the new P4 Server is initialized. If not specified, defaults to the current directory."
287    )]
288    pub fn dir(mut self, v: impl Into<PathBuf>) -> Self {
289        self.dir = Some(v.into());
290        self
291    }
292
293    /// Returns the value of `-c client`, if set.
294    ///
295    /// This is one of the few options that `p4 clone` recognizes *before* the
296    /// subcommand, in place of the full set of global options.
297    pub fn get_client(&self) -> Option<&str> {
298        self.client.as_deref()
299    }
300
301    /// Sets the value of `-c client`.
302    pub fn set_client(&mut self, v: impl Into<String>) -> &mut Self {
303        self.client = Some(v.into());
304        self
305    }
306
307    /// Sets `-c client`.
308    ///
309    /// # Description
310    ///
311    /// -c client
312    ///
313    /// Specifies the client name. If not specified, defaults to the name
314    /// established with the `p4 init` command.
315    pub fn client(mut self, v: impl Into<String>) -> Self {
316        self.client = Some(v.into());
317        self
318    }
319
320    /// Returns the value of `-m depth`, if set.
321    pub fn get_depth(&self) -> Option<u64> {
322        self.depth
323    }
324
325    /// Sets the value of `-m depth`.
326    pub fn set_depth(&mut self, v: u64) -> &mut Self {
327        self.depth = Some(v);
328        self
329    }
330
331    /// Sets `-m depth`.
332    ///
333    /// # Description
334    ///
335    /// -m depth
336    ///
337    /// Specifies the maximum number of revisions of each file to clone; a
338    /// *shallow* clone.
339    pub fn depth(mut self, v: u64) -> Self {
340        self.depth = Some(v);
341        self
342    }
343
344    /// Returns whether `-v` verbose mode is enabled.
345    pub fn get_verbose(&self) -> bool {
346        self.verbose
347    }
348
349    /// Sets whether `-v` verbose mode is enabled.
350    pub fn set_verbose(&mut self, v: bool) -> &mut Self {
351        self.verbose = v;
352        self
353    }
354
355    /// Enables `-v` verbose mode when `v` is `true`.
356    ///
357    /// # Description
358    ///
359    /// -v
360    ///
361    /// Enables verbose mode.
362    pub fn verbose(mut self, v: bool) -> Self {
363        self.verbose = v;
364        self
365    }
366}
367
368// ---------------------------------------------------------------------------
369// Port selection: `-p port`
370// ---------------------------------------------------------------------------
371
372impl<M> Clone<Unselected, M> {
373    /// Sets `-p port` and transitions this command to the [`Port`] state.
374    ///
375    /// # Description
376    ///
377    /// -p port
378    ///
379    #[cfg_attr(
380        feature = "lt2016_1",
381        doc = "Specifies the address (`P4PORT`) of the remote server you wish to clone from."
382    )]
383    #[cfg_attr(
384        not(feature = "lt2016_1"),
385        doc = "Specifies the address (`P4PORT`) of the remote server you wish to clone from.",
386        doc = "",
387        doc = "This flag is optional. If not specified, `p4 clone` uses the remote server specified by the `P4PORT` environment variable."
388    )]
389    ///
390    /// A remote port is required before the command can be assembled.
391    pub fn port(self, v: impl Into<String>) -> Clone<Port, M> {
392        Clone {
393            bin: self.bin,
394            user: self.user,
395            dir: self.dir,
396            client: self.client,
397            depth: self.depth,
398            verbose: self.verbose,
399            port: Port { port: v.into() },
400            mode: self.mode,
401        }
402    }
403}
404
405impl<M> Clone<Port, M> {
406    /// Returns the value of `-p port`.
407    pub fn get_port(&self) -> &str {
408        &self.port.port
409    }
410
411    /// Sets the value of `-p port`.
412    pub fn set_port(&mut self, v: impl Into<String>) -> &mut Self {
413        self.port.port = v.into();
414        self
415    }
416
417    /// Sets `-p port`.
418    ///
419    /// # Description
420    ///
421    /// -p port
422    ///
423    #[cfg_attr(
424        feature = "lt2016_1",
425        doc = "Specifies the address (`P4PORT`) of the remote server you wish to clone from."
426    )]
427    #[cfg_attr(
428        not(feature = "lt2016_1"),
429        doc = "Specifies the address (`P4PORT`) of the remote server you wish to clone from.",
430        doc = "",
431        doc = "This flag is optional. If not specified, `p4 clone` uses the remote server specified by the `P4PORT` environment variable."
432    )]
433    pub fn port(mut self, v: impl Into<String>) -> Self {
434        self.port.port = v.into();
435        self
436    }
437}
438
439// ---------------------------------------------------------------------------
440// Clone target selection: `-r remotespec` vs `-f filespec`
441// ---------------------------------------------------------------------------
442
443impl<P> Clone<P, Unselected> {
444    /// Sets `-r remotespec` and transitions this command to the
445    /// [`RemoteSpecMode`] state.
446    ///
447    /// # Description
448    ///
449    /// -r remotespec
450    ///
451    /// Specifies the remote spec call `remotespec` installed on the remote
452    /// server to use as a template for the clone and stream setup.
453    ///
454    /// This is mutually exclusive with `-f filespec`
455    /// ([`Self::file`]).
456    pub fn remote(self, v: impl Into<String>) -> Clone<P, RemoteSpecMode> {
457        Clone {
458            bin: self.bin,
459            user: self.user,
460            dir: self.dir,
461            client: self.client,
462            depth: self.depth,
463            verbose: self.verbose,
464            port: self.port,
465            mode: RemoteSpecMode { source: v.into() },
466        }
467    }
468
469    /// Sets `-f filespec` and transitions this command to the
470    /// [`FileSpecMode`] state.
471    ///
472    /// # Description
473    ///
474    /// -f filespec
475    ///
476    #[cfg_attr(
477        feature = "lt2016_1",
478        doc = "Specifies a `filepath` in the remote server to use as the path to clone. Perforce will use this path to determine the stream setup in the local server. Specifying the filepath also creates a default remote spec called `origin`."
479    )]
480    #[cfg_attr(
481        all(feature = "lt2017_2", not(feature = "lt2016_1")),
482        doc = "Specifies a `filespec` in the remote server to use as the path to clone. Perforce uses this path to determine the stream setup in the local server. The Helix Versioning Engine also uses this file specification to determine the stream setup in the personal server. Specifying the filespec also creates a default remote spec called `origin`.",
483        doc = "",
484        doc = "The `-f` preceding the filespec is optional. You can simply issue the command `p4 clone //file/path`."
485    )]
486    #[cfg_attr(
487        all(feature = "lt2018_1", not(feature = "lt2017_2")),
488        doc = "Specifies a `filespec` in the remote server to use as the path to clone. The Helix Versioning Engine uses this path to determine the stream setup in the local server. Helix Server also uses this file specification to determine the stream setup in the personal server. Specifying the filespec also creates a default remote spec called `origin`.",
489        doc = "",
490        doc = "The `-f` preceding the filespec is optional. You can simply issue the command `p4 clone //file/path`."
491    )]
492    #[cfg_attr(
493        all(feature = "lt2019_1", not(feature = "lt2018_1")),
494        doc = "Specifies a `filespec` in the remote server to use as the path to clone. The Helix Core Server uses this path to determine the stream setup in the local server. Helix Server also uses this file specification to determine the stream setup in the personal server. Specifying the filespec also creates a default remote spec called `origin`.",
495        doc = "",
496        doc = "The `-f` preceding the filespec is optional. You can simply issue the command `p4 clone //file/path`."
497    )]
498    #[cfg_attr(
499        all(feature = "lt2021_1", not(feature = "lt2019_1")),
500        doc = "Specifies a `filespec` in the remote server to use as the path to clone. The Helix Core server uses this path to determine the stream setup in the local server. Helix server also uses this file specification to determine the stream setup in the personal server. Specifying the filespec also creates a default remote spec called `origin`.",
501        doc = "",
502        doc = "The `-f` preceding the filespec is optional. You can simply issue the command `p4 clone //file/path`."
503    )]
504    #[cfg_attr(
505        all(feature = "lt2024_1", not(feature = "lt2021_1")),
506        doc = "Specifies a `filespec` in the remote server to use as the path to clone. The Helix Core Server uses this path to determine the stream setup in the local server. Helix Server also uses this file specification to determine the stream setup in the personal server. Specifying the filespec also creates a default remote spec called `origin`.",
507        doc = "",
508        doc = "The `-f` preceding the filespec is optional. You can simply issue the command `p4 clone //file/path`."
509    )]
510    #[cfg_attr(
511        all(feature = "lt2024_2", not(feature = "lt2024_1")),
512        doc = "Specifies a `filespec` in the remote server to use as the path to clone. The Helix Core Server uses this path to determine the stream setup in the local server. Helix Core Server also uses this file specification to determine the stream setup in the personal server. Specifying the filespec also creates a default remote spec called `origin`.",
513        doc = "",
514        doc = "The `-f` preceding the filespec is optional. You can simply issue the command `p4 clone //file/path`."
515    )]
516    #[cfg_attr(
517        not(feature = "lt2024_2"),
518        doc = "Specifies a `filespec` in the remote server to use as the path to clone. The P4 Server uses this path to determine the stream setup in the local server. P4 Server also uses this file specification to determine the stream setup in the personal server. Specifying the filespec also creates a default remote spec called `origin`.",
519        doc = "",
520        doc = "The `-f` preceding the filespec is optional. You can simply issue the command `p4 clone //file/path`."
521    )]
522    ///
523    /// This is mutually exclusive with `-r remotespec`
524    /// ([`Self::remote`]).
525    pub fn file(self, v: impl Into<String>) -> Clone<P, FileSpecMode> {
526        Clone {
527            bin: self.bin,
528            user: self.user,
529            dir: self.dir,
530            client: self.client,
531            depth: self.depth,
532            verbose: self.verbose,
533            port: self.port,
534            mode: FileSpecMode { source: v.into() },
535        }
536    }
537}
538
539impl<P> Clone<P, RemoteSpecMode> {
540    /// Returns the value of `-r remotespec`.
541    pub fn get_source(&self) -> &str {
542        &self.mode.source
543    }
544
545    /// Sets the value of `-r remotespec`.
546    pub fn set_source(&mut self, v: impl Into<String>) -> &mut Self {
547        self.mode.source = v.into();
548        self
549    }
550
551    /// Sets `-r remotespec`.
552    ///
553    /// # Description
554    ///
555    /// -r remotespec
556    ///
557    /// Specifies the remote spec call `remotespec` installed on the remote
558    /// server to use as a template for the clone and stream setup.
559    pub fn source(mut self, v: impl Into<String>) -> Self {
560        self.mode.source = v.into();
561        self
562    }
563}
564
565impl<P> Clone<P, FileSpecMode> {
566    /// Returns the value of `-f filespec`.
567    pub fn get_source(&self) -> &str {
568        &self.mode.source
569    }
570
571    /// Sets the value of `-f filespec`.
572    pub fn set_source(&mut self, v: impl Into<String>) -> &mut Self {
573        self.mode.source = v.into();
574        self
575    }
576
577    /// Sets `-f filespec`.
578    ///
579    /// # Description
580    ///
581    /// -f filespec
582    ///
583    #[cfg_attr(
584        feature = "lt2016_1",
585        doc = "Specifies a `filepath` in the remote server to use as the path to clone. Perforce will use this path to determine the stream setup in the local server. Specifying the filepath also creates a default remote spec called `origin`."
586    )]
587    #[cfg_attr(
588        all(feature = "lt2017_2", not(feature = "lt2016_1")),
589        doc = "Specifies a `filespec` in the remote server to use as the path to clone. Perforce uses this path to determine the stream setup in the local server. The Helix Versioning Engine also uses this file specification to determine the stream setup in the personal server. Specifying the filespec also creates a default remote spec called `origin`.",
590        doc = "",
591        doc = "The `-f` preceding the filespec is optional. You can simply issue the command `p4 clone //file/path`."
592    )]
593    #[cfg_attr(
594        all(feature = "lt2018_1", not(feature = "lt2017_2")),
595        doc = "Specifies a `filespec` in the remote server to use as the path to clone. The Helix Versioning Engine uses this path to determine the stream setup in the local server. Helix Server also uses this file specification to determine the stream setup in the personal server. Specifying the filespec also creates a default remote spec called `origin`.",
596        doc = "",
597        doc = "The `-f` preceding the filespec is optional. You can simply issue the command `p4 clone //file/path`."
598    )]
599    #[cfg_attr(
600        all(feature = "lt2019_1", not(feature = "lt2018_1")),
601        doc = "Specifies a `filespec` in the remote server to use as the path to clone. The Helix Core Server uses this path to determine the stream setup in the local server. Helix Server also uses this file specification to determine the stream setup in the personal server. Specifying the filespec also creates a default remote spec called `origin`.",
602        doc = "",
603        doc = "The `-f` preceding the filespec is optional. You can simply issue the command `p4 clone //file/path`."
604    )]
605    #[cfg_attr(
606        all(feature = "lt2021_1", not(feature = "lt2019_1")),
607        doc = "Specifies a `filespec` in the remote server to use as the path to clone. The Helix Core server uses this path to determine the stream setup in the local server. Helix server also uses this file specification to determine the stream setup in the personal server. Specifying the filespec also creates a default remote spec called `origin`.",
608        doc = "",
609        doc = "The `-f` preceding the filespec is optional. You can simply issue the command `p4 clone //file/path`."
610    )]
611    #[cfg_attr(
612        all(feature = "lt2024_1", not(feature = "lt2021_1")),
613        doc = "Specifies a `filespec` in the remote server to use as the path to clone. The Helix Core Server uses this path to determine the stream setup in the local server. Helix Server also uses this file specification to determine the stream setup in the personal server. Specifying the filespec also creates a default remote spec called `origin`.",
614        doc = "",
615        doc = "The `-f` preceding the filespec is optional. You can simply issue the command `p4 clone //file/path`."
616    )]
617    #[cfg_attr(
618        all(feature = "lt2024_2", not(feature = "lt2024_1")),
619        doc = "Specifies a `filespec` in the remote server to use as the path to clone. The Helix Core Server uses this path to determine the stream setup in the local server. Helix Core Server also uses this file specification to determine the stream setup in the personal server. Specifying the filespec also creates a default remote spec called `origin`.",
620        doc = "",
621        doc = "The `-f` preceding the filespec is optional. You can simply issue the command `p4 clone //file/path`."
622    )]
623    #[cfg_attr(
624        not(feature = "lt2024_2"),
625        doc = "Specifies a `filespec` in the remote server to use as the path to clone. The P4 Server uses this path to determine the stream setup in the local server. P4 Server also uses this file specification to determine the stream setup in the personal server. Specifying the filespec also creates a default remote spec called `origin`.",
626        doc = "",
627        doc = "The `-f` preceding the filespec is optional. You can simply issue the command `p4 clone //file/path`."
628    )]
629    pub fn source(mut self, v: impl Into<String>) -> Self {
630        self.mode.source = v.into();
631        self
632    }
633}
634
635// ---------------------------------------------------------------------------
636// SubCommand: only after a port (`-p`) and a target (`-r` / `-f`) are selected
637// ---------------------------------------------------------------------------
638
639impl<M: CloneTarget> SubCommand for Clone<Port, M> {
640    fn name(&self) -> &str {
641        "clone"
642    }
643
644    /// Injects the options that precede the subcommand name (`-u`, `-d`,
645    /// `-c`), then the subcommand name, then the remaining options.
646    ///
647    /// `p4 clone` does not accept the global options, so no
648    /// [`GlobalOpts`](crate::global::GlobalOpts) are injected.
649    fn inject_args(&self, command: &mut Command) {
650        if let Some(user) = &self.user {
651            command.arg("-u").arg(user);
652        }
653
654        if let Some(dir) = &self.dir {
655            command.arg("-d").arg(dir);
656        }
657
658        if let Some(client) = &self.client {
659            command.arg("-c").arg(client);
660        }
661
662        self.inject_local_args(command.arg(self.name()));
663    }
664
665    fn inject_local_args(&self, command: &mut Command) {
666        if let Some(depth) = self.depth {
667            command.arg("-m").arg(depth.to_string());
668        }
669
670        if self.verbose {
671            command.arg("-v");
672        }
673
674        command.arg("-p").arg(&self.port.port);
675
676        self.mode.inject_args(command);
677    }
678}
679
680// ---------------------------------------------------------------------------
681// Spawning: only after a port (`-p`) and a target (`-r` / `-f`) are selected
682// ---------------------------------------------------------------------------
683
684impl<M: CloneTarget> ParameterizedSpawn<()> for Clone<Port, M> {
685    type Output = Child;
686    type Error = std::io::Error;
687
688    /// Spawns `p4 clone` as a child process with piped standard output and
689    /// error streams; use the returned [`Child`] handle to wait for it or
690    /// 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
699#[cfg(test)]
700mod tests {
701    use super::*;
702    use crate::cmd::args_of;
703
704    #[test]
705    fn bin_accessors_update_executable_path() {
706        let mut command = Clone::new("p4").port("perforce:1666").remote("origin");
707        assert_eq!(command.get_bin(), Path::new("p4"));
708
709        command.set_bin("/usr/local/bin/p4");
710        assert_eq!(command.get_bin(), Path::new("/usr/local/bin/p4"));
711
712        let command = command.bin("p4.exe");
713        assert_eq!(command.get_bin(), Path::new("p4.exe"));
714    }
715
716    #[test]
717    fn getters_reflect_selected_values() {
718        let mut command = Clone::new("p4").port("perforce:1666").remote("origin");
719
720        assert_eq!(command.get_user(), None);
721        assert_eq!(command.get_dir(), None);
722        assert_eq!(command.get_client(), None);
723        assert_eq!(command.get_depth(), None);
724        assert!(!command.get_verbose());
725        assert_eq!(command.get_port(), "perforce:1666");
726        assert_eq!(command.get_source(), "origin");
727
728        command.set_user("bruno");
729        command.set_dir("Ace");
730        command.set_client("bruno-ws");
731        command.set_depth(5);
732        command.set_verbose(true);
733        command.set_port("perforce:1667");
734        command.set_source("upstream");
735
736        assert_eq!(command.get_user(), Some("bruno"));
737        assert_eq!(command.get_dir(), Some(Path::new("Ace")));
738        assert_eq!(command.get_client(), Some("bruno-ws"));
739        assert_eq!(command.get_depth(), Some(5));
740        assert!(command.get_verbose());
741        assert_eq!(command.get_port(), "perforce:1667");
742        assert_eq!(command.get_source(), "upstream");
743    }
744
745    /// Dry-run checks of the assembled `p4 clone` command line; no process is
746    /// spawned.
747    #[test]
748    fn port_and_remote_only() {
749        let clone = Clone::new("p4").port("perforce:1666").remote("origin");
750
751        assert_eq!(
752            args_of(&clone.setup_command("p4")),
753            ["clone", "-p", "perforce:1666", "-r", "origin"]
754        );
755    }
756
757    #[test]
758    fn port_and_file_only() {
759        let clone = Clone::new("p4")
760            .port("perforce:1666")
761            .file("//depot/main/...");
762
763        assert_eq!(
764            args_of(&clone.setup_command("p4")),
765            ["clone", "-p", "perforce:1666", "-f", "//depot/main/..."]
766        );
767        assert_eq!(clone.get_source(), "//depot/main/...");
768    }
769
770    /// The two required selections are independent of each other: the target
771    /// may be chosen before the port.
772    #[test]
773    fn selection_order_is_independent() {
774        let check = |clone: Clone<Port, RemoteSpecMode>| {
775            assert_eq!(
776                args_of(&clone.setup_command("p4")),
777                ["clone", "-p", "perforce:1666", "-r", "origin"]
778            );
779        };
780
781        check(Clone::new("p4").port("perforce:1666").remote("origin"));
782        check(Clone::new("p4").remote("origin").port("perforce:1666"));
783    }
784
785    #[test]
786    fn all_options_in_syntax_order() {
787        let clone = Clone::new("p4")
788            .user("bruno")
789            .dir("Ace")
790            .client("bruno-ws")
791            .depth(5)
792            .verbose(true)
793            .port("perforce:1666")
794            .file("//depot/main/...");
795
796        assert_eq!(
797            args_of(&clone.setup_command("p4")),
798            [
799                "-u",
800                "bruno",
801                "-d",
802                "Ace",
803                "-c",
804                "bruno-ws",
805                "clone",
806                "-m",
807                "5",
808                "-v",
809                "-p",
810                "perforce:1666",
811                "-f",
812                "//depot/main/..."
813            ]
814        );
815    }
816
817    #[test]
818    fn verbose_flag_is_omitted_when_disabled() {
819        let clone = Clone::new("p4")
820            .port("perforce:1666")
821            .remote("origin")
822            .verbose(false);
823
824        assert_eq!(
825            args_of(&clone.setup_command("p4")),
826            ["clone", "-p", "perforce:1666", "-r", "origin"]
827        );
828    }
829
830    /// `-p`, `-m`, and `-v` are common options: they may be set before the
831    /// port and target are selected.
832    #[test]
833    fn common_options_before_required_selections() {
834        let clone = Clone::new("p4")
835            .depth(1)
836            .verbose(true)
837            .port("perforce:1666")
838            .remote("origin");
839
840        assert_eq!(
841            args_of(&clone.setup_command("p4")),
842            [
843                "clone",
844                "-m",
845                "1",
846                "-v",
847                "-p",
848                "perforce:1666",
849                "-r",
850                "origin"
851            ]
852        );
853    }
854}