Flutter版本控制插件simple_git的使用

Flutter 版本控制插件 simple_git 的使用

Simple Git

一个轻量级的接口,用于在任何 Dart 应用程序中运行 git 命令。

Simple git 包灵感来源于 nodejs simple-git

这个包并不是 nodejs simple-git 的精确克隆,改进和新功能都是受欢迎的!

安装

将以下依赖项添加到 pubspec.yaml 文件中:

dependencies:
  simple_git: any

系统依赖

需要安装 git 并且可以在命令行中通过 git 调用它。

使用

在 Dart 应用程序中包含插件:

import 'package:simple_git/simple_git.dart';

var simpleGit = SimpleGit(SimpleProcessOptions());

配置

配置每个 simple_git 实例通过传递给 SimpleGit 构造函数的属性对象:

import 'package:simple_git/simple_git.dart';

var options = SimpleProcessOptions();

// 或者

// 所有字段都是可选的
var options = SimpleProcessOptions(
  baseDir: Directory.current.path, // 工作目录,用于运行 `git` 命令
  showOutput: true, // 是否打印所有输出到终端(默认 = false)
  binary: 'git',
  config: 'http.proxy=someproxy',
  maxConcurrentProcesses: 6,
  runInShell: true,
);

所有配置属性都是可选的,上面的例子展示了默认值。

每个命令的配置

要使用不保存在 git 配置中的自定义配置前缀运行 simple_git 命令(例如使用 -c 命令),在实例构建器中提供 config 选项:

// 配置实例使用自定义配置属性
var options = SimpleProcessOptions(
  config: 'http.proxy=someproxy'
);

// 任何命令执行时都会以该配置为前缀
// 运行: git -c http.proxy=someproxy pull
simpleGit.pull();

默认的 SimpleGit 是同步的,但你可以使用异步版本 SimpleGitAsync

使用任务 Future

你可以在同步版本中使用级联操作符链式调用命令,或者在异步版本中同时运行所有命令。或者等待 Future 完成。

// 同步
simpleGitSync..init()..addRemote('origin', '...remote.git');

// 异步使用 await
await simpleGitAsync.init();
await simpleGitAsync.addRemote('origin', '...remote.git');

// 异步同时运行(Future.await 也是可能的)
simpleGitAsync..init()..addRemote('origin', '...remote.git');

捕获错误 GitException

要在异步代码中捕获错误,可以将整个链包装在 try/catch 中:

try {
  await simpleGitAsync.init();
  await simpleGitAsync.addRemote(name, repoUrl);
} on GitException catch(gitException) { /* 处理所有 git 错误 */ }
catch (e) { /* 处理其他类型的错误 */ }

或者分别捕获各个步骤,允许主链继续执行而不是跳转到最后的 catch

// 异步
await simpleGitAsync.init().catchError(gitException); // GitException
// 同步

// 手动处理错误
var result = simpleGit.init(skipOnError: true); // 如果 `skipOnError: true` 则不会抛出错误
if (result.exitCode != 0) {
  print('Error: ' + result.stderr);
  // 返回
}

使用任务回调 HandlerFunction

simpleGit.init(
  handlerFn: (result) { // ProcessResult result
      // 总是被触发!无论是否有错误
  }
);

任务响应 ProcessResult

无论是使用尾随回调、同步还是异步命令,任务都返回 ProcessResultFuture<ProcessResult> 响应。

查看示例项目文件夹以获取更多示例

API 尚未准备好 - 待办事项

API 列表

