| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- package main
- import (
- "flag"
- "fmt"
- "io"
- "os"
- )
- type executer interface {
- execute() (string, error)
- }
- func run(proj string, out io.Writer) error {
- // 参数有效性检查
- if proj == "" {
- return fmt.Errorf("project directory is required: %w", ErrValidation)
- }
- // 构造 CI 流水线步骤
- pipeline := make([]executer, 3)
- pipeline[0] = newStep( // 构建步骤
- "go build", // 执行命令
- "Go Build: SUCCESS", // 成功输出信息
- proj, // 项目目录
- "go", // 命令执行路径
- []string{"build", ".", "errors"}, // 命令参数
- )
- pipeline[1] = newStep( // 测试步骤
- "go test",
- "Go Test: SUCCESS",
- proj,
- "go",
- []string{"test", "-v"}, // -v 显示详细输出
- )
- pipeline[2] = newExceptionStep(
- "go fmt",
- "GoFmt: SUCCESS",
- proj,
- "gofmt",
- []string{"-l", "."},
- )
- // 执行流水线任务
- for _, s := range pipeline {
- msg, err := s.execute() // 执行并获取结果
- if err != nil {
- return err // 遇到错误立即中断流程
- }
- // 输出成功信息到指定流
- if _, err = fmt.Fprintln(out, msg); err != nil {
- return err
- }
- }
- return nil
- }
- func main() {
- proj := flag.String("p", "", "Project directory")
- flag.Parse()
- // 执行主逻辑并检查错误
- if err := run(*proj, os.Stdout); err != nil {
- // 将错误输出到标准错误流
- _, _ = fmt.Fprintln(os.Stderr, err)
- // 异常退出,状态码1表示错误
- os.Exit(1)
- }
- }
|