Skip to main content

perforce_cli/cmd/
diskspace.rs

1use std::ffi::OsStr;
2use std::path::{Path, PathBuf};
3use std::process::{Child, Command, Stdio};
4
5use super::{ExclusiveOption, SubCommand, Unselected};
6
7use crate::global::GlobalOpts;
8use crate::spawn::ParameterizedSpawn;
9
10// ---------------------------------------------------------------------------
11// Predefined targets
12// ---------------------------------------------------------------------------
13
14/// The `P4ROOT` target: report disk space for the filesystem holding
15/// [`P4ROOT`](https://help.perforce.com/helix-core/server-apps/cmdref/current/Content/CmdRef/P4ROOT.html).
16///
17/// Entered with [`DiskSpace::report_p4root`].
18#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
19pub struct P4Root;
20
21/// The `P4JOURNAL` target: report disk space for the filesystem holding
22/// [`P4JOURNAL`](https://help.perforce.com/helix-core/server-apps/cmdref/current/Content/CmdRef/P4JOURNAL.html).
23///
24/// Entered with [`DiskSpace::report_p4journal`].
25#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
26pub struct P4Journal;
27
28/// The `P4LOG` target: report disk space for the filesystem holding
29/// [`P4LOG`](https://help.perforce.com/helix-core/server-apps/cmdref/current/Content/CmdRef/P4LOG.html)
30/// (the server log).
31///
32/// Entered with [`DiskSpace::report_p4log`].
33#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
34pub struct P4Log;
35
36/// The `TEMP` target: report disk space for the filesystem holding temporary
37/// files. If `TEMP` is not defined, `P4ROOT` is used on Windows and `/tmp` on
38/// Unix.
39///
40/// Entered with [`DiskSpace::report_temp`].
41#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
42pub struct Temp;
43
44// ---------------------------------------------------------------------------
45// Argument injection
46// ---------------------------------------------------------------------------
47
48impl ExclusiveOption for P4Root {
49    fn inject_args(&self, command: &mut Command) {
50        command.arg("P4ROOT");
51    }
52}
53
54impl ExclusiveOption for P4Journal {
55    fn inject_args(&self, command: &mut Command) {
56        command.arg("P4JOURNAL");
57    }
58}
59
60impl ExclusiveOption for P4Log {
61    fn inject_args(&self, command: &mut Command) {
62        command.arg("P4LOG");
63    }
64}
65
66impl ExclusiveOption for Temp {
67    fn inject_args(&self, command: &mut Command) {
68        command.arg("TEMP");
69    }
70}
71
72// ---------------------------------------------------------------------------
73// Command struct
74// ---------------------------------------------------------------------------
75
76/// Type-safe builder for `p4 diskspace`.
77///
78/// `p4 df` is an alias for `p4 diskspace`.
79///
80/// # Syntax
81///
82/// ```text
83/// p4 [g-opts] diskspace [P4ROOT | P4JOURNAL | P4LOG | TEMP | journalPrefix | depot]
84/// ```
85///
86/// Shows summary information about the current availability of disk space on
87/// the server.
88///
89/// The output of `p4 diskspace` is in the form:
90///
91/// ```text
92/// name (type type) : xxx GB free, yyy GB used, zzz GB total (ff % full)
93/// ```
94///
95#[cfg_attr(
96    feature = "lt2017_2",
97    doc = "Where `name` can be either `P4ROOT`, `P4JOURNAL`, `P4LOG`, `TEMP`, a prefix to a non-default Perforce journal file location, or the name of a Perforce depot. The filesystem `type` is that reported by the operating system."
98)]
99#[cfg_attr(
100    all(feature = "lt2019_1", not(feature = "lt2017_2")),
101    doc = "Where `name` can be either `P4ROOT`, `P4JOURNAL`, `P4LOG`, `TEMP`, a prefix to a non-default Helix Server journal file location, or the name of a Helix Server depot. The filesystem `type` is that reported by the operating system."
102)]
103#[cfg_attr(
104    all(feature = "lt2021_1", not(feature = "lt2019_1")),
105    doc = "Where `name` can be either `P4ROOT`, `P4JOURNAL`, `P4LOG`, `TEMP`, a prefix to a non-default Helix server journal file location, or the name of a Helix server depot. The filesystem `type` is that reported by the operating system."
106)]
107#[cfg_attr(
108    all(feature = "lt2024_1", not(feature = "lt2021_1")),
109    doc = "Where `name` can be either `P4ROOT`, `P4JOURNAL`, `P4LOG`, `TEMP`, a prefix to a non-default Helix Server journal file location, or the name of a Helix Server depot. The filesystem `type` is that reported by the operating system."
110)]
111#[cfg_attr(
112    all(feature = "lt2024_2", not(feature = "lt2024_1")),
113    doc = "Where `name` can be either `P4ROOT`, `P4JOURNAL`, `P4LOG`, `TEMP`, a prefix to a non-default Helix Core Server journal file location, or the name of a Helix Core Server depot. The filesystem `type` is that reported by the operating system."
114)]
115#[cfg_attr(
116    not(feature = "lt2024_2"),
117    doc = "Where `name` can be either `P4ROOT`, `P4JOURNAL`, `P4LOG`, `TEMP`, a prefix to a non-default P4 Server journal file location, or the name of a P4 Server depot. The filesystem `type` is that reported by the operating system."
118)]
119///
120/// If no arguments are specified, disk space information is displayed for all
121/// objects.
122///
123#[cfg_attr(
124    all(not(feature = "lt2016_1"), feature = "lt2017_2"),
125    doc = "By default, Perforce rejects commands when free space on the filesystems housing the `P4ROOT`, `P4JOURNAL`, `P4LOG`, or `TEMP` falls below 10 megabytes. To change this behavior, set the `filesys.P4ROOT.min` (and corresponding) configurables to your desired limits."
126)]
127#[cfg_attr(
128    all(
129        not(feature = "lt2016_1"),
130        feature = "lt2019_1",
131        not(feature = "lt2017_2")
132    ),
133    doc = "By default, Helix Server rejects commands when free space on the filesystems housing the `P4ROOT`, `P4JOURNAL`, `P4LOG`, or `TEMP` falls below 10 megabytes. To change this behavior, set the `filesys.P4ROOT.min` (and corresponding) configurables to your desired limits."
134)]
135#[cfg_attr(
136    all(
137        not(feature = "lt2016_1"),
138        feature = "lt2021_1",
139        not(feature = "lt2019_1")
140    ),
141    doc = "By default, Helix server rejects commands when free space on the filesystems housing the `P4ROOT`, `P4JOURNAL`, `P4LOG`, or `TEMP` falls below 10 megabytes. To change this behavior, set the `filesys.P4ROOT.min` (and corresponding) configurables to your desired limits."
142)]
143#[cfg_attr(
144    all(
145        not(feature = "lt2016_1"),
146        feature = "lt2024_1",
147        not(feature = "lt2021_1")
148    ),
149    doc = "By default, Helix Server rejects commands when free space on the filesystems housing the `P4ROOT`, `P4JOURNAL`, `P4LOG`, or `TEMP` falls below 10 megabytes. To change this behavior, set the `filesys.P4ROOT.min` (and corresponding) configurables to your desired limits."
150)]
151#[cfg_attr(
152    all(
153        not(feature = "lt2016_1"),
154        feature = "lt2024_2",
155        not(feature = "lt2024_1")
156    ),
157    doc = "By default, Helix Core Server rejects commands when free space on the filesystems housing the `P4ROOT`, `P4JOURNAL`, `P4LOG`, or `TEMP` falls below 10 megabytes. To change this behavior, set the `filesys.P4ROOT.min` (and corresponding) configurables to your desired limits."
158)]
159#[cfg_attr(
160    all(not(feature = "lt2016_1"), not(feature = "lt2024_2")),
161    doc = "By default, P4 Server rejects commands when free space on the filesystems housing the `P4ROOT`, `P4JOURNAL`, `P4LOG`, or `TEMP` falls below 10 megabytes. To change this behavior, set the `filesys.P4ROOT.min` (and corresponding) configurables to your desired limits."
162)]
163#[cfg_attr(not(feature = "lt2016_1"), doc = "")]
164#[cfg_attr(
165    all(not(feature = "lt2016_1"), feature = "lt2017_2"),
166    doc = "If the user account that runs the Perforce versioning service is subject to disk quotas, the `filesys.*.min` configurables reflect those quotas, regardless of how much physical space actually remains on the filesystem(s) in question."
167)]
168#[cfg_attr(
169    all(
170        not(feature = "lt2016_1"),
171        feature = "lt2019_1",
172        not(feature = "lt2017_2")
173    ),
174    doc = "If the user account that runs the Helix Server is subject to disk quotas, the `filesys.*.min` configurables reflect those quotas, regardless of how much physical space actually remains on the filesystem(s) in question."
175)]
176#[cfg_attr(
177    all(
178        not(feature = "lt2016_1"),
179        feature = "lt2021_1",
180        not(feature = "lt2019_1")
181    ),
182    doc = "If the user account that runs the Helix server is subject to disk quotas, the `filesys.*.min` configurables reflect those quotas, regardless of how much physical space actually remains on the filesystem(s) in question."
183)]
184#[cfg_attr(
185    all(
186        not(feature = "lt2016_1"),
187        feature = "lt2024_1",
188        not(feature = "lt2021_1")
189    ),
190    doc = "If the user account that runs the Helix Server is subject to disk quotas, the `filesys.*.min` configurables reflect those quotas, regardless of how much physical space actually remains on the filesystem(s) in question."
191)]
192#[cfg_attr(
193    all(
194        not(feature = "lt2016_1"),
195        feature = "lt2024_2",
196        not(feature = "lt2024_1")
197    ),
198    doc = "If the user account that runs the Helix Core Server is subject to disk quotas, the `filesys.*.min` configurables reflect those quotas, regardless of how much physical space actually remains on the filesystem(s) in question."
199)]
200#[cfg_attr(
201    all(not(feature = "lt2016_1"), not(feature = "lt2024_2")),
202    doc = "If the user account that runs the P4 Server is subject to disk quotas, the `filesys.*.min` configurables reflect those quotas, regardless of how much physical space actually remains on the filesystem(s) in question."
203)]
204#[cfg_attr(not(feature = "lt2016_1"), doc = "", doc = "# Note", doc = "")]
205#[cfg_attr(
206    not(feature = "lt2016_1"),
207    doc = "Server releases prior to 16.1 included reserved space in the number displayed for used space in the Size column for Unix filesystems. This has been changed so that the size given now excludes reserved space."
208)]
209///
210/// The `M` type parameter tracks the target at compile time. [`Unselected`]
211/// (the state returned by [`DiskSpace::new`]) spawns the bare command, which
212/// reports disk space for every object, and can also be spawned with an
213/// arbitrary target argument through
214/// [`ParameterizedSpawn`] with a one-element tuple, or
215/// [`SpawnExt1`](crate::spawn::SpawnExt1); that covers a `journalPrefix` or a
216/// depot name. Use [`DiskSpace::report_p4root`], [`DiskSpace::report_p4journal`],
217/// [`DiskSpace::report_p4log`], or [`DiskSpace::report_temp`] to select one of
218/// the predefined targets; those states spawn without arguments.
219#[derive(Debug, Clone, Default)]
220pub struct DiskSpace<M = Unselected> {
221    bin: PathBuf,
222
223    global_opts: GlobalOpts,
224
225    mode: M,
226}
227
228// ---------------------------------------------------------------------------
229// Constructors and target transitions
230// ---------------------------------------------------------------------------
231
232impl DiskSpace<Unselected> {
233    /// Creates a new `p4 diskspace` command.
234    ///
235    /// `bin` is the path to the Perforce command-line executable. The
236    /// resulting command has no target argument and reports disk space for
237    /// every object.
238    pub fn new(bin: impl Into<PathBuf>, global_opts: GlobalOpts) -> Self {
239        Self {
240            bin: bin.into(),
241            global_opts,
242            mode: Unselected,
243        }
244    }
245}
246
247impl<M> DiskSpace<M> {
248    fn with_mode<N>(self, mode: N) -> DiskSpace<N> {
249        DiskSpace {
250            bin: self.bin,
251            global_opts: self.global_opts,
252            mode,
253        }
254    }
255
256    /// # Description
257    ///
258    /// `P4ROOT`
259    ///
260    /// Report disk space available for filesystem holding `P4ROOT`.
261    ///
262    /// Transitions to the [`P4Root`] state, which spawns without arguments.
263    pub fn report_p4root(self) -> DiskSpace<P4Root> {
264        self.with_mode(P4Root)
265    }
266
267    /// # Description
268    ///
269    /// `P4JOURNAL`
270    ///
271    /// Report disk space available for filesystem holding `P4JOURNAL`.
272    ///
273    /// Transitions to the [`P4Journal`] state, which spawns without
274    /// arguments.
275    pub fn report_p4journal(self) -> DiskSpace<P4Journal> {
276        self.with_mode(P4Journal)
277    }
278
279    /// # Description
280    ///
281    /// `P4LOG`
282    ///
283    /// Report disk space available for filesystem holding `P4LOG` (server
284    /// log).
285    ///
286    /// Transitions to the [`P4Log`] state, which spawns without arguments.
287    pub fn report_p4log(self) -> DiskSpace<P4Log> {
288        self.with_mode(P4Log)
289    }
290
291    /// # Description
292    ///
293    /// `TEMP`
294    ///
295    /// Report disk space available for filesystem holding temporary files. If
296    /// not defined, uses `P4ROOT` on Windows, and `/tmp` on Unix.
297    ///
298    /// Transitions to the [`Temp`] state, which spawns without arguments.
299    pub fn report_temp(self) -> DiskSpace<Temp> {
300        self.with_mode(Temp)
301    }
302}
303
304// ---------------------------------------------------------------------------
305// Accessors
306// ---------------------------------------------------------------------------
307
308impl<M: ExclusiveOption> DiskSpace<M> {
309    /// Get the Perforce command path.
310    pub fn get_bin(&self) -> &Path {
311        &self.bin
312    }
313
314    /// Set the Perforce command path.
315    pub fn set_bin(&mut self, bin: impl Into<PathBuf>) -> &mut Self {
316        self.bin = bin.into();
317        self
318    }
319
320    /// Set the Perforce command path.
321    pub fn bin(mut self, bin: impl Into<PathBuf>) -> Self {
322        self.set_bin(bin);
323        self
324    }
325
326    /// # Description
327    ///
328    /// g-opts
329    ///
330    #[cfg_attr(
331        feature = "lt2014_2",
332        doc = "See the [Global Options](GlobalOpts) section."
333    )]
334    #[cfg_attr(
335        all(feature = "lt2015_1", not(feature = "lt2014_2")),
336        doc = "See the [“Global Options”](GlobalOpts) section."
337    )]
338    #[cfg_attr(
339        all(feature = "lt2017_1", not(feature = "lt2015_1")),
340        doc = "See [“Global Options”](GlobalOpts)."
341    )]
342    #[cfg_attr(
343        all(feature = "lt2018_2", not(feature = "lt2017_1")),
344        doc = "See [Global Options](GlobalOpts)."
345    )]
346    #[cfg_attr(not(feature = "lt2018_2"), doc = "See [Global options](GlobalOpts).")]
347    pub fn get_global_opts(&self) -> &GlobalOpts {
348        &self.global_opts
349    }
350
351    /// # Description
352    ///
353    /// g-opts
354    ///
355    #[cfg_attr(
356        feature = "lt2014_2",
357        doc = "See the [Global Options](GlobalOpts) section."
358    )]
359    #[cfg_attr(
360        all(feature = "lt2015_1", not(feature = "lt2014_2")),
361        doc = "See the [“Global Options”](GlobalOpts) section."
362    )]
363    #[cfg_attr(
364        all(feature = "lt2017_1", not(feature = "lt2015_1")),
365        doc = "See [“Global Options”](GlobalOpts)."
366    )]
367    #[cfg_attr(
368        all(feature = "lt2018_2", not(feature = "lt2017_1")),
369        doc = "See [Global Options](GlobalOpts)."
370    )]
371    #[cfg_attr(not(feature = "lt2018_2"), doc = "See [Global options](GlobalOpts).")]
372    pub fn set_global_opts(&mut self, v: GlobalOpts) -> &mut Self {
373        self.global_opts = v;
374        self
375    }
376
377    /// # Description
378    ///
379    /// g-opts
380    ///
381    #[cfg_attr(
382        feature = "lt2014_2",
383        doc = "See the [Global Options](GlobalOpts) section."
384    )]
385    #[cfg_attr(
386        all(feature = "lt2015_1", not(feature = "lt2014_2")),
387        doc = "See the [“Global Options”](GlobalOpts) section."
388    )]
389    #[cfg_attr(
390        all(feature = "lt2017_1", not(feature = "lt2015_1")),
391        doc = "See [“Global Options”](GlobalOpts)."
392    )]
393    #[cfg_attr(
394        all(feature = "lt2018_2", not(feature = "lt2017_1")),
395        doc = "See [Global Options](GlobalOpts)."
396    )]
397    #[cfg_attr(not(feature = "lt2018_2"), doc = "See [Global options](GlobalOpts).")]
398    pub fn global_opts(mut self, v: GlobalOpts) -> Self {
399        self.global_opts = v;
400        self
401    }
402}
403
404// ---------------------------------------------------------------------------
405// SubCommand and spawning
406// ---------------------------------------------------------------------------
407
408impl<M: ExclusiveOption> SubCommand for DiskSpace<M> {
409    fn name(&self) -> &str {
410        "diskspace"
411    }
412
413    fn inject_local_args(&self, command: &mut Command) {
414        self.mode.inject_args(command);
415    }
416
417    fn global_opts(&self) -> Option<&GlobalOpts> {
418        Some(&self.global_opts)
419    }
420}
421
422impl<M: ExclusiveOption> ParameterizedSpawn<()> for DiskSpace<M> {
423    type Output = Child;
424    type Error = std::io::Error;
425
426    /// Spawns `p4 diskspace` as a child process with piped standard output
427    /// and error streams; use the returned [`Child`] handle to wait for it or
428    /// interact with it.
429    fn spawn_with(&mut self, (): ()) -> Result<Self::Output, Self::Error> {
430        self.setup_command(&self.bin)
431            .stdout(Stdio::piped())
432            .stderr(Stdio::piped())
433            .spawn()
434    }
435}
436
437impl<S: AsRef<OsStr>> ParameterizedSpawn<(S,)> for DiskSpace<Unselected> {
438    type Output = Child;
439    type Error = std::io::Error;
440
441    /// Spawns `p4 diskspace <target>` as a child process with piped standard
442    /// output and error streams, where `target` is a `journalPrefix` or a
443    /// depot name.
444    fn spawn_with(&mut self, (target,): (S,)) -> Result<Self::Output, Self::Error> {
445        self.setup_command(&self.bin)
446            .arg(target)
447            .stdout(Stdio::piped())
448            .stderr(Stdio::piped())
449            .spawn()
450    }
451}
452
453#[cfg(test)]
454mod tests {
455    use super::*;
456    use crate::cmd::args_of;
457
458    fn args(cmd: &impl SubCommand) -> Vec<String> {
459        args_of(&cmd.setup_command("p4"))
460    }
461
462    /// Dry-run checks of the assembled `p4 diskspace` command line; no
463    /// process is spawned.
464    #[test]
465    fn bare_form_has_no_argument() {
466        let cmd = DiskSpace::new("p4", GlobalOpts::new());
467
468        assert_eq!(args(&cmd), ["diskspace"]);
469    }
470
471    #[test]
472    fn predefined_targets() {
473        assert_eq!(
474            args(&DiskSpace::new("p4", GlobalOpts::new()).report_p4root()),
475            ["diskspace", "P4ROOT"]
476        );
477        assert_eq!(
478            args(&DiskSpace::new("p4", GlobalOpts::new()).report_p4journal()),
479            ["diskspace", "P4JOURNAL"]
480        );
481        assert_eq!(
482            args(&DiskSpace::new("p4", GlobalOpts::new()).report_p4log()),
483            ["diskspace", "P4LOG"]
484        );
485        assert_eq!(
486            args(&DiskSpace::new("p4", GlobalOpts::new()).report_temp()),
487            ["diskspace", "TEMP"]
488        );
489    }
490
491    #[test]
492    fn targets_can_be_switched() {
493        let cmd = DiskSpace::new("p4", GlobalOpts::new()).report_p4root();
494        let cmd = cmd.report_temp();
495
496        assert_eq!(args(&cmd), ["diskspace", "TEMP"]);
497    }
498
499    #[test]
500    fn global_opts_are_injected_once() {
501        let cmd = DiskSpace::new(
502            "p4",
503            GlobalOpts::new().port("localhost:1666").quiet_mode(true),
504        )
505        .report_p4root();
506
507        assert_eq!(
508            args(&cmd),
509            ["-p", "localhost:1666", "-q", "diskspace", "P4ROOT"]
510        );
511    }
512
513    #[test]
514    fn bin_accessors_update_executable_path() {
515        let mut cmd = DiskSpace::new("p4", GlobalOpts::new()).report_temp();
516        assert_eq!(cmd.get_bin(), Path::new("p4"));
517
518        cmd.set_bin("/usr/local/bin/p4");
519        assert_eq!(cmd.get_bin(), Path::new("/usr/local/bin/p4"));
520
521        let cmd = cmd.bin("p4.exe");
522        assert_eq!(cmd.get_bin(), Path::new("p4.exe"));
523    }
524}