main.rs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. use minify_html::{minify, Cfg};
  2. use scraper::{Html, Selector};
  3. use std::fs::{read, write};
  4. use std::path::{Path, PathBuf};
  5. use std::error::Error;
  6. use std::fmt;
  7. #[derive(Debug)]
  8. struct HtmlProcessorError(String);
  9. impl fmt::Display for HtmlProcessorError {
  10. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  11. write!(f, "HtmlProcessorError: {}", self.0)
  12. }
  13. }
  14. impl Error for HtmlProcessorError {}
  15. type Result<T> = std::result::Result<T, Box<dyn Error>>;
  16. /// 压缩HTML文件
  17. pub fn minify_html(input_path: &str) -> Result<PathBuf> {
  18. let input_path_obj = Path::new(input_path);
  19. let file_stem = input_path_obj.file_stem()
  20. .and_then(|s| s.to_str())
  21. .ok_or_else(|| HtmlProcessorError("Invalid input file name".into()))?;
  22. let output_path = input_path_obj
  23. .parent()
  24. .map(|p| p.join(format!("{}.min.html", file_stem)))
  25. .unwrap_or_else(|| PathBuf::from(format!("{}.min.html", file_stem)));
  26. let code = read(input_path)?;
  27. let mut cfg = Cfg::new();
  28. cfg.do_not_minify_doctype = true;
  29. cfg.ensure_spec_compliant_unquoted_attribute_values = true;
  30. cfg.keep_closing_tags = true;
  31. cfg.keep_html_and_head_opening_tags = true;
  32. cfg.keep_spaces_between_attributes = true;
  33. cfg.keep_comments = false;
  34. cfg.keep_input_type_text_attr = true;
  35. cfg.keep_ssi_comments = false;
  36. cfg.minify_css = true;
  37. cfg.minify_js = true;
  38. cfg.remove_bangs = false;
  39. cfg.remove_processing_instructions = false;
  40. let minified = minify(&code, &cfg);
  41. write(&output_path, minified)?;
  42. Ok(output_path)
  43. }
  44. /// 获取外部资源内容
  45. fn fetch_external_resource(url: &str) -> Result<String> {
  46. let client = reqwest::blocking::Client::builder()
  47. .user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
  48. .build()?;
  49. let resp = client.get(url).send()?;
  50. if !resp.status().is_success() {
  51. eprintln!("Warning: Failed to fetch {}: {}", url, resp.status());
  52. return Err(Box::new(HtmlProcessorError(format!("Failed to fetch {}", url))));
  53. }
  54. Ok(resp.text()?)
  55. }
  56. /// 内联所有外部资源
  57. pub fn all_in_one(input_path: &str) -> Result<PathBuf> {
  58. let input_path_obj = Path::new(input_path);
  59. let file_stem = input_path_obj.file_stem()
  60. .and_then(|s| s.to_str())
  61. .ok_or_else(|| HtmlProcessorError("Invalid input file name".into()))?;
  62. let output_path = input_path_obj
  63. .parent()
  64. .map(|p| p.join(format!("{}.allinone.html", file_stem)))
  65. .unwrap_or_else(|| PathBuf::from(format!("{}.allinone.html", file_stem)));
  66. let html_content = read(input_path)?;
  67. let html_str = String::from_utf8_lossy(&html_content);
  68. let document = Html::parse_document(&html_str);
  69. // 保留原始HTML结构,只替换特定标签内容
  70. let mut processed_html = html_str.to_string();
  71. // 处理script标签
  72. let script_selector = Selector::parse("script[src]").unwrap();
  73. for script in document.select(&script_selector) {
  74. if let Some(src) = script.value().attr("src") {
  75. if src.starts_with("http") {
  76. match fetch_external_resource(src) {
  77. Ok(content) => {
  78. let original = script.html();
  79. let replacement = format!("<script type=\"{}\"{}>{}</script>",
  80. script.value().attr("type").unwrap_or(""),
  81. script.value().attrs()
  82. .filter(|(name, _)| *name != "src" && *name != "type")
  83. .map(|(name, value)| format!(" {}=\"{}\"", name, value))
  84. .collect::<String>(),
  85. content);
  86. processed_html = processed_html.replace(&original, &replacement);
  87. },
  88. Err(e) => {
  89. eprintln!("Warning: Could not inline {}: {}", src, e);
  90. }
  91. }
  92. }
  93. }
  94. }
  95. // 处理link标签
  96. let link_selector = Selector::parse("link[rel=stylesheet]").unwrap();
  97. for link in document.select(&link_selector) {
  98. if let Some(href) = link.value().attr("href") {
  99. if href.starts_with("http") {
  100. match fetch_external_resource(href) {
  101. Ok(content) => {
  102. let original = link.html();
  103. let replacement = format!("<style type=\"text/css\"{}>{}</style>",
  104. link.value().attrs()
  105. .filter(|(name, _)| *name != "href" && *name != "rel")
  106. .map(|(name, value)| format!(" {}=\"{}\"", name, value))
  107. .collect::<String>(),
  108. content);
  109. processed_html = processed_html.replace(&original, &replacement);
  110. },
  111. Err(e) => {
  112. eprintln!("Warning: Could not inline {}: {}", href, e);
  113. }
  114. }
  115. }
  116. }
  117. }
  118. write(&output_path, processed_html)?;
  119. Ok(output_path)
  120. }
  121. fn main() {
  122. if std::env::args().len() < 2 {
  123. eprintln!("Usage: {} <path_to_html_file>", std::env::args().next().unwrap());
  124. return;
  125. }
  126. let input_path = std::env::args().nth(1).expect("Expected a path to an HTML file");
  127. // 1. 生成min.html
  128. match minify_html(&input_path) {
  129. Ok(minified_path) => {
  130. println!("Minified HTML written to {}", minified_path.display());
  131. },
  132. Err(e) => eprintln!("Error minifying HTML: {}", e),
  133. }
  134. // 2. 生成allinone.html
  135. match all_in_one(&input_path) {
  136. Ok(all_in_one_path) => {
  137. println!("All-in-one HTML written to {}", all_in_one_path.display());
  138. // 3. 生成allinone.min.html
  139. match minify_html(all_in_one_path.to_str().unwrap()) {
  140. Ok(minified_path) => {
  141. println!("Minified all-in-one HTML written to {}", minified_path.display());
  142. },
  143. Err(e) => eprintln!("Error minifying all-in-one HTML: {}", e),
  144. }
  145. },
  146. Err(e) => eprintln!("Error creating all-in-one HTML: {}", e),
  147. }
  148. }