API 功能
.add([fileA, ...], handlerFn) 添加一个或多个文件到源代码控制下
.addAnnotatedTag(tagName, tagMessage, handlerFn) 在当前分支头添加一个注释标签
.addTag(name, handlerFn) 在当前分支头添加一个轻量标签
.catFile(options[, handlerFn]) 生成 cat-file 详情,options 应该是一个字符串数组,作为支持的 cat-file 命令参数
.checkIgnore([filepath, ...], handlerFn) 检查文件是否被 .gitignore 规则排除
.clearQueue() 立即清除待处理任务队列(注意:任何正在执行的命令仍会调用其完成回调)
.commit(message, handlerFn) 提交当前工作目录中的更改,并附带提供的消息
.commit(message, [fileA, ...], options, handlerFn) 提交指定文件中的更改,并附带提供的消息
.customBinary(gitPath) 设置引用 git 的命令,允许使用不在路径环境变量中的 git 二进制文件
.cwd(workingDirectory) 设置从这一步骤开始的所有命令的工作目录
.diff(options, handlerFn) 获取当前仓库与上次提交之间的差异
.diff(handlerFn) 获取当前仓库中所有文件与上次提交之间的差异
.diffSummary(handlerFn) 获取仓库中文件差异的摘要
.diffSummary(options, handlerFn) 包括 diff --stat options 调用,并返回 DiffSummary
.env(name, value) 设置要传递给子进程的环境变量
.exec(handlerFn) 在当前步骤中调用一个简单的函数
.fetch([options, ] handlerFn) 更新本地工作副本数据库,获取默认远程仓库和分支的更改
.fetch(remote, branch, handlerFn) 更新本地工作副本数据库,获取远程仓库的更改
.fetch(handlerFn) 更新本地工作副本数据库,获取默认远程仓库和分支的更改
.log([options], handlerFn) 列出 options.fromoptions.to 之间的提交
.outputHandler(handlerFn) 附加一个处理程序,该处理程序将在运行的命令名称和创建的 stdoutstderr 流上调用
.raw(args[, handlerFn]) 执行任何受底层 git 二进制文件支持的任意数组命令
.rebase([options,] handlerFn) 重新定位仓库
.revert(commit [, options [, handlerFn]]) 撤销工作副本中的一个或多个提交
.rm([fileA, ...], handlerFn) 从源代码控制中删除任意数量的文件
.rmKeepLocal([fileA, ...], handlerFn) 从源代码控制中删除文件,但保留在磁盘上
.stash([options, ][ handlerFn]) 暂存工作目录
.stashList([options, ][handlerFn]) 获取暂存列表
.tag(args[], handlerFn) 使用传递的字符串数组运行任何受支持的 git tag 命令
.tags([options, ] handlerFn) 列出所有标签
.show([options], handlerFn) 显示各种类型的对象

免责声明:这是一个正在进行中的工作,请考虑帮助改进此包,并避免在生产发布中使用它,因为它尚未准备就绪。

欢迎提交拉取请求!如果您能贡献,请贡献。让我们一起实现这个目标!

完整示例 Demo

import 'package:simple_git/simple_git.dart';
import 'package:simple_git/src/utils/logger/logger.dart';
import 'package:simple_process/simple_process.dart';

var logger = LoggerUtil.verbose();

// 所有字段都是可选的
var options = SimpleProcessOptions(
  //showOutput: false, // 是否打印所有输出到终端(默认 = false)
  binary: 'git',
);

// 要测试此示例,您需要在一个 git 项目目录中
void main() async {
  // runSync();
  runAsync();
}

void runSync() {
  var gitSync = SimpleGit(options: options);

  var result = gitSync.status();
  logger.stdout('[STATUS]: ${result.lines.first}\n');

  /// 只有第二个命令会抛出错误并退出应用程序
  /// 第二个命令总是在第一个命令完成后发生(同步)
  /// 参数 `skipOnError = true` 允许即使之前出现错误也继续执行下一个命令,但是您可以根据需要使用 `handlerFn` 处理错误
  /// 如果 `skipOnError = false`(默认),如果之前出现错误,则不会执行第二个命令
  // gitSync..add(file: '*FirstErrorSkiped*', skipOnError: true)..add(file: '*SecondErrorFired*');

  try {
    var result = gitSync.add(file: '##1', skipOnError: true, showOutput: true);
    if (result.exitCode != 0) {
      logger.stderr(
          'First error supressed, with "skipOnError: true" - message: ${result.resultMessage}');
    }

    // 第一个命令不会抛出错误且不会被捕获
    // 第二个命令不会被执行
    gitSync
      ..add(file: '##2', skipOnError: true, showOutput: true)
      ..add(file: '%%3', showOutput: true);
  } on SimpleProcessResult catch (gitException) {
    logger.stderr(
        'Third error (Try/Catch) with exit code: ${gitException.exitCode} - [Description] ${gitException.toString()}');
  } catch (e) {
    logger.stderr('Platform error $e');
  }
}

