reactive_graph_tooling/tooling/instances/
provisioning.rs1use anyhow::Result;
2use std::fs::OpenOptions;
3use std::fs::create_dir_all;
4use std::fs::write;
5use std::path::Path;
6use std::path::PathBuf;
7
8pub struct Chown {
9 pub uid: u32,
10 pub gid: u32,
11}
12
13impl Chown {
14 pub fn new(uid: u32, gid: u32) -> Self {
15 Self { uid, gid }
16 }
17}
18
19pub fn create_dir<S: Into<String>>(working_dir: &Path, sub_dir: S, chown: &Option<Chown>) -> Result<PathBuf> {
20 let mut target_dir = working_dir.to_owned();
21 target_dir.push(sub_dir.into());
22 match create_dir_all(&target_dir) {
23 Ok(_) => {
24 println!("Created {}", target_dir.to_string_lossy());
25 #[cfg(target_os = "linux")]
26 if let Some(chown) = chown {
27 use std::os::unix::fs;
28 fs::chown(&target_dir, Some(chown.uid), Some(chown.gid))?;
29 }
30 Ok(target_dir)
31 }
32 Err(e) => {
33 eprintln!("Failed to create {}: {}", target_dir.to_string_lossy(), e);
34 Err(e.into())
35 }
36 }
37}
38
39pub fn write_file<P: Into<PathBuf>>(target_dir: &Path, file: P, content: &str, chown: &Option<Chown>) -> Result<PathBuf> {
40 let mut target_file = target_dir.to_owned();
41 target_file.push(file.into());
42 match write(&target_file, content) {
43 Ok(_) => {
44 println!("Wrote file {}", target_file.to_string_lossy());
45 #[cfg(target_os = "linux")]
46 if let Some(chown) = chown {
47 use std::os::unix::fs;
48 fs::chown(&target_file, Some(chown.uid), Some(chown.gid))?;
49 }
50 Ok(target_file)
51 }
52 Err(e) => {
53 eprintln!("Failed to write file {}: {}", target_file.to_string_lossy(), e);
54 Err(e.into())
55 }
56 }
57}
58
59pub fn create_empty_file(target_file: &Path, chown: &Option<Chown>) -> Result<()> {
60 match OpenOptions::new().create(true).truncate(false).write(true).open(target_file) {
61 Ok(_file) => {
62 println!("Created file {}", target_file.to_string_lossy());
63 #[cfg(target_os = "linux")]
64 if let Some(chown) = chown {
65 use std::os::unix::fs;
66 fs::chown(target_file, Some(chown.uid), Some(chown.gid))?;
67 }
68 Ok(())
69 }
70 Err(e) => {
71 eprintln!("Failed to create file {}: {}", target_file.to_string_lossy(), e);
72 Err(e.into())
73 }
74 }
75}