1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
use std::{
    any::type_name,
    collections::BTreeMap,
    fmt::{Debug, Formatter},
    fs::read_to_string,
    path::{Path, PathBuf},
};

use serde::{
    de::{MapAccess, Visitor},
    Deserialize, Deserializer, Serialize, Serializer,
};
use toml::Value;

use xcell_errors::{
    for_3rd::{
        build_glob_set, file_watcher, read_map_next_extra, read_map_next_key_lowercase, read_map_next_value, GlobSet,
        StreamExt, WalkDir,
    },
    XError, XResult,
};
use xcell_types::{default_deserialize, EnumerateDescription, TypeMetaInfo};

use crate::{
    config::unity::UnityCodegen,
    utils::{get_relative, valid_file},
    XTable, XTableKind,
};

pub use self::{
    project::ProjectConfig,
    table::{TableConfig, TableLineMode},
    unity::UnityBinaryConfig,
};

pub mod merge_rules;
mod project;
mod table;
pub mod unity;

/// 默认的全局项目设置
pub const PROJECT_CONFIG: &str = include_str!("ProjectConfig.toml");

pub struct WorkspaceManager {
    pub config: ProjectConfig,
    pub glob_pattern: GlobSet,
    pub file_mapping: BTreeMap<PathBuf, XTable>,
    pub enum_mapping: BTreeMap<String, EnumerateDescription>,
}

default_deserialize![ProjectConfig, TableConfig, TableLineMode];

impl Debug for WorkspaceManager {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WorkspaceManager")
            .field("workspace", &self.config.root.display())
            .field("config", &self.config)
            .finish()
    }
}

impl WorkspaceManager {
    /// 设置工作目录
    pub fn new<P>(workspace: P) -> XResult<Self>
    where
        P: AsRef<Path>,
    {
        let input = workspace.as_ref();
        let root = input.canonicalize()?;
        if !root.is_dir() {
            return Err(XError::table_error(format!("{} 不是目录名", input.display())));
        }
        let config = ProjectConfig::new(&root);
        let glob_pattern = build_glob_set(&config.include).unwrap();
        Ok(Self { config, glob_pattern, file_mapping: Default::default(), enum_mapping: Default::default() })
    }
    /// 首次加载目录
    pub async fn first_walk(&mut self) -> XResult<()> {
        let glob = build_glob_set(&self.config.include).result(|e| log::error!("{e}"))?;
        let mut entries = WalkDir::new(&self.config.root);
        loop {
            match entries.next().await {
                Some(Ok(o)) if valid_file(&o) => {
                    let file = o.path();
                    let normed = self.get_relative(&file)?;
                    if glob.is_match(&normed) {
                        log::info!("首次加载: {}", normed.display());
                        self.update_file(&file)
                    }
                }
                None => break,
                _ => continue,
            }
        }
        self.link_enumerate();
        self.write_unity()?;
        Ok(())
    }
    pub async fn watcher(&mut self) -> XResult<()> {
        let mut watcher = file_watcher(&self.config.root)?;
        loop {
            match watcher.next().await {
                Some(Ok(o)) => {
                    log::trace!("文件变更: {:?}", o);
                }
                None => break,
                _ => continue,
            }
        }
        Ok(())
    }
}

impl WorkspaceManager {
    /// path 需要是绝对路径
    pub fn update_file(&mut self, file: &Path) {
        if let Err(e) = self.try_update_file(file) {
            log::error!("{e}")
        }
    }
    pub fn try_update_file(&mut self, file: &Path) -> XResult<()> {
        let table = XTable::load_file(file, &self.config)?;
        if let XTableKind::Enumerate(e) = &table.data {
            let mut mapping = BTreeMap::default();
            for (key, item) in &e.data {
                mapping.insert(key.clone(), item.id.clone());
            }
            let ed = EnumerateDescription {
                integer: e.id_type,
                typing: table.name.clone(),
                // TODO
                default: "".to_string(),
                mapping,
            };
            self.insert_enum_mapping(ed)
        }
        self.file_mapping.insert(file.to_path_buf(), table);
        Ok(())
    }
    pub fn write_unity(&self) -> XResult<()> {
        for table in self.file_mapping.values() {
            table.config.unity.ensure_path(&self.config.root)?;
            table.config.unity.write_class(table, &self.config.root)?;
            table.config.unity.write_binary(table, &self.config.root)?;
            table.config.unity.write_data_contract(table, &self.config.root)?;
        }
        self.config.unity.write_manager(&self.collect_merged(), &self.config.root, &self.config.version)?;
        Ok(())
    }
    pub fn insert_enum_mapping(&mut self, define: EnumerateDescription) {
        self.enum_mapping.insert(define.typing.clone(), define);
    }
}