上一篇我们在发布时记录一个变量时间戳,与用户本地的变量进行比较确定远端是否有更新; 但是我们能展示出到底更新了什么功能,对应的git仓库哪个版本,不要服务器参与,那么我们该如何实现呢?
这时我们意识到,因为我们是根据分支控制发布环境的的;分支commit时的message就是此次更新的内容; 这时我们拿到commit的message不就可以了;我们用的是gitlab管理项目代码,所以我们需要开始研究gitlab的api
这里我们只是要获取最新的一个commit提交
所以在.gitlab-ci.yml
中新增一个stage
stages:
- commitLog // 提交log
- build
- deploy
- notify
# 写入commit变更
write_commit_info:
image: node:16.5.0-buster
stage: commitLog
artifacts:
untracked: true
cache:
paths:
- ./build/script/commit.json
script:
- curl --header "PRIVATE-TOKEN:$ACCESS_TOKEN" "https://git.xxx.com/api/v4/projects/{项目id}/repository/commits/$CI_COMMIT_BRANCH" > ./build/script/commit.json
- cat ./build/script/commit.json
rules:
- if: $CI_COMMIT_BRANCH == "dev" || $CI_COMMIT_BRANCH == "master" || $CI_COMMIT_BRANCH == "release"
这$
开头表示是变量,$CI
开头的是预定义变量,前面$ACCESS_TOKEN
是自己定义的变量,需要在自己的项目仓库下-settings-CI/CD-Variables
点击expand,Add variable
调试时,可以把变量替换成固定值,在终端中输入就可看到结果;也可以直接将代码推倒gitlab上,点击查看CI/CD-Pipelines-running
能看到四个stage;
点击第一个任务,就可以看到具体的执行过程喝打印的log了
经过上述步骤,我们最终获取了最新的当前分支的commit信息并写入到了./build/script/commit.json
中;
接下来,我们在下一步stage的build脚本中读取commit.json
中要用的字段; 结合上一篇文档,我们build/script/buildConf.ts
中设置version信息时加入commit中的字段即可;
import CommitJson from './commit.json';
// 常量定义 /build/constant.ts中
export const OUTPUT_DIR = 'dir'
export const OUTPUT_GLOBAL_VERSION = '_TC_ADMIN_VERSION'
export const OUTPUT_VERSION_FILE_NAME = '_version.js';
![image.png](https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/057cd8589a9a4307bc005827216f21d0~tplv-k3u1fbpfcp-watermark.image?)
function getRootPath(...dir: string[]) {
return path.resolve(process.cwd(), ...dir);
}
function createConfig() {
// 其他代码省略 OUTPUT_DIR = 'dist'
fs.mkdirp(getRootPath(OUTPUT_DIR));
// add version
const windowVersion = `window.${OUTPUT_GLOBAL_VERSION}`;
// 本次新增
const { short_id, message, web_url, author_name }: any = CommitJson;
const windowVersionConf = `${windowVersion}=${JSON.stringify({
version: Date.now(),
short_id,
message,
web_url,
author_name,
})};
Object.freeze(${windowVersion});
Object.defineProperty(window, "${OUTPUT_GLOBAL_VERSION}", {
configurable: false,
writable: false,
});
`.replace(/\s/g, '');
writeFileSync(getRootPath(`${OUTPUT_DIR}/${OUTPUT_VERSION_FILE_NAME}`), windowVersionConf);
}
这样我们在全局的window._TC_ADMIN_VERSION
上就不仅有version
了,还有message
等其他信息;这样我们在elert时就可以做更丰富的内容了
const openNotification = ({ author_name, message }) => {
const key = `open${Date.now()}`;
notification.open({
message: '更新提醒',
description: `${author_name}新提交【${message}】,点击按钮获取最新版本`,
duration: null,
placement: 'topLeft',
btn: h(
Button,
{
type: 'primary',
color: 'warning',
size: 'small',
onClick: () => {
notification.close(key);
window.location.reload();
},
},
'确定刷新'
),
key,
onClose: close,
});
};
自此结束!