e_utils/
build.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
use crate::chrono::{china_now, Datelike as _, STANDARD_DATETIME_FORMAT};
use crate::{
  chrono::now,
  cmd::Cmd,
  fs::{_fs::AutoPath as _, write_utf8},
};
use std::path::Path;

/// 包信息结构体
#[derive(Debug)]
pub struct PackageInfo {
  /// 包名
  pub name: String,
  /// 版本
  pub version: String,
  /// 描述
  pub description: String,
  /// 作者
  pub authors: String,
  /// 主页
  pub homepage: String,
  /// 仓库
  pub repository: String,
}

impl PackageInfo {
  /// 生成版本信息
  pub fn comments(&self) -> String {
    format!(
      "版本: {}\n主页: {}\n仓库: {}\n作者: {}",
      self.version,
      self.homepage,
      self.repository,
      self.formatted_authors()
    )
  }
  /// 生成版权信息
  pub fn copyright(&self) -> String {
    format!(
      "版权所有 © {} {}",
      chrono::Local::now().year(),
      if self.authors.is_empty() {
        String::new()
      } else {
        self.formatted_authors()
      }
    )
  }
  /// 格式化作者信息
  pub fn formatted_authors(&self) -> String {
    self.authors.replace(':', ", ")
  }
}

/// 导出git历史
pub fn export_git_history(
  pkg_version: impl AsRef<str>,
  target: impl AsRef<Path>,
  is_china: bool,
) -> crate::AnyResult<()> {
  target.as_ref().auto_remove_file()?;
  let build_time = if is_china {
    china_now()
      .ok_or("获取时间失败")?
      .format(STANDARD_DATETIME_FORMAT)
  } else {
    now().format(STANDARD_DATETIME_FORMAT)
  };
  let tag_commits = git_tag_commits().unwrap_or_default();
  let version_info = format!(
    "当前版本号: {}\n\
      构建时间: {}\n\
      构建类型: {}\n\
      历史提交 :\n\n{}",
    pkg_version.as_ref(),
    build_time,
    if cfg!(debug_assertions) {
      "Debug"
    } else {
      "Release"
    },
    tag_commits,
  );
  write_utf8(&target.as_ref().to_path_buf(), &version_info, false, false)?;

  Ok(())
}

/// 获取git标签提交历史
pub fn git_tag_commits() -> crate::Result<String> {
  // 获取所有标签的提交历史
  let tag_commits = Cmd::new("git")
    .args([
      "log",
      "--simplify-by-decoration", // 只显示有标签的提交
      "--date=\"format-local:%Y-%m-%d %H:%M:%S\"",
      "--format=\"标识: %h\n标签: %D\n时间: %cd\n作者: %an <%ae>\n提交: %s\n\"",
    ])
    .output()
    .map(|output| output.stdout.to_string())
    .unwrap_or("获取失败".to_string());

  Ok(tag_commits)
}