Skip to main content

coreutils_rs/chgrp/
core.rs

1use std::io;
2use std::path::Path;
3
4use crate::chown::{ChownConfig, SymlinkFollow};
5
6/// Configuration for chgrp operations.
7/// This is a convenience wrapper that builds a `ChownConfig` internally.
8#[derive(Debug, Clone)]
9pub struct ChgrpConfig {
10    pub verbose: bool,
11    pub changes: bool,
12    pub silent: bool,
13    pub recursive: bool,
14    pub no_dereference: bool,
15    pub preserve_root: bool,
16    pub from_group: Option<u32>,
17    pub symlink_follow: SymlinkFollow,
18}
19
20impl Default for ChgrpConfig {
21    fn default() -> Self {
22        Self {
23            verbose: false,
24            changes: false,
25            silent: false,
26            recursive: false,
27            no_dereference: false,
28            preserve_root: false,
29            from_group: None,
30            symlink_follow: SymlinkFollow::Never,
31        }
32    }
33}
34
35impl ChgrpConfig {
36    /// Convert to a `ChownConfig` for reuse of the chown infrastructure.
37    pub fn to_chown_config(&self) -> ChownConfig {
38        ChownConfig {
39            verbose: self.verbose,
40            changes: self.changes,
41            silent: self.silent,
42            recursive: self.recursive,
43            no_dereference: self.no_dereference,
44            preserve_root: self.preserve_root,
45            from_owner: None,
46            from_group: self.from_group,
47            symlink_follow: self.symlink_follow,
48        }
49    }
50}
51
52/// Change the group of a single file.
53///
54/// This is a thin wrapper around `chown_file` with `uid = None`.
55/// Returns `Ok(true)` if the group was actually changed.
56pub fn chgrp_file(path: &Path, gid: u32, config: &ChgrpConfig) -> io::Result<bool> {
57    let chown_config = config.to_chown_config();
58    crate::chown::chown_file(path, None, Some(gid), &chown_config)
59}
60
61/// Recursively change the group of a directory tree.
62///
63/// Returns the number of errors encountered.
64pub fn chgrp_recursive(
65    path: &Path,
66    gid: u32,
67    config: &ChgrpConfig,
68    is_command_line_arg: bool,
69    tool_name: &str,
70) -> i32 {
71    let chown_config = config.to_chown_config();
72    crate::chown::chown_recursive(
73        path,
74        None,
75        Some(gid),
76        &chown_config,
77        is_command_line_arg,
78        tool_name,
79    )
80}