1/**
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 *
7 * @format
8 */
9
10'use strict';
11
12const {cp, echo, exec, exit} = require('shelljs');
13const fs = require('fs');
14const path = require('path');
15const mkdirp = require('mkdirp');
16
17function isGitRepo() {
18  try {
19    return (
20      exec('git rev-parse --is-inside-work-tree', {
21        silent: true,
22      }).stdout.trim() === 'true'
23    );
24  } catch (error) {
25    echo(
26      `It wasn't possible to check if we are in a git repository. Details: ${error}`,
27    );
28  }
29  return false;
30}
31
32function exitIfNotOnGit(command, errorMessage, gracefulExit = false) {
33  if (isGitRepo()) {
34    return command();
35  } else {
36    echo(errorMessage);
37    exit(gracefulExit ? 0 : 1);
38  }
39}
40
41function isTaggedLatest(commitSha) {
42  return (
43    exec(`git rev-list -1 latest | grep ${commitSha}`, {
44      silent: true,
45    }).stdout.trim() === commitSha
46  );
47}
48
49function getBranchName() {
50  return exec('git rev-parse --abbrev-ref HEAD', {
51    silent: true,
52  }).stdout.trim();
53}
54
55function getCurrentCommit() {
56  return isGitRepo()
57    ? exec('git rev-parse HEAD', {
58        silent: true,
59      }).stdout.trim()
60    : 'TEMP';
61}
62
63function saveFiles(filePaths, tmpFolder) {
64  for (const filePath of filePaths) {
65    const dirName = path.dirname(filePath);
66    if (dirName !== '.') {
67      const destFolder = `${tmpFolder}/${dirName}`;
68      mkdirp.sync(destFolder);
69    }
70    cp(filePath, `${tmpFolder}/${filePath}`);
71  }
72}
73
74function revertFiles(filePaths, tmpFolder) {
75  for (const filePath of filePaths) {
76    const absoluteTmpPath = `${tmpFolder}/${filePath}`;
77    if (fs.existsSync(absoluteTmpPath)) {
78      cp(absoluteTmpPath, filePath);
79    } else {
80      echo(
81        `It was not possible to revert ${filePath} since ${absoluteTmpPath} does not exist.`,
82      );
83      exit(1);
84    }
85  }
86}
87
88module.exports = {
89  exitIfNotOnGit,
90  getCurrentCommit,
91  getBranchName,
92  isTaggedLatest,
93  revertFiles,
94  saveFiles,
95};
96