prune_mocks.go 1.5 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. //go:build ignore
  7. // +build ignore
  8. package main
  9. import (
  10. "bufio"
  11. "flag"
  12. "log"
  13. "os"
  14. "os/exec"
  15. "path/filepath"
  16. "strings"
  17. )
  18. func main() {
  19. var path string
  20. flag.StringVar(&path, "t", "", "Name of file to prune")
  21. flag.Parse()
  22. filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
  23. if err != nil {
  24. log.Fatal(err)
  25. }
  26. if !info.Mode().IsRegular() {
  27. return nil
  28. }
  29. err = pruneInterfaceCheck(path, info.Size())
  30. if err != nil {
  31. log.Fatal(err)
  32. }
  33. err = exec.Command("go", "run", "golang.org/x/tools/cmd/goimports", "-w", path).Run()
  34. if err != nil {
  35. log.Fatal(err)
  36. }
  37. return nil
  38. })
  39. }
  40. func pruneInterfaceCheck(path string, size int64) error {
  41. fd, err := os.Open(path)
  42. if err != nil {
  43. return err
  44. }
  45. defer fd.Close()
  46. tmp, err := os.CreateTemp(".", "")
  47. if err != nil {
  48. return err
  49. }
  50. scanner := bufio.NewScanner(fd)
  51. for scanner.Scan() {
  52. line := scanner.Text()
  53. if strings.HasPrefix(strings.TrimSpace(line), "var _ ") {
  54. continue
  55. }
  56. if _, err := tmp.WriteString(line + "\n"); err != nil {
  57. os.Remove(tmp.Name())
  58. return err
  59. }
  60. }
  61. if err := fd.Close(); err != nil {
  62. return err
  63. }
  64. if err := os.Remove(path); err != nil {
  65. return err
  66. }
  67. return os.Rename(tmp.Name(), path)
  68. }