package com.freeleaps.devops

class CommitMessageLinter {
  def steps
  private defaultRule = 'com/freeleaps/devops/builtins/commitlint/default.js'

  CommitMessageLinter(steps) {
    this.steps = steps
  }

  def lint(configurations) {
    def rules = ''
    steps.log.info("Commit Message Linter","Check if there has custom commit lint rules specified...")

    if (configurations.commitLintRules != null && !configurations.commitLintRules.isEmpty()) {
      steps.log.info("Commit Message Linter","Custom commit lint rules found, using custom rules files: ${configurations.commitLintRules}")
      rules = configurations.commitLintRules
    } else {
      steps.dir(steps.env.workroot) {
        steps.log.info("Commit Message Linter","No custom commit lint rules found, using built-in rules at: ${defaultRule}")
        steps.writeFile file: '.commitlintrc.js', text: steps.libraryResource(defaultRule)
        steps.log.info("Commit Message Linter","Built-in commit lint rules requires @commitlint/config-angular, ready to install it...")
        steps.sh "npm install -g @commitlint/config-angular"
      }
      rules = '.commitlintrc.js'
    }

    steps.log.info("Commit Message Linter","Linting commit messages from HEAD...")

    steps.dir(steps.env.workroot) {
      // commit lint cli requires a git repository to lint commit messages, so we need make sure the workspace is a trusted git repository
      steps.sh "git config --global --add safe.directory ${steps.env.workroot}"
      steps.sh """
        #!/bin/bash

        commitlint --verbose -g ${rules} -f HEAD^
      """
    }
  }
}