Cách cấu hình Gitlab CI chỉ kiểm tra các file thay đổi với merge request

by khanhcd92
493 views

Chúng ta sẽ thường hay cấu hình chạy kiểm tra code quality cho tất các các nhánh và merge request trên Gitlab CI. Nhưng Gitlab runner job sẽ chạy scan toàn bộ source code nên sẽ mất thời gian đối với merge request. Ngoài ra đôi khi do source code cũ của khách hàng lỏm sẽ dẫn tới lúc nào merge request đó cũng sẽ bị failed.

Dưới đây là sample về Gitlab CI chạy python lint với cấu hình chạy cho nhánh develop và merge request.

pylint:
  stage: lint
  before_script:
    - mkdir -p public/badges public/lint
    - echo undefined > public/badges/$CI_JOB_NAME.score
    - pip install pylint-gitlab
  script:
    - pip install -r requirements.txt
    - pylint --rcfile=.pylintrc --exit-zero --output-format=text $(find -type f -name "*.py" ! -path "**/.venv/**") | tee /tmp/pylint.txt
    - sed -n 's/^Your code has been rated at \([-0-9.]*\)\/.*/\1/p' /tmp/pylint.txt > public/badges/$CI_JOB_NAME.score
    - pylint --exit-zero --output-format=pylint_gitlab.GitlabCodeClimateReporter $(find -type f -name "*.py" ! -path "**/.venv/**") > codeclimate.json
    - pylint --exit-zero --output-format=pylint_gitlab.GitlabPagesHtmlReporter $(find -type f -name "*.py" ! -path "**/.venv/**") > public/lint/index.html
  after_script:
    - anybadge --overwrite --label $CI_JOB_NAME --value=$(cat public/badges/$CI_JOB_NAME.score) --file=public/badges/$CI_JOB_NAME.svg 4=red 6=orange 8=yellow 10=green
    - |
      echo "Your score is: $(cat public/badges/$CI_JOB_NAME.score)"
  artifacts:
    paths:
      - public
    reports:
      codequality: codeclimate.json
    when: always
  only:
    - develop
    - merge_requests
  tags:
    - docker

Để giải quyết các vấn đề trên và có thể tập trung vào chất lượng code của các bạn member tốt hơn, chúng ta có thể tạo thêm 1 config mới cho merge request event. Với config mới chỉ cần kiểm tra code quality trên các file thay đổi là được.

pylint_merge_request:
  stage: lint
  before_script:
    - pip install pylint-gitlab
  script:
    - echo CI_COMMIT_SHA=${CI_COMMIT_SHA}
    - echo CI_MERGE_REQUEST_TARGET_BRANCH_NAME=${CI_MERGE_REQUEST_TARGET_BRANCH_NAME}
    - git fetch origin ${CI_MERGE_REQUEST_TARGET_BRANCH_NAME}
    - FILES=$(git diff --name-only ${CI_COMMIT_SHA} origin/${CI_MERGE_REQUEST_TARGET_BRANCH_NAME} | grep '\.py'$)
    - echo "Changed files are $FILES"
    - pip install -r requirements.txt
    - pylint --rcfile=.pylintrc --output-format=text $FILES | tee /tmp/pylint.txt
  only:
    - merge_requests
  tags:
    - docker

Hi vọng nó hữu ích với mọi người và có thể apply nó vào dự án của mình.

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.

You may also like