@@ -4,12 +4,13 @@ import (
44 "bytes"
55 "context"
66 "errors"
7- "github.com/murphysecurity/murphysec/infra/logctx"
8- "github.com/murphysecurity/murphysec/scanerr"
9- "go.uber.org/zap"
107 "os"
118 "os/exec"
129 "strings"
10+
11+ "github.com/murphysecurity/murphysec/infra/logctx"
12+ "github.com/murphysecurity/murphysec/scanerr"
13+ "go.uber.org/zap"
1314)
1415
1516const (
@@ -42,8 +43,10 @@ func goModTidyError(ctx context.Context, msg string) error {
4243func goModTidy (ctx context.Context , path string ) error {
4344 logger := logctx .Use (ctx )
4445 var stdErr bytes.Buffer
45- var againBol = false
4646 logger .Debug ("go mod tidy :" + path )
47+ //记录次数
48+ var count int = 0
49+ var isourceError bool = false
4750again:
4851
4952 cmd := exec .Command ("go" , "mod" , "tidy" )
@@ -54,24 +57,48 @@ again:
5457 return err
5558 }
5659 if err := cmd .Wait (); err != nil {
57- logctx .Use (ctx ).Error ("cmd wait error :" + err .Error ())
58- return err
59- }
60+ // 命令执行失败,先看 stderr 里是否包含需要特殊处理的错误(例如设置 GOPRIVATE)
61+ msg := stdErr .String ()
62+
63+ // 如果包含特定错误,尝试修复后重试一次
64+ if strings .Contains (msg , sourceError ) {
65+ if e := goModTidyError (ctx , msg ); e != nil {
66+ return e
67+ }
68+ isourceError = true
69+ }
70+ count ++
71+ //如果因为设置GOPRIVATE失败,重试3次后还是失败,则返回错误
72+ if count == 3 {
73+
74+ // 普通失败,记录基础扫描错误
75+ scanerr .Add (ctx , scanerr.Param {
76+ Kind : "auto_build_error" ,
77+ Content : msg ,
78+ })
79+ return errors .New (msg )
80+ } else if count == 2 && ! isourceError {
81+ // 普通失败,记录基础扫描错误
82+ scanerr .Add (ctx , scanerr.Param {
83+ Kind : "auto_build_error" ,
84+ Content : msg ,
85+ })
86+ //如果因为不是因为设置GOPRIVATE失败,重试2次后还是失败,则返回错误,避免无限重试
87+ return errors .New (msg )
88+ }
89+
90+ // 清空上一次的 stderr,再重试
91+ stdErr .Reset ()
92+ goto again
6093
61- if againBol {
62- scanerr .Add (ctx , scanerr.Param {
63- Kind : "auto_build_error" ,
64- Content : stdErr .String (),
65- })
66- return errors .New (stdErr .String ())
6794 }
95+
96+ // 走到这里说明 go mod tidy 成功了
97+ // 即使命令成功,stderr 也可能只是一些警告信息,这里只打日志,不触发基础扫描
6898 if stdErr .Len () > 0 {
69- if err := goModTidyError (ctx , stdErr .String ()); err != nil {
70- return err
71- } else {
72- againBol = true
73- goto again
74- }
99+ logger .Warn ("go mod tidy stderr (ignored, command succeeded)" ,
100+ zap .String ("stderr" , stdErr .String ()))
75101 }
102+
76103 return nil
77104}
0 commit comments