Skip to content

Instantly share code, notes, and snippets.

@teknoraver
Last active December 9, 2019 01:16
Show Gist options
  • Save teknoraver/2cdbfb7932c9c34acff6efe821c4d370 to your computer and use it in GitHub Desktop.
Save teknoraver/2cdbfb7932c9c34acff6efe821c4d370 to your computer and use it in GitHub Desktop.
tool to find reverse Xmas tree declarations in a source tree
/*
* rxmastree - tool to find reverse Xmas tree declarations in a source tree
* Copyright (C) 2019 Matteo Croce <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package main
import (
"bufio"
"flag"
"fmt"
"os"
"path/filepath"
"strings"
)
var (
minTreeSize *int
maxEqLines *int
)
func scanFile(path string, _ os.FileInfo, _ error) error {
if !strings.HasSuffix(path, ".c") && !strings.HasSuffix(path, ".h") {
return nil
}
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
var last, eqlines int
tree := []string{}
for scanner, i := bufio.NewScanner(file), 1; scanner.Scan(); i++ {
line := scanner.Text()
newlen := len(line)
switch {
case newlen == 0:
if len(tree) >= *minTreeSize {
fmt.Printf("%s:%d tree size %d\n", path, i-len(tree), len(tree))
for _, l := range tree {
fmt.Println(l)
}
fmt.Println()
}
tree = []string{}
case line[newlen-1] == ';' && newlen < last:
last = newlen
tree = append(tree, line)
eqlines = 0
case line[newlen-1] == ';' && newlen == last:
eqlines++
if eqlines == *maxEqLines {
eqlines = 0
last = 0
tree = tree[:0]
break
}
last = newlen
tree = append(tree, line)
case line[newlen-1] == ';':
eqlines = 0
last = newlen
tree = []string{line}
default:
eqlines = 0
last = 0
tree = tree[:0]
}
}
return nil
}
func main() {
minTreeSize = flag.Int("minTreeSize", 10, "Minimum tree size")
maxEqLines = flag.Int("maxEqLines", 3, "maximum number of consecutive equal lines")
flag.Usage = func() {
fmt.Println("usage:", os.Args[0], "dir1", "dir2", "...")
flag.PrintDefaults()
os.Exit(0)
}
flag.Parse()
if flag.NArg() == 0 {
flag.Usage()
}
for _, p := range flag.Args() {
if err := filepath.Walk(p, scanFile); err != nil {
panic(err)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment