มาทำ api ไว้เช็กโค้ด version ล่าสุดของ commit git กัน
เวลาที่เรา Develop โค้ดกัน เราจะแน่ใจได้ไงว่าโค้ดของเราที่ Deploy ไปบน server เป็นโค้ดล่าสุดจริงๆ เกิดวันใดวันนึง jenkins ตาย, gitlab ci/cd ตาย ฯลฯ ก็อาจไม่ Deploy ให้เราเลย สิ่งที่เราทำได้ตอนนี้ก็คือเช็ก feature ที่เราส่งไป deploy ว่ามันทำงานได้ไหม ก็ต้องมาเสียเวลาเช็กอีก แต่จะดีกว่าไหมถ้าเราสามารถเช็กจาก commit ล่าสุดได้
ในบทความนี้จะเอา date ของ commit ล่าสุดแสดงมานะครับ
สร้างโปรเจค
mkdir project
cd project
ลง package
npm init -y
npm install express
สร้างไฟล์ index.js
const child_process = require('child_process')const express = require("express")const app = express()
app.get('/api/version', (req, res) => { child_process.exec('git log -1 --format=%cd', (err, stdout) => { res.send(stdout) })})app.listen(7777, () => console.info("Server running with http://localhost:7777"))
git log -1 — format=%cd เป็น command ของ git เอาไว้เช็ก date ของ commit ล่าสุด
git log — format=”%H” -n 1 หากจะดู commit ล่าสุดก็ใช้คำสั่งนี้ได้
run server
node index.js
commit code
git initgit add index.jsgit commit -m "[Add] index.js"
http://localhost:7777/api/version
Sun Feb 28 23:51:31 2021 +0700
ลอง commit ใหม่
git add package.jsongit commit -m "[Add] package.json"
Sun Feb 28 23:55:06 2021 +0700
จะเห็นว่า date มีการเปลี่ยนเป็นของ commit ล่าสุด
ถ้าหากมีวิธีอื่นก็แนะนำกันได้นะครับ