package com.freeleaps.devops

class ChangedComponentsDetector {
  def steps
  def workspace

  ChangedComponentsDetector(steps) {
    this.steps = steps
  }

  def detect(workspace, components) {
    def changedComponents = [] as Set

    steps.dir(workspace) {
      // using git command to get changed files list
      def changedFiles = steps.sh(script: 'git diff --name-only HEAD~1 HEAD', returnStdout: true)
        .trim()
        .split('\n')

      steps.log.info("ChangedComponentsDetector", "Changed files: ${changedFiles}")
      
      changedFiles.each { file ->
        components.each { component ->
          if (file.startsWith("${component.root}/")) {
            changedComponents.add(component.name)
          }
        }
      }
    }

    return changedComponents.toList()
  }
}