You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

166 lines
5.4KB

  1. use std::fs::{canonicalize, create_dir};
  2. use std::path::Path;
  3. use errors::Result;
  4. use utils::fs::create_file;
  5. use console;
  6. use prompt::{ask_bool, ask_url};
  7. const CONFIG: &str = r#"
  8. # The URL the site will be built for
  9. base_url = "%BASE_URL%"
  10. # Whether to automatically compile all Sass files in the sass directory
  11. compile_sass = %COMPILE_SASS%
  12. # Whether to do syntax highlighting
  13. # Theme can be customised by setting the `highlight_theme` variable to a theme supported by Zola
  14. highlight_code = %HIGHLIGHT%
  15. # Whether to build a search index to be used later on by a JavaScript library
  16. build_search_index = %SEARCH%
  17. [extra]
  18. # Put all your custom variables here
  19. "#;
  20. // Given a path, return true if it is a directory and it doesn't have any
  21. // non-hidden files, otherwise return false (path is assumed to exist)
  22. pub fn is_directory_quasi_empty(path: &Path) -> Result<bool> {
  23. if path.is_dir() {
  24. let mut entries = match path.read_dir() {
  25. Ok(entries) => entries,
  26. Err(e) => {
  27. bail!(
  28. "Could not read `{}` because of error: {}",
  29. path.to_string_lossy().to_string(),
  30. e
  31. );
  32. }
  33. };
  34. // If any entry raises an error or isn't hidden (i.e. starts with `.`), we raise an error
  35. if entries.any(|x| match x {
  36. Ok(file) => !file
  37. .file_name()
  38. .to_str()
  39. .expect("Could not convert filename to &str")
  40. .starts_with('.'),
  41. Err(_) => true,
  42. }) {
  43. return Ok(false);
  44. }
  45. return Ok(true);
  46. }
  47. Ok(false)
  48. }
  49. pub fn create_new_project(name: &str) -> Result<()> {
  50. let path = Path::new(name);
  51. // Better error message than the rust default
  52. if path.exists() && !is_directory_quasi_empty(&path)? {
  53. if name == "." {
  54. bail!("The current directory is not an empty folder (hidden files are ignored).");
  55. } else {
  56. bail!(
  57. "`{}` is not an empty folder (hidden files are ignored).",
  58. path.to_string_lossy().to_string()
  59. )
  60. }
  61. }
  62. console::info("Welcome to Zola!");
  63. console::info("Please answer a few questions to get started quickly.");
  64. console::info("Any choices made can be changed by modifying the `config.toml` file later.");
  65. let base_url = ask_url("> What is the URL of your site?", "https://example.com")?;
  66. let compile_sass = ask_bool("> Do you want to enable Sass compilation?", true)?;
  67. let highlight = ask_bool("> Do you want to enable syntax highlighting?", false)?;
  68. let search = ask_bool("> Do you want to build a search index of the content?", false)?;
  69. let config = CONFIG
  70. .trim_start()
  71. .replace("%BASE_URL%", &base_url)
  72. .replace("%COMPILE_SASS%", &format!("{}", compile_sass))
  73. .replace("%SEARCH%", &format!("{}", search))
  74. .replace("%HIGHLIGHT%", &format!("{}", highlight));
  75. create_dir(path)?;
  76. create_file(&path.join("config.toml"), &config)?;
  77. create_dir(path.join("content"))?;
  78. create_dir(path.join("templates"))?;
  79. create_dir(path.join("static"))?;
  80. create_dir(path.join("themes"))?;
  81. if compile_sass {
  82. create_dir(path.join("sass"))?;
  83. }
  84. println!();
  85. console::success(&format!("Done! Your site was created in {:?}", canonicalize(path).unwrap()));
  86. println!();
  87. console::info(
  88. "Get started by moving into the directory and using the built-in server: `zola serve`",
  89. );
  90. println!("Visit https://www.getzola.org for the full documentation.");
  91. Ok(())
  92. }
  93. #[cfg(test)]
  94. mod tests {
  95. use super::*;
  96. use std::env::temp_dir;
  97. use std::fs::{create_dir, remove_dir, remove_dir_all};
  98. #[test]
  99. fn init_empty_directory() {
  100. let mut dir = temp_dir();
  101. dir.push("test_empty_dir");
  102. if dir.exists() {
  103. remove_dir_all(&dir).expect("Could not free test directory");
  104. }
  105. create_dir(&dir).expect("Could not create test directory");
  106. let allowed = is_directory_quasi_empty(&dir)
  107. .expect("An error happened reading the directory's contents");
  108. remove_dir(&dir).unwrap();
  109. assert_eq!(true, allowed);
  110. }
  111. #[test]
  112. fn init_non_empty_directory() {
  113. let mut dir = temp_dir();
  114. dir.push("test_non_empty_dir");
  115. if dir.exists() {
  116. remove_dir_all(&dir).expect("Could not free test directory");
  117. }
  118. create_dir(&dir).expect("Could not create test directory");
  119. let mut content = dir.clone();
  120. content.push("content");
  121. create_dir(&content).unwrap();
  122. let allowed = is_directory_quasi_empty(&dir)
  123. .expect("An error happened reading the directory's contents");
  124. remove_dir(&content).unwrap();
  125. remove_dir(&dir).unwrap();
  126. assert_eq!(false, allowed);
  127. }
  128. #[test]
  129. fn init_quasi_empty_directory() {
  130. let mut dir = temp_dir();
  131. dir.push("test_quasi_empty_dir");
  132. if dir.exists() {
  133. remove_dir_all(&dir).expect("Could not free test directory");
  134. }
  135. create_dir(&dir).expect("Could not create test directory");
  136. let mut git = dir.clone();
  137. git.push(".git");
  138. create_dir(&git).unwrap();
  139. let allowed = is_directory_quasi_empty(&dir)
  140. .expect("An error happened reading the directory's contents");
  141. remove_dir(&git).unwrap();
  142. remove_dir(&dir).unwrap();
  143. assert_eq!(true, allowed);
  144. }
  145. }