Copy getGerritChangeByRefspec from mcp-pipelines/kaas-bm/helpers.groovy

Related: PRODX-35279
Change-Id: I984027e618d4b1c515321654ea830fe540ccc58a
diff --git a/src/com/mirantis/mk/Gerrit.groovy b/src/com/mirantis/mk/Gerrit.groovy
index 51771cb..b436345 100644
--- a/src/com/mirantis/mk/Gerrit.groovy
+++ b/src/com/mirantis/mk/Gerrit.groovy
@@ -559,3 +559,48 @@
     }
     return res
 }
+
+/**
+ * Get gerrit change based on a given refspec.
+ *
+ * @param gerritAuth A map containing Gerrit authentication details (credentialsId, USER, HOST, PORT).
+ * @param repoName The name of the repository.
+ * @param refSpec The refspec or commit hash.
+ * @return A map containing information about the Gerrit change.
+ */
+def getGerritChangeInfoByRefspec(Map gerritAuth, String repoName, String refSpec) {
+  def common = new com.mirantis.mk.Common()
+  String commitHash = ''
+  if (refSpec.startsWith('refs/') || refSpec == 'master') {
+    // why we have retry here? bz infra is awesome and stable!
+    common.retry(15, 10) {
+      sshagent([gerritAuth['credentialsId']]) {
+        commitHash = sh(script: "git ls-remote ssh://${gerritAuth['USER']}@${gerritAuth['HOST']}:${gerritAuth['PORT']}/${repoName} ${refSpec}", returnStdout: true).trim().split('\\t')[0]
+      }
+    }
+  } else {
+    commitHash = refSpec
+  }
+  if (!commitHash) {
+    common.errorMsg("Could not get commit hash for refspec '${refSpec}'")
+    return [:]
+  }
+  LinkedHashMap gerritQuery = [
+    'commit': commitHash,
+  ]
+  String gerritFlags = '--current-patch-set'
+  String patchsetRawJson = findGerritChange(gerritAuth['credentialsId'], gerritAuth, gerritQuery, gerritFlags)
+  if (!patchsetRawJson) {
+    // WARNING(alexz): gerrit search only by CR. so merge event,like https://gerrit.mcp.mirantis.com/plugins/gitiles/kaas/si-tests/+/cabb45ea73ac538c653d62cb0a2ffb4802521251
+    // will not be catched here. In that case, return dummy raw_commit_hash only
+    common.errorMsg("Could not find gerrit change as refspec '${refSpec}' (commit: ${commitHash})")
+    return ['raw_commit_hash': commitHash]
+  }
+  try {
+    // It can (and should) return only one json for given commitHash
+    return readYaml(text: patchsetRawJson)
+  } catch (Exception e) {
+    common.errorMsg("Could not parse JSON: ${patchsetRawJson}\nError: ${e}")
+    return [:]
+  }
+}