1use std::{env::current_dir, fmt::Display};
2
3use crate::io::file;
4
5use anyhow::Result;
6use home::home_dir;
7
8use serde_derive::{Deserialize, Serialize};
9
10#[derive(Debug, Deserialize, Serialize)]
11pub struct Config {
12 pub notes_dir: String,
13 pub metadata_dir: String,
14 pub file_format: String,
15}
16
17impl Display for Config {
18 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
19 write!(
20 f,
21 "notes directory: {}\nmetadata directory: {}\nfile format: {}",
22 self.notes_dir, self.metadata_dir, self.file_format
23 )
24 }
25}
26
27pub enum WEnv {
28 Prod,
29 Test,
30}
31
32impl WEnv {
33 fn config_base_dir(&self) -> String {
34 match self {
35 Self::Prod => home_dir().unwrap().display().to_string(),
36 Self::Test => current_dir().unwrap().display().to_string(),
37 }
38 }
39
40 fn wikio_base_dir(&self) -> String {
41 match self {
42 Self::Prod => home_dir().unwrap().display().to_string(),
43 Self::Test => current_dir().unwrap().display().to_string(),
44 }
45 }
46
47 fn config_dir(&self) -> String {
48 match self {
49 Self::Prod => ".config/wiki-o".to_string(),
50 Self::Test => "test-dir/config".to_string(),
51 }
52 }
53
54 pub fn config(&self) -> Config {
55 match self {
56 Self::Prod => Config {
57 notes_dir: "wiki-o/notes".to_string(),
58 metadata_dir: "wiki-o/_metadata".to_string(),
59 file_format: String::from("md"),
60 },
61 Self::Test => Config {
62 notes_dir: "test-dir/notes".to_string(),
63 metadata_dir: "test-dir/_metadata".to_string(),
64 file_format: String::from("md"),
65 },
66 }
67 }
68
69 pub fn notes_abs_dir(&self) -> String {
70 format!("{}/{}", self.wikio_base_dir(), self.config().notes_dir)
71 }
72
73 pub fn metadata_abs_dir(&self) -> String {
74 format!("{}/{}", self.wikio_base_dir(), self.config().metadata_dir)
75 }
76}
77
78pub struct ContextWriter {
79 pub env: WEnv,
80}
81
82impl ContextWriter {
83 pub fn init(&self) -> Result<()> {
84 self.create_config_dir()?;
85 self.create_dir_if_not_exist()?;
86 Ok(())
87 }
88
89 fn create_config_dir(&self) -> Result<()> {
90 file::create_dir_if_not_exist(&format!(
91 "{}/{}",
92 self.env.config_base_dir(),
93 self.env.config_dir()
94 ))?;
95 Ok(())
96 }
97
98 fn create_dir_if_not_exist(&self) -> Result<()> {
99 file::create_dir_if_not_exist(&self.env.notes_abs_dir())?;
100 file::create_dir_if_not_exist(&self.env.metadata_abs_dir())?;
101 Ok(())
102 }
103}
104
105