aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/packages/create-turbo/src/utils/git.ts
blob: 593e7eac851f557aafb961f76d71409cc9346adc (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import fs from "fs-extra";
import { execSync } from "child_process";
import path from "path";
import rimraf from "rimraf";

export const DEFAULT_IGNORE = `
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
node_modules
.pnp
.pnp.js

# testing
coverage

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# turbo
.turbo

# vercel
.vercel
`;

export const GIT_REPO_COMMAND = "git rev-parse --is-inside-work-tree";
export const HG_REPO_COMMAND = "hg --cwd . root";

export function isInGitRepository(): boolean {
  try {
    execSync(GIT_REPO_COMMAND, { stdio: "ignore" });
    return true;
  } catch (_) {}
  return false;
}

export function isInMercurialRepository(): boolean {
  try {
    execSync(HG_REPO_COMMAND, { stdio: "ignore" });
    return true;
  } catch (_) {}
  return false;
}

export function tryGitInit(root: string, message: string): boolean {
  let didInit = false;
  try {
    execSync("git --version", { stdio: "ignore" });
    if (isInGitRepository() || isInMercurialRepository()) {
      return false;
    }

    execSync("git init", { stdio: "ignore" });
    didInit = true;

    execSync("git checkout -b main", { stdio: "ignore" });

    execSync("git add -A", { stdio: "ignore" });
    execSync(`git commit -m "${message}"`, {
      stdio: "ignore",
    });
    return true;
  } catch (err) {
    if (didInit) {
      try {
        rimraf.sync(path.join(root, ".git"));
      } catch (_) {}
    }
    return false;
  }
}

export function tryGitCommit(message: string): boolean {
  try {
    execSync("git add -A", { stdio: "ignore" });
    execSync(`git commit -m "${message}"`, {
      stdio: "ignore",
    });
    return true;
  } catch (err) {
    return false;
  }
}