forge
Explore
Log in

Don't you dare go Hollow

Create default config file if missing

Browse files at this commit

0ebcc3e0d6ff7eda50d54fce312d0d1a42bd8224Ivan MolodetskikhParent: 64c85d8
src/main.rsmodified+38 -1
@@ -26,6 +26,8 @@ mod dummy_pw_utils;
26 mod pw_utils;26 mod pw_utils;
27 27
28 use std::ffi::OsString;28 use std::ffi::OsString;
29+use std::fs::{self, File};
30+use std::io::{self, Write};
29 use std::path::PathBuf;31 use std::path::PathBuf;
30 use std::process::Command;32 use std::process::Command;
31 use std::{env, mem};33 use std::{env, mem};
@@ -154,7 +156,42 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
154 info!("starting version {}", &version());156 info!("starting version {}", &version());
155 157
156 // Load the config.158 // Load the config.
157- let path = cli.config.or_else(default_config_path);159+ let path = cli.config.or_else(|| {
160+ let default_path = default_config_path()?;
161+ let default_parent = default_path.parent().unwrap();
162+
163+ if let Err(err) = fs::create_dir_all(default_parent) {
164+ warn!(
165+ "error creating config directories {:?}: {err:?}",
166+ default_parent
167+ );
168+ return Some(default_path);
169+ }
170+
171+ // Create the config and fill it with the default config if it doesn't exist.
172+ let new_file = File::options()
173+ .read(true)
174+ .write(true)
175+ .create_new(true)
176+ .open(&default_path);
177+ match new_file {
178+ Ok(mut new_file) => {
179+ let default = include_bytes!("../resources/default-config.kdl");
180+ match new_file.write_all(default) {
181+ Ok(()) => {
182+ info!("wrote default config to {:?}", &default_path);
183+ }
184+ Err(err) => {
185+ warn!("error writing config file at {:?}: {err:?}", &default_path)
186+ }
187+ }
188+ }
189+ Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {}
190+ Err(err) => warn!("error creating config file at {:?}: {err:?}", &default_path),
191+ }
192+
193+ Some(default_path)
194+ });
158 195
159 let mut config_errored = false;196 let mut config_errored = false;
160 let mut config = path197 let mut config = path