main.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "io"
  6. "os"
  7. )
  8. type executer interface {
  9. execute() (string, error)
  10. }
  11. func run(proj string, out io.Writer) error {
  12. // 参数有效性检查
  13. if proj == "" {
  14. return fmt.Errorf("project directory is required: %w", ErrValidation)
  15. }
  16. // 构造 CI 流水线步骤
  17. pipeline := make([]executer, 3)
  18. pipeline[0] = newStep( // 构建步骤
  19. "go build", // 执行命令
  20. "Go Build: SUCCESS", // 成功输出信息
  21. proj, // 项目目录
  22. "go", // 命令执行路径
  23. []string{"build", ".", "errors"}, // 命令参数
  24. )
  25. pipeline[1] = newStep( // 测试步骤
  26. "go test",
  27. "Go Test: SUCCESS",
  28. proj,
  29. "go",
  30. []string{"test", "-v"}, // -v 显示详细输出
  31. )
  32. pipeline[2] = newExceptionStep(
  33. "go fmt",
  34. "GoFmt: SUCCESS",
  35. proj,
  36. "gofmt",
  37. []string{"-l", "."},
  38. )
  39. // 执行流水线任务
  40. for _, s := range pipeline {
  41. msg, err := s.execute() // 执行并获取结果
  42. if err != nil {
  43. return err // 遇到错误立即中断流程
  44. }
  45. // 输出成功信息到指定流
  46. if _, err = fmt.Fprintln(out, msg); err != nil {
  47. return err
  48. }
  49. }
  50. return nil
  51. }
  52. func main() {
  53. proj := flag.String("p", "", "Project directory")
  54. flag.Parse()
  55. // 执行主逻辑并检查错误
  56. if err := run(*proj, os.Stdout); err != nil {
  57. // 将错误输出到标准错误流
  58. _, _ = fmt.Fprintln(os.Stderr, err)
  59. // 异常退出,状态码1表示错误
  60. os.Exit(1)
  61. }
  62. }