Skip to content

Commit

Permalink
Allow multiple targets on command line
Browse files Browse the repository at this point in the history
This addresses #96

- iterate over the list of remaining arguments treating
  each as an origin path

- fully remove support for the -filePath option

- defer printing deprecation warnings until after all paths
  are processed

- print deprecation warnings to stderr, not stdout
  • Loading branch information
n-oden committed Jul 5, 2024
1 parent 5f29621 commit 2c2a3a9
Show file tree
Hide file tree
Showing 2 changed files with 101 additions and 98 deletions.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,11 @@ goimports-reviser -rm-unused -set-alias -format -recursive reviser
goimports-reviser -rm-unused -set-alias -format ./...
```

You can also apply rules to multiple targets:
```bash
goimports-reviser -rm-unused -set-alias -format ./reviser/reviser.go ./pkg/...
```

### Example, to configure it with JetBrains IDEs (via file watcher plugin):
![example](./images/image.png)

Expand Down
194 changes: 96 additions & 98 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -205,20 +205,22 @@ func main() {
return
}

originPath := flag.Arg(0)
if filePath != "" {
deprecatedMessagesCh <- fmt.Sprintf("-%s is deprecated. Put file name as last argument to the command(Example: goimports-reviser -rm-unused -set-alias -format goimports-reviser/main.go)", filePathArg)
originPath = filePath
log.Fatalf("-%s is deprecated. Put file name(s) as last argument to the command(Example: goimports-reviser -rm-unused -set-alias -format goimports-reviser/main.go)", filePathArg)
}

if originPath == "" {
originPath = reviser.StandardInput
originPaths := flag.Args()
var originPath string
if len(originPaths) == 0 || (len(originPaths) == 1 && originPaths[0] == "-") {
originPaths[0] = reviser.StandardInput
}

if err := validateRequiredParam(originPath); err != nil {
fmt.Printf("%s\n\n", err)
printUsage()
os.Exit(1)
for _, originPath = range originPaths {
if err := validateRequiredParam(originPath); err != nil {
fmt.Printf("%s\n\n", err)
printUsage()
os.Exit(1)
}
}

var options reviser.SourceFileOptions
Expand Down Expand Up @@ -267,108 +269,110 @@ func main() {
}

close(deprecatedMessagesCh)

if _, ok := reviser.IsDir(originPath); ok {
if *listFileName {
unformattedFiles, err := reviser.NewSourceDir(originProjectName, originPath, *isRecursive, excludes).Find(options...)
var hasChange bool
log.Printf("Paths: %v\n", originPaths)
for _, originPath = range originPaths {
log.Printf("Processing %s\n", originPath)
if _, ok := reviser.IsDir(originPath); ok {
if *listFileName {
unformattedFiles, err := reviser.NewSourceDir(originProjectName, originPath, *isRecursive, excludes).Find(options...)
if err != nil {
log.Fatalf("Failed to find unformatted files %s: %+v\n", originPath, err)
}
fmt.Printf("%s\n", unformattedFiles.String())
continue
}
err := reviser.NewSourceDir(originProjectName, originPath, *isRecursive, excludes).Fix(options...)
if err != nil {
log.Fatalf("Failed to find unformatted files %s: %+v\n", originPath, err)
log.Fatalf("Failed to fix directory %s: %+v\n", originPath, err)
}
fmt.Printf("%s\n", unformattedFiles.String())
return
continue
}
err := reviser.NewSourceDir(originProjectName, originPath, *isRecursive, excludes).Fix(options...)
if err != nil {
log.Fatalf("Failed to fix directory %s: %+v\n", originPath, err)
}
return
}

if originPath != reviser.StandardInput {
originPath, err = filepath.Abs(originPath)
if err != nil {
log.Fatalf("Failed to get abs path: %+v\n", err)
if originPath != reviser.StandardInput {
originPath, err = filepath.Abs(originPath)
if err != nil {
log.Fatalf("Failed to get abs path: %+v\n", err)
}
}
}

var formattedOutput []byte
var hasChange bool
if *isUseCache {
hash := md5.Sum([]byte(originPath))
var formattedOutput []byte
var pathHasChange bool
if *isUseCache {
hash := md5.Sum([]byte(originPath))

u, err := user.Current()
if err != nil {
log.Fatalf("Failed to get current user: %+v\n", err)
}
cacheDir := path.Join(u.HomeDir, ".cache", "goimports-reviser")
if err = os.MkdirAll(cacheDir, os.ModePerm); err != nil {
log.Fatalf("Failed to create cache directory: %+v\n", err)
}
cacheFile := path.Join(cacheDir, hex.EncodeToString(hash[:]))

var cacheContent, fileContent []byte
if cacheContent, err = os.ReadFile(cacheFile); err == nil {
// compare file content hash
var fileHashHex string
if fileContent, err = os.ReadFile(originPath); err == nil {
fileHash := md5.Sum(fileContent)
fileHashHex = hex.EncodeToString(fileHash[:])
u, err := user.Current()
if err != nil {
log.Fatalf("Failed to get current user: %+v\n", err)
}
if string(cacheContent) == fileHashHex {
// point to cache
return
cacheDir := path.Join(u.HomeDir, ".cache", "goimports-reviser")
if err = os.MkdirAll(cacheDir, os.ModePerm); err != nil {
log.Fatalf("Failed to create cache directory: %+v\n", err)
}
}
formattedOutput, _, hasChange, err = reviser.NewSourceFile(originProjectName, originPath).Fix(options...)
if err != nil {
log.Fatalf("Failed to fix file: %+v\n", err)
}
fileHash := md5.Sum(formattedOutput)
fileHashHex := hex.EncodeToString(fileHash[:])
if fileInfo, err := os.Stat(cacheFile); err != nil || fileInfo.IsDir() {
if _, err = os.Create(cacheFile); err != nil {
log.Fatalf("Failed to create cache file: %+v\n", err)
cacheFile := path.Join(cacheDir, hex.EncodeToString(hash[:]))

var cacheContent, fileContent []byte
if cacheContent, err = os.ReadFile(cacheFile); err == nil {
// compare file content hash
var fileHashHex string
if fileContent, err = os.ReadFile(originPath); err == nil {
fileHash := md5.Sum(fileContent)
fileHashHex = hex.EncodeToString(fileHash[:])
}
if string(cacheContent) == fileHashHex {
// point to cache
continue
}
}
formattedOutput, _, pathHasChange, err = reviser.NewSourceFile(originProjectName, originPath).Fix(options...)
if err != nil {
log.Fatalf("Failed to fix file: %+v\n", err)
}
fileHash := md5.Sum(formattedOutput)
fileHashHex := hex.EncodeToString(fileHash[:])
if fileInfo, err := os.Stat(cacheFile); err != nil || fileInfo.IsDir() {
if _, err = os.Create(cacheFile); err != nil {
log.Fatalf("Failed to create cache file: %+v\n", err)
}
}
file, _ := os.OpenFile(cacheFile, os.O_RDWR, os.ModePerm)
defer func() {
_ = file.Close()
}()
if err = file.Truncate(0); err != nil {
log.Fatalf("Failed file truncate: %+v\n", err)
}
if _, err = file.Seek(0, 0); err != nil {
log.Fatalf("Failed file seek: %+v\n", err)
}
if _, err = file.WriteString(fileHashHex); err != nil {
log.Fatalf("Failed to write file hash: %+v\n", err)
}
} else {
formattedOutput, _, pathHasChange, err = reviser.NewSourceFile(originProjectName, originPath).Fix(options...)
if err != nil {
log.Fatalf("Failed to fix file: %+v\n", err)
}
}
file, _ := os.OpenFile(cacheFile, os.O_RDWR, os.ModePerm)
defer func() {
_ = file.Close()
}()
if err = file.Truncate(0); err != nil {
log.Fatalf("Failed file truncate: %+v\n", err)
}
if _, err = file.Seek(0, 0); err != nil {
log.Fatalf("Failed file seek: %+v\n", err)
}
if _, err = file.WriteString(fileHashHex); err != nil {
log.Fatalf("Failed to write file hash: %+v\n", err)
}
} else {
formattedOutput, _, hasChange, err = reviser.NewSourceFile(originProjectName, originPath).Fix(options...)
if err != nil {
log.Fatalf("Failed to fix file: %+v\n", err)
if !hasChange && pathHasChange {
hasChange = pathHasChange
}
}

resultPostProcess(hasChange, deprecatedMessagesCh, originPath, formattedOutput)
resultPostProcess(hasChange, originPath, formattedOutput)
}
printDeprecations(deprecatedMessagesCh)
if hasChange && *setExitStatus {
os.Exit(1)
}
}

func resultPostProcess(hasChange bool, deprecatedMessagesCh chan string, originFilePath string, formattedOutput []byte) {
if !hasChange && *listFileName {
printDeprecations(deprecatedMessagesCh)
return
}
func resultPostProcess(hasChange bool, originFilePath string, formattedOutput []byte) {
switch {
case hasChange && *listFileName && output != "write":
fmt.Println(originFilePath)
case output == "stdout" || originFilePath == reviser.StandardInput:
fmt.Print(string(formattedOutput))
case output == "file" || output == "write":
if !hasChange {
printDeprecations(deprecatedMessagesCh)
return
}

if err := os.WriteFile(originFilePath, formattedOutput, 0o644); err != nil {
log.Fatalf("failed to write fixed result to file(%s): %+v\n", originFilePath, err)
}
Expand All @@ -378,12 +382,6 @@ func resultPostProcess(hasChange bool, deprecatedMessagesCh chan string, originF
default:
log.Fatalf(`invalid output %q specified`, output)
}

if hasChange && *setExitStatus {
os.Exit(1)
}

printDeprecations(deprecatedMessagesCh)
}

func validateRequiredParam(filePath string) error {
Expand All @@ -401,10 +399,10 @@ func printDeprecations(deprecatedMessagesCh chan string) {
var hasDeprecations bool
for deprecatedMessage := range deprecatedMessagesCh {
hasDeprecations = true
fmt.Printf("%s\n", deprecatedMessage)
log.Printf("%s\n", deprecatedMessage)
}
if hasDeprecations {
fmt.Printf("All changes to file are applied, but command-line syntax should be fixed\n")
log.Printf("All changes to file are applied, but command-line syntax should be fixed\n")
os.Exit(1)
}
}

0 comments on commit 2c2a3a9

Please sign in to comment.