forked from getzola/zola
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinit.rs
289 lines (251 loc) · 9.88 KB
/
init.rs
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
use std::fs::{canonicalize, create_dir};
use std::path::Path;
use errors::{bail, Result};
use utils::fs::create_file;
use crate::prompt::{ask_bool, ask_url};
const CONFIG: &str = r#"
# The URL the site will be built for
base_url = "%BASE_URL%"
# Whether to automatically compile all Sass files in the sass directory
compile_sass = %COMPILE_SASS%
# Whether to build a search index to be used later on by a JavaScript library
build_search_index = %SEARCH%
[markdown]
# Whether to do syntax highlighting
# Theme can be customised by setting the `highlight_theme` variable to a theme supported by Zola
highlight_code = %HIGHLIGHT%
[extra]
# Put all your custom variables here
"#;
// canonicalize(path) function on windows system returns a path with UNC.
// Example: \\?\C:\Users\VssAdministrator\AppData\Local\Temp\new_project
// More details on Universal Naming Convention (UNC):
// https://en.wikipedia.org/wiki/Path_(computing)#Uniform_Naming_Convention
// So the following const will be used to remove the network part of the UNC to display users a more common
// path on windows systems.
// This is a workaround until this issue https://github.com/rust-lang/rust/issues/42869 was fixed.
const LOCAL_UNC: &str = "\\\\?\\";
// Given a path, return true if it is a directory and it doesn't have any
// non-hidden files, otherwise return false (path is assumed to exist)
pub fn is_directory_quasi_empty(path: &Path) -> Result<bool> {
if path.is_dir() {
let mut entries = match path.read_dir() {
Ok(entries) => entries,
Err(e) => {
bail!(
"Could not read `{}` because of error: {}",
path.to_string_lossy().to_string(),
e
);
}
};
// If any entry raises an error or isn't hidden (i.e. starts with `.`), we raise an error
if entries.any(|x| match x {
Ok(file) => !file
.file_name()
.to_str()
.expect("Could not convert filename to &str")
.starts_with('.'),
Err(_) => true,
}) {
return Ok(false);
}
return Ok(true);
}
Ok(false)
}
// Remove the unc part of a windows path
fn strip_unc(path: &Path) -> String {
let path_to_refine = path.to_str().unwrap();
path_to_refine.trim_start_matches(LOCAL_UNC).to_string()
}
pub fn create_new_project(name: &str, force: bool) -> Result<()> {
let path = Path::new(name);
// Better error message than the rust default
if path.exists() && !is_directory_quasi_empty(path)? && !force {
if name == "." {
bail!("The current directory is not an empty folder (hidden files are ignored).");
} else {
bail!(
"`{}` is not an empty folder (hidden files are ignored).",
path.to_string_lossy().to_string()
)
}
}
console::info("Welcome to Zola!");
console::info("Please answer a few questions to get started quickly.");
console::info("Any choices made can be changed by modifying the `config.toml` file later.");
let base_url = ask_url("> What is the URL of your site?", "https://example.com")?;
let compile_sass = ask_bool("> Do you want to enable Sass compilation?", true)?;
let highlight = ask_bool("> Do you want to enable syntax highlighting?", false)?;
let search = ask_bool("> Do you want to build a search index of the content?", false)?;
let config = CONFIG
.trim_start()
.replace("%BASE_URL%", &base_url)
.replace("%COMPILE_SASS%", &format!("{}", compile_sass))
.replace("%SEARCH%", &format!("{}", search))
.replace("%HIGHLIGHT%", &format!("{}", highlight));
populate(path, compile_sass, &config)?;
println!();
console::success(&format!(
"Done! Your site was created in {}",
strip_unc(&canonicalize(path).unwrap())
));
println!();
console::info(
"Get started by moving into the directory and using the built-in server: `zola serve`",
);
println!("Visit https://www.getzola.org for the full documentation.");
Ok(())
}
fn populate(path: &Path, compile_sass: bool, config: &str) -> Result<()> {
if !path.exists() {
create_dir(path)?;
}
create_file(&path.join("config.toml"), config)?;
create_dir(path.join("content"))?;
create_dir(path.join("templates"))?;
create_dir(path.join("static"))?;
create_dir(path.join("themes"))?;
if compile_sass {
create_dir(path.join("sass"))?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::env::temp_dir;
use std::fs::{create_dir, remove_dir, remove_dir_all};
use std::path::Path;
#[test]
fn init_empty_directory() {
let mut dir = temp_dir();
dir.push("test_empty_dir");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
create_dir(&dir).expect("Could not create test directory");
let allowed = is_directory_quasi_empty(&dir)
.expect("An error happened reading the directory's contents");
remove_dir(&dir).unwrap();
assert!(allowed);
}
#[test]
fn init_non_empty_directory() {
let mut dir = temp_dir();
dir.push("test_non_empty_dir");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
create_dir(&dir).expect("Could not create test directory");
let mut content = dir.clone();
content.push("content");
create_dir(&content).unwrap();
let allowed = is_directory_quasi_empty(&dir)
.expect("An error happened reading the directory's contents");
remove_dir(&content).unwrap();
remove_dir(&dir).unwrap();
assert!(!allowed);
}
#[test]
fn init_quasi_empty_directory() {
let mut dir = temp_dir();
dir.push("test_quasi_empty_dir");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
create_dir(&dir).expect("Could not create test directory");
let mut git = dir.clone();
git.push(".git");
create_dir(&git).unwrap();
let allowed = is_directory_quasi_empty(&dir)
.expect("An error happened reading the directory's contents");
remove_dir(&git).unwrap();
remove_dir(&dir).unwrap();
assert!(allowed);
}
#[test]
fn populate_existing_directory() {
let mut dir = temp_dir();
dir.push("test_existing_dir");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
create_dir(&dir).expect("Could not create test directory");
populate(&dir, true, "").expect("Could not populate zola directories");
assert!(dir.join("config.toml").exists());
assert!(dir.join("content").exists());
assert!(dir.join("templates").exists());
assert!(dir.join("static").exists());
assert!(dir.join("themes").exists());
assert!(dir.join("sass").exists());
remove_dir_all(&dir).unwrap();
}
#[test]
fn populate_non_existing_directory() {
let mut dir = temp_dir();
dir.push("test_non_existing_dir");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
populate(&dir, true, "").expect("Could not populate zola directories");
assert!(dir.exists());
assert!(dir.join("config.toml").exists());
assert!(dir.join("content").exists());
assert!(dir.join("templates").exists());
assert!(dir.join("static").exists());
assert!(dir.join("themes").exists());
assert!(dir.join("sass").exists());
remove_dir_all(&dir).unwrap();
}
#[test]
fn populate_without_sass() {
let mut dir = temp_dir();
dir.push("test_wihout_sass_dir");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
create_dir(&dir).expect("Could not create test directory");
populate(&dir, false, "").expect("Could not populate zola directories");
assert!(!dir.join("sass").exists());
remove_dir_all(&dir).unwrap();
}
#[test]
fn strip_unc_test() {
let mut dir = temp_dir();
dir.push("new_project1");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
create_dir(&dir).expect("Could not create test directory");
if cfg!(target_os = "windows") {
let stripped_path = strip_unc(&canonicalize(Path::new(&dir)).unwrap());
assert!(same_file::is_same_file(Path::new(&stripped_path), &dir).unwrap());
assert!(!stripped_path.starts_with(LOCAL_UNC), "The path was not stripped.");
} else {
assert_eq!(
strip_unc(&canonicalize(Path::new(&dir)).unwrap()),
canonicalize(Path::new(&dir)).unwrap().to_str().unwrap().to_string()
);
}
remove_dir_all(&dir).unwrap();
}
// If the following test fails it means that the canonicalize function is fixed and strip_unc
// function/workaround is not anymore required.
// See issue https://github.com/rust-lang/rust/issues/42869 as a reference.
#[test]
#[cfg(target_os = "windows")]
fn strip_unc_required_test() {
let mut dir = temp_dir();
dir.push("new_project2");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
create_dir(&dir).expect("Could not create test directory");
let canonicalized_path = canonicalize(Path::new(&dir)).unwrap();
assert!(same_file::is_same_file(Path::new(&canonicalized_path), &dir).unwrap());
assert!(canonicalized_path.to_str().unwrap().starts_with(LOCAL_UNC));
remove_dir_all(&dir).unwrap();
}
}