void runAsync() async {
  var gitAsync = SimpleGitAsync(options: options);

  try {
    var result = await gitAsync.addAll(handlerFn: (result) {
      // 总是被触发!无论是否有错误
    });
    logger.stdout(
        'command execute successfully, pid: ${result.processResult?.pid}');
  } on SimpleProcessResult catch (e) {
    logger.stderr('awaited error with exit code: ${e.exitCode}');
  } catch (e) {
    logger.stderr('Generic error: $e');
  }

  // 抛出错误并捕获错误
  await gitAsync.add(file: '###').catchError((dynamicError) {
    SimpleProcessResult error = dynamicError;
    logger.stderr(
        'Current Exit code: ${error.exitCode} - [Description] ${error.resultMessage}');
    return error; // 需要返回错误,因为安全约束
  });

  logger.stdout('awaited...');

  // 一切都在一起工作,不推荐并发文件访问
  gitAsync
    // ignore: unawaited_futures
    ..addAll(handlerFn: (result) {
      logger.stdout(
          'this can be finished or not, it depends if some error get fired before');
    })
    // ignore: unawaited_futures
    ..add(
      file: '##',
      // skipOnError: true
    ).then((value) {
      logger.stdout('This code will never be executed');
      return value;
    }) // 这将抛出一个错误。如果没有 catchError,它将停止所有执行并退出应用程序
    // ignore: unawaited_futures
    ..addAll(handlerFn: (result) {
      logger.stdout(
          'this can be finished or not, it depends if some error get fired before');
    });
}

更多关于Flutter版本控制插件simple_git的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter版本控制插件simple_git的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


simple_git 是一个用于 Flutter 的 Git 版本控制插件,它允许你在 Flutter 应用中轻松地与 Git 仓库进行交互。通过 simple_git,你可以执行各种 Git 操作,如克隆仓库、提交更改、拉取更新等。

安装 simple_git

首先,你需要在 pubspec.yaml 文件中添加 simple_git 依赖:

dependencies:
  flutter:
    sdk: flutter
  simple_git: ^0.0.1

然后运行 flutter pub get 来安装依赖。

使用 simple_git

以下是一些常见的 simple_git 使用示例:

1. 初始化 Git 仓库

import 'package:simple_git/simple_git.dart';

void main() async {
  final git = SimpleGit();
  await git.init();
  print('Git repository initialized');
}

2. 克隆仓库

import 'package:simple_git/simple_git.dart';

void main() async {
  final git = SimpleGit();
  await git.clone('https://github.com/username/repository.git', './local_path');
  print('Repository cloned');
}

3. 添加文件到暂存区

import 'package:simple_git/simple_git.dart';

void main() async {
  final git = SimpleGit();
  await git.add('path/to/file');
  print('File added to staging area');
}

4. 提交更改

import 'package:simple_git/simple_git.dart';

void main() async {
  final git = SimpleGit();
  await git.commit('Your commit message');
  print('Changes committed');
}

5. 拉取更新

import 'package:simple_git/simple_git.dart';

void main() async {
  final git = SimpleGit();
  await git.pull();
  print('Changes pulled');
}

6. 推送更改

import 'package:simple_git/simple_git.dart';

void main() async {
  final git = SimpleGit();
  await git.push();
  print('Changes pushed');
}

其他常用命令

  • git.status(): 查看当前仓库状态。
  • git.branch(): 查看或操作分支。
  • git.checkout(): 切换分支。
  • git.log(): 查看提交日志。

注意事项

  1. 权限问题: 在执行某些 Git 操作时,可能需要用户权限(如推送更改到远程仓库)。确保你的应用有足够的权限来执行这些操作。

  2. 错误处理: 在实际使用中,建议对 simple_git 的每个操作进行错误处理,以便在出现问题时能够及时捕获并处理异常。

try {
  await git.push();
} catch (e) {
  print('Error pushing changes: $e');
}
回到顶部