File: prune_mocks.go

package info (click to toggle)
syncthing 1.29.5~ds1-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 22,848 kB
  • sloc: javascript: 37,288; sh: 1,838; xml: 1,115; makefile: 66
file content (78 lines) | stat: -rw-r--r-- 1,502 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Copyright (C) 2021 The Syncthing Authors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.

//go:build ignore
// +build ignore

package main

import (
	"bufio"
	"flag"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
)

func main() {
	var path string
	flag.StringVar(&path, "t", "", "Name of file to prune")
	flag.Parse()

	filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			log.Fatal(err)
		}
		if !info.Mode().IsRegular() {
			return nil
		}
		err = pruneInterfaceCheck(path, info.Size())
		if err != nil {
			log.Fatal(err)
		}
		err = exec.Command("go", "run", "golang.org/x/tools/cmd/goimports", "-w", path).Run()
		if err != nil {
			log.Fatal(err)
		}
		return nil
	})
}

func pruneInterfaceCheck(path string, size int64) error {
	fd, err := os.Open(path)
	if err != nil {
		return err
	}
	defer fd.Close()

	tmp, err := os.CreateTemp(".", "")
	if err != nil {
		return err
	}

	scanner := bufio.NewScanner(fd)

	for scanner.Scan() {
		line := scanner.Text()
		if strings.HasPrefix(strings.TrimSpace(line), "var _ ") {
			continue
		}
		if _, err := tmp.WriteString(line + "\n"); err != nil {
			os.Remove(tmp.Name())
			return err
		}
	}

	if err := fd.Close(); err != nil {
		return err
	}
	if err := os.Remove(path); err != nil {
		return err
	}
	return os.Rename(tmp.Name(), path)
}