updateBranchWithDirectoryContents method

Future<Commit?> updateBranchWithDirectoryContents(
  1. String branchName,
  2. String sourceDirectoryPath,
  3. String commitMessage
)

Implementation

Future<Commit?> updateBranchWithDirectoryContents(
  String branchName,
  String sourceDirectoryPath,
  String commitMessage,
) async {
  final tempGitRoot = await _createTempDir();

  final tempGitDir = GitDir._raw(tempGitRoot.path, sourceDirectoryPath);

  // time for crazy clone tricks
  final args = ['clone', '--shared', '--bare', path, '.'];

  await runGit(args, processWorkingDir: tempGitDir.path);

  await tempGitDir
      .runCommand(['symbolic-ref', 'HEAD', 'refs/heads/$branchName']);

  try {
    // make sure there is something in the working three
    var pr = await tempGitDir.runCommand(['ls-files', '--others']);

    if ((pr.stdout as String).isEmpty) {
      throw GitError('No files were added');
    }
    // add new files to index

    // --verbose is not strictly needed, but nice for debugging
    pr = await tempGitDir.runCommand(['add', '--all', '--verbose']);

    // now to see if we have any changes here
    pr = await tempGitDir.runCommand(['status', '--porcelain']);

    if ((pr.stdout as String).isEmpty) {
      // no change in files! we should return a null result
      return null;
    }

    final args = [
      'commit',
      '--verbose',
    ];

    Directory? tmpDir;

    if (LineSplitter.split(commitMessage).length > 1 && Platform.isWindows) {
      tmpDir = Directory.systemTemp.createTempSync('pkg_git_');

      final fileName = p.join(tmpDir.path, 'commit_message.txt');
      File(fileName).writeAsStringSync(
        commitMessage,
        mode: FileMode.writeOnly,
        flush: true,
      );

      args.addAll(['--file', fileName]);
    } else {
      args.addAll(['-m', commitMessage]);
    }

    try {
      // Time to commit.
      await tempGitDir.runCommand(args);
    } finally {
      tmpDir?.deleteSync(recursive: true);
    }

    // --verbose is not strictly needed, but nice for debugging
    await tempGitDir
        .runCommand(['push', '--verbose', '--progress', path, branchName]);

    // pr.stderr will have all of the info

    // so we have this wonderful new commit, right?
    // need to crack out the commit and return the value
    return commitFromRevision('refs/heads/$branchName');
  } finally {
    await tempGitRoot.delete(recursive: true);
  }
}