ช่วงนี้ต้องมาเขียน code บ่อยขึ้น ประกอบกับช่วงก่อนหน้านี้ covid ครึ่งปีแรก ไปนั่งทำ lab owasp top 10 เล่น พอมีเวลาก็เขียน go project ไว้ใช้งานเล่นด้วย พยายามเขียน unit test ให้ครอบคลุมไปด้วยทุกครั้ง และทุกครั้งที่ commit Sonarcloud.io จะ scan code ของเรา ว่า
Security เป็นยังไง Reliability เป็นไงบ้าง Code Smells เป็นไงบ้าง ใช้เวลาแก้เท่าไหร่ Coverage Unit Tests เท่าไหร่
ทั้งหมดนี่ ฟรี!! สำหรับ public repo และเสียเงินสำหรับ private repo
หลังจากนั้นเราไปที่ github repo ของเรา แล้วเลือกที่ menu setting เพื่อทำการตั้งค่า Sonarcloud.io token key
โดยเจ้า sonarcloud token key เนี่ยเราจะหาได้จาก ตามรูปเลย
ตอนนี้ โครงสร้าง repo ของเราจะเป็นประมาณนี้
.├── Readme.md├── conf├── database├── docker-compose.yml├── redis└── services
โดย code ที่เราจะทำการ scan จะอยู่ใน services directory
ต่อไปเราจะไปทำการสร้าง github action ขึ้นมา โดยจะให้ทำการ ลง golang และทำการ run test coverage ใน services ให้ได้ออกมาเป็น coverage.out และ report.json เพื่อนำไปใช้ใน Sonarcloud.io กัน
โดยเราจะสร้างไว้ที่ .github/workflows โดยผมมีการ debug ดู path file ไว้ที่ fix code coverage paths ว่าถูกต้องไหม
name: Buildon:push:branches:- mainpull_request:types: [opened, synchronize, reopened]jobs:sonarcloud:name: SonarCloudruns-on: ubuntu-lateststeps:- name: Setup golanguses: actions/setup-go@v2with:go-version: '^1.16.5'- name: Check out code into the Go module directoryuses: actions/checkout@v2- name: Get dependenciesrun: |cd ./services && go mod tidy- name: Go Run Testrun: |cd ./services && go test "./..." -coverprofile="coverage.out" -covermode=count -json > report.json- name: fix code coverage pathsworking-directory: ./servicesrun: |pwdls -la- name: SonarCloud Scanuses: SonarSource/sonarcloud-github-action@masterwith:projectBaseDir: ./servicesenv:GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if anySONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
จากนั้น จะไปสร้าง config ให้ Sonarcloud.io ใน services ชื่อว่า sonar-project.properties เพื่อตั้งค่า project ของเรา และกำหนด inclusions และ exclusions file ที่จะทำการ scan
sonar.projectKey=aofiee_golang-clean-architecturesonar.organization=aofieesonar.sources=.sonar.exclusions=**/*_test.go,**/vendor/**,**/testdata/*,**/*.html,**/mocks/*.gosonar.tests=.sonar.test.inclusions=**/*_test.gosonar.test.exclusions=**/vendor/**,**/mocks/*.gosonar.go.coverage.reportPaths=coverage.outsonar.go.tests.reportPaths=report.json
หลังจากนั้นเราทำการ commit code และ push ขึ้นไปที่ branch main ระบบจะทำการ scan code และ แสดง report ออกมาดังตัวอย่าง
โดย Sonarcloud.io จะทำการ แสกนให้เราทุก commit ก่อนทำการ merge ลง master
Quick Links
Legal Stuff