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 Nov 20, 2024
1 parent 37bb521 commit b6af086
Show file tree
Hide file tree
Showing 2 changed files with 102 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
195 changes: 97 additions & 98 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -277,21 +277,24 @@ func main() {
return
}

originPath := flag.Arg(0)
originPaths := flag.Args()

Check warning on line 280 in main.go

View check run for this annotation

Codecov / codecov/patch

main.go#L280

Added line #L280 was not covered by tests

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
deprecatedMessagesCh <- fmt.Sprintf("-%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)
originPaths = append(originPaths, filePath)

Check warning on line 284 in main.go

View check run for this annotation

Codecov / codecov/patch

main.go#L283-L284

Added lines #L283 - L284 were not covered by tests
}

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

Check warning on line 289 in main.go

View check run for this annotation

Codecov / codecov/patch

main.go#L287-L289

Added lines #L287 - L289 were not covered by tests
}

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)
}

Check warning on line 297 in main.go

View check run for this annotation

Codecov / codecov/patch

main.go#L292-L297

Added lines #L292 - L297 were not covered by tests
}

var options reviser.SourceFileOptions
Expand Down Expand Up @@ -340,108 +343,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

Check warning on line 357 in main.go

View check run for this annotation

Codecov / codecov/patch

main.go#L346-L357

Added lines #L346 - L357 were not covered by tests
}
err := reviser.NewSourceDir(originProjectName, originPath, *isRecursive, excludes).Fix(options...)

Check warning on line 359 in main.go

View check run for this annotation

Codecov / codecov/patch

main.go#L359

Added line #L359 was not covered by tests
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)

Check warning on line 361 in main.go

View check run for this annotation

Codecov / codecov/patch

main.go#L361

Added line #L361 was not covered by tests
}
fmt.Printf("%s\n", unformattedFiles.String())
return
continue

Check warning on line 363 in main.go

View check run for this annotation

Codecov / codecov/patch

main.go#L363

Added line #L363 was not covered by tests
}
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)
}

Check warning on line 370 in main.go

View check run for this annotation

Codecov / codecov/patch

main.go#L366-L370

Added lines #L366 - L370 were not covered by tests
}
}

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))

Check warning on line 376 in main.go

View check run for this annotation

Codecov / codecov/patch

main.go#L373-L376

Added lines #L373 - L376 were not covered by tests

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)

Check warning on line 380 in main.go

View check run for this annotation

Codecov / codecov/patch

main.go#L378-L380

Added lines #L378 - L380 were not covered by tests
}
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)

Check warning on line 384 in main.go

View check run for this annotation

Codecov / codecov/patch

main.go#L382-L384

Added lines #L382 - L384 were not covered by tests
}
}
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

Check warning on line 398 in main.go

View check run for this annotation

Codecov / codecov/patch

main.go#L386-L398

Added lines #L386 - L398 were not covered by tests
}
}
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)
}

Check warning on line 410 in main.go

View check run for this annotation

Codecov / codecov/patch

main.go#L401-L410

Added lines #L401 - L410 were not covered by tests
}
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)

Check warning on line 428 in main.go

View check run for this annotation

Codecov / codecov/patch

main.go#L412-L428

Added lines #L412 - L428 were not covered by tests
}
}
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

Check warning on line 432 in main.go

View check run for this annotation

Codecov / codecov/patch

main.go#L431-L432

Added lines #L431 - L432 were not covered by tests
}
}

resultPostProcess(hasChange, deprecatedMessagesCh, originPath, formattedOutput)
resultPostProcess(hasChange, originPath, formattedOutput)

Check warning on line 435 in main.go

View check run for this annotation

Codecov / codecov/patch

main.go#L435

Added line #L435 was not covered by tests
}
printDeprecations(deprecatedMessagesCh)
if hasChange && *setExitStatus {
os.Exit(1)
}

Check warning on line 440 in main.go

View check run for this annotation

Codecov / codecov/patch

main.go#L437-L440

Added lines #L437 - L440 were not covered by tests
}

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) {

Check warning on line 443 in main.go

View check run for this annotation

Codecov / codecov/patch

main.go#L443

Added line #L443 was not covered by tests
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 @@ -451,12 +456,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 @@ -474,10 +473,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)

Check warning on line 476 in main.go

View check run for this annotation

Codecov / codecov/patch

main.go#L476

Added line #L476 was not covered by tests
}
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")

Check warning on line 479 in main.go

View check run for this annotation

Codecov / codecov/patch

main.go#L479

Added line #L479 was not covered by tests
os.Exit(1)
}
}

0 comments on commit b6af086

Please sign in to comment.