trpc.group/trpc-go/trpc-cmdline@v1.0.9/plugin/goimports.go (about) 1 // Tencent is pleased to support the open source community by making tRPC available. 2 // 3 // Copyright (C) 2023 THL A29 Limited, a Tencent company. 4 // All rights reserved. 5 // 6 // If you have downloaded a copy of the tRPC source code from Tencent, 7 // please note that tRPC source code is licensed under the Apache 2.0 License, 8 // A copy of the Apache 2.0 License is included in this file. 9 10 package plugin 11 12 import ( 13 "fmt" 14 "os/exec" 15 16 "trpc.group/trpc-go/trpc-cmdline/descriptor" 17 "trpc.group/trpc-go/trpc-cmdline/params" 18 "trpc.group/trpc-go/trpc-cmdline/util/log" 19 ) 20 21 // GoImports is goimports plugin. 22 type GoImports struct{} 23 24 // Name return plugin's name. 25 func (p *GoImports) Name() string { 26 return "goimports" 27 } 28 29 // Check only run when `--lang=go && --goimports=true` 30 func (p *GoImports) Check(_ *descriptor.FileDescriptor, opt *params.Option) bool { 31 if opt.Language == "go" { 32 return true 33 } 34 return false 35 } 36 37 // Run runs goimports action. 38 func (p *GoImports) Run(_ *descriptor.FileDescriptor, _ *params.Option) error { 39 goimports, err := exec.LookPath("goimports") 40 if err != nil { 41 return fmt.Errorf("goimports not found, install it first") 42 } 43 44 // Under some rare circumstances, we need run goimports multiple times to 45 // prevent duplicate imports. 46 const maxGoImports = 5 47 for i := 0; i < maxGoImports; i++ { 48 buf, err := exec.Command(goimports, "-w", ".").CombinedOutput() 49 if err != nil { 50 log.Error("run goimports -w . error: %+v,\n%s", err, string(buf)) 51 return err 52 } 53 buf, err = exec.Command(goimports, "-d", ".").CombinedOutput() 54 if err != nil { 55 log.Error("run goimports -d . error: %+v,\n%s", err, string(buf)) 56 return err 57 } 58 if len(buf) == 0 { 59 break 60 } 61 } 62 63 return nil 64 }