prune_mocks.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Copyright (C) 2021 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. // +build ignore
  7. package main
  8. import (
  9. "bufio"
  10. "flag"
  11. "fmt"
  12. "io/ioutil"
  13. "log"
  14. "os"
  15. "os/exec"
  16. "path/filepath"
  17. "strings"
  18. )
  19. func main() {
  20. var path string
  21. flag.StringVar(&path, "t", "", "Name of file to prune")
  22. flag.Parse()
  23. filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
  24. if err != nil {
  25. log.Fatal(err)
  26. }
  27. if !info.Mode().IsRegular() {
  28. return nil
  29. }
  30. err = pruneInterfaceCheck(path, info.Size())
  31. if err != nil {
  32. log.Fatal(err)
  33. }
  34. err = exec.Command("goimports", "-w", path).Run()
  35. if err != nil {
  36. log.Fatal(err)
  37. }
  38. return nil
  39. })
  40. }
  41. func pruneInterfaceCheck(path string, size int64) error {
  42. fd, err := os.Open(path)
  43. if err != nil {
  44. return err
  45. }
  46. defer fd.Close()
  47. tmp, err := ioutil.TempFile(".", "")
  48. if err != nil {
  49. return err
  50. }
  51. scanner := bufio.NewScanner(fd)
  52. for scanner.Scan() {
  53. line := scanner.Text()
  54. if strings.HasPrefix(strings.TrimSpace(line), "var _ ") {
  55. continue
  56. }
  57. if _, err := tmp.WriteString(line + "\n"); err != nil {
  58. os.Remove(tmp.Name())
  59. return err
  60. }
  61. }
  62. if err := fd.Close(); err != nil {
  63. return err
  64. }
  65. if err := os.Remove(path); err != nil {
  66. return err
  67. }
  68. return os.Rename(tmp.Name(), path)
  69. }