Skip to content

Instantly share code, notes, and snippets.

@ymtdzzz
Created Nov 5, 2022
Embed
What would you like to do?
extract dependency from dephend result
package main
import (
"bufio"
"flag"
"fmt"
"io/ioutil"
"os"
"regexp"
"strings"
)
var (
inputPath string
className string
outputPath string
dependingRegex = regexp.MustCompile(`---> .*Library$`)
cache map[string]ResultSet = map[string]ResultSet{}
)
type ResultSet struct {
classNames []string
rows []string
}
func init() {
flag.StringVar(&inputPath, "input", "", "input file path")
flag.StringVar(&className, "class", "", "search class name")
flag.StringVar(&outputPath, "output", "", "output file path")
}
func main() {
flag.Parse()
if inputPath == "" || className == "" || outputPath == "" {
fmt.Println("all args cannot be empty.")
flag.CommandLine.PrintDefaults()
os.Exit(2)
}
data, err := ioutil.ReadFile(inputPath)
if err != nil {
panic(err)
}
content := string(data)
_, rows := recur(className, content, []string{}, []string{})
file, err := os.Create(outputPath)
if err != nil {
panic(err)
}
defer file.Close()
for _, r := range rows {
_, err := file.WriteString(fmt.Sprintln(r))
if err != nil {
panic(err)
}
}
}
func recur(class string, input string, progClass, progRow []string) ([]string, []string) {
classes, rows := findDependingClasses(class, input)
if len(classes) == 0 {
return progClass, progRow
}
progClass = append(progClass, classes...)
progRow = append(progRow, rows...)
for _, c := range classes {
a, b := recur(c, input, []string{}, []string{})
progClass = append(progClass, a...)
progRow = append(progRow, b...)
}
return progClass, progRow
}
func findDependingClasses(class string, input string) (resultClass, resultRow []string) {
fmt.Printf("class: %s, input: %s\n", class, input)
if val, ok := cache[class]; ok {
fmt.Println("cache hit")
return val.classNames, val.rows
}
regex := regexp.MustCompile(fmt.Sprintf(`--> .*%s$`, strings.ReplaceAll(class, `\`, `\/`)))
scanner := bufio.NewScanner(strings.NewReader(input))
for scanner.Scan() {
row := scanner.Text()
if regex.MatchString(row) {
resultRow = append(resultRow, row)
splitRow := strings.Split(row, "-->")
resultClass = append(resultClass, strings.TrimSpace(splitRow[0]))
}
}
cache[class] = ResultSet{
classNames: resultClass,
rows: resultRow,
}
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment