xref: /expo/packages/create-expo/src/utils/git.ts (revision b7d15820)
1import spawnAsync from '@expo/spawn-async';
2import chalk from 'chalk';
3
4const debug = require('debug')('expo:init:git') as typeof console.log;
5
6export async function initGitRepoAsync(root: string) {
7  // let's see if we're in a git tree
8  try {
9    await spawnAsync('git', ['rev-parse', '--is-inside-work-tree'], { stdio: 'ignore', cwd: root });
10    debug(chalk.dim('New project is already inside of a Git repo, skipping git init.'));
11    return false;
12  } catch (e: any) {
13    if (e.errno === 'ENOENT') {
14      debug(chalk.dim('Unable to initialize Git repo. `git` not in $PATH.'));
15      return false;
16    }
17  }
18
19  const packageJSON = require('../package.json');
20
21  // not in git tree, so let's init
22  try {
23    await spawnAsync('git', ['init'], { stdio: 'ignore', cwd: root });
24    await spawnAsync('git', ['add', '-A'], { stdio: 'ignore', cwd: root });
25
26    const commitMsg = `Initial commit\n\nGenerated by ${packageJSON.name} ${packageJSON.version}.`;
27    await spawnAsync('git', ['commit', '-m', commitMsg], {
28      stdio: 'ignore',
29      cwd: root,
30    });
31
32    debug(chalk.dim('Initialized a Git repository.'));
33    return true;
34  } catch (error: any) {
35    debug('Error initializing Git repo:', error);
36    // no-op -- this is just a convenience and we don't care if it fails
37    return false;
38  }
39}
40