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
mod build;
pub mod channel;
mod ci;
mod env;
pub mod err;
mod git;
use build::*;
use env::*;
use git::*;
use crate::ci::CIType;
use std::cell::RefCell;
use std::collections::HashMap;
use std::fs::File;
use std::io::Write;
use std::path::Path;
pub use err::{SdResult, ShadowError};
const SHADOW_RS: &str = "shadow.rs";
#[derive(Debug)]
pub struct Shadow {
f: File,
map: HashMap<ShadowConst, RefCell<ConstVal>>,
}
impl Shadow {
fn try_ci() -> CIType {
if let Some(c) = option_env!("GITLAB_CI") {
if c == "true" {
return CIType::Gitlab;
}
}
if let Some(c) = option_env!("GITHUB_ACTIONS") {
if c == "true" {
return CIType::Github;
}
}
CIType::None
}
pub fn build(src_path: String, out_path: String) -> SdResult<()> {
let ci_type = Self::try_ci();
let src_path = Path::new(src_path.as_str());
let out = {
let path = Path::new(out_path.as_str());
if !out_path.ends_with("/") {
path.join(format!("{}/{}", out_path, SHADOW_RS))
} else {
path.join(SHADOW_RS)
}
};
let mut map = Git::new(&src_path, ci_type);
for (k, v) in Project::new() {
map.insert(k, v);
}
for (k, v) in SystemEnv::new() {
map.insert(k, v);
}
let mut shadow = Shadow {
f: File::create(out)?,
map,
};
shadow.gen_const()?;
println!("shadow build success");
Ok(())
}
fn gen_const(&mut self) -> SdResult<()> {
self.write_header()?;
for (k, v) in self.map.clone() {
self.write_const(k, v)?;
}
Ok(())
}
fn write_header(&self) -> SdResult<()> {
let desc = r#"// Code generated by shadow-rs generator. DO NOT EDIT."#;
writeln!(&self.f, "{}\n\n", desc)?;
Ok(())
}
fn write_const(&mut self, shadow_const: ShadowConst, val: RefCell<ConstVal>) -> SdResult<()> {
let val = val.into_inner();
let desc = format!("// {}", val.desc);
let (t, v) = match val.t {
ConstType::OptStr => (ConstType::Str.to_string(), "".into()),
ConstType::Str => (ConstType::Str.to_string(), val.v),
};
let define = format!(
"pub const {} :{} = \"{}\";",
shadow_const.to_ascii_uppercase(),
t,
v
);
writeln!(&self.f, "{}", desc)?;
writeln!(&self.f, "{}\n", define)?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_build() -> SdResult<()> {
Shadow::build("./".into(), "./".into())?;
Ok(())
}
}