目的

達(dá)成的目標(biāo).png
實現(xiàn)思路
(第一次接觸OSS和SemaphoreCI,第一反應(yīng)是一臉懵逼,。。。。。)先了解SemaphoreCI和阿里云OSS是什么吧!
======== 實現(xiàn)腳本(上傳文件到哪里,怎么上傳,如何控制上傳文件的數(shù)量大小,) ======== 本地如何運行腳本 ======== CI上部署
實現(xiàn)路徑
利用OSS的官方文檔查看API并提取目標(biāo)API(如本地上傳文件API)實現(xiàn)腳本。阿里云OSS中包含各種API并支持各種編程語言,可根據(jù)需求選擇(本次我們使用的是nodejs)。具體代碼如下所示:
const OSS = require('ali-oss');
const fs = require('fs');
const child_process = require('child_process');
// 目標(biāo)文件的相對路徑
const remoteResourcePath = './dist';
// OSS配置
const client = new OSS({
region: 'oss-cn-shenzhen',
accessKeyId: process.env.ALIYUN_ACCESS_KEY_ID,
accessKeySecret: process.env.ALIYUN_ACCESS_KEY_SECRET,
bucket: 'xunlugaokao-school',
});
client.useBucket('xunlugaokao-school');
function adjustUploadFilesOrder(filesArray) {
// 上傳所有文件
...
}
function uploadStaticResource(filesArray){
const version = child_process.execSync("git describe --tag",{shell:true,encoding:"utf8"}).replace(/[\r\n]/g,"");
filesArray && filesArray.forEach(e => {
const stat = fs.lstatSync(`./dist/${e}`);
// e是文件還是文件夾
if(stat.isDirectory()) {
// 讀static中的文件并依次上傳
const files = fs.readdirSync(`./dist/${e}`);
files.forEach(item => {
// 文件加上版本號
const newName = item.split('.').splice(-1).shift() === 'html'? `${item}`:`${version}/${e}/${item}`;
client.put(newName,`${remoteResourcePath}/${e}/${item}`);
})
}else {
const newName = e.split('.').splice(-1).shift() === 'html'? `${e}`:`${version}/${e}`;
client.put(newName,`${remoteResourcePath}/${e}`);
}
})
client.put(`index_${version}.html`,`${remoteResourcePath}/index.html`);
}
function deploy() {
try {
const filesArray = fs.readdirSync(remoteResourcePath);
const files = adjustUploadFilesOrder(filesArray)
uploadStaticResource(files);
} catch (err) {
console.log (err);
}
}
deploy()
腳本實現(xiàn)后,在本地運行驗證腳本成功。。。。
package.json中配置scripts命令,npm run deploy即可運行腳本。
"deploy": "node deploy.js"
進(jìn)入semaphoreCI官網(wǎng),semaphoreCI是一個可以幫助你自動運行設(shè)置的命令的“小機(jī)器人”,添加project后按照文檔指示添加你需要運行的命令。
CI部署,參考deploy your application實現(xiàn)運行腳本文件
感想
最開始的時候,是在是不知道怎么下手,完成后回頭看呢,...。。。不過如此。。。。。
- 遇到問題,首先應(yīng)該明確目的,明確后一步一步來就沒想象中的那么難。
- 多讀官方文檔,仔細(xì),認(rèn)真。