From cca5052df878e7ae7c15fd96a21ec1871f5f4746 Mon Sep 17 00:00:00 2001 From: lorenzhohermuth Date: Tue, 14 May 2024 14:13:59 +0200 Subject: [PATCH] better architecture for file system --- cmd/registry.go | 7 ++++--- internal/splitter/objects.go | 20 ++++++++++++++++++++ internal/splitter/splitter.go | 27 ++++++++++++++++----------- 3 files changed, 40 insertions(+), 14 deletions(-) create mode 100644 internal/splitter/objects.go diff --git a/cmd/registry.go b/cmd/registry.go index 47ad8f0..79d4da5 100644 --- a/cmd/registry.go +++ b/cmd/registry.go @@ -20,14 +20,15 @@ var registryCmd = &cobra.Command{ Long: `Distributes tokens from a file or a direcotry into a HashMap and prints the Map`, Run: func(cmd *cobra.Command, args []string) { - tokens := splitter.SplitFile(args[0]) + entrys := splitter.SplitFile(args[0]) tr := registry.TokenRegistry{ Map: make(map[string]int64)} - tr.DistributeTokens(tokens) + + tr.DistributeTokens(entrys.CreateMatrix()) tw := new(tabwriter.Writer) tw.Init(os.Stdout, 0, 8, 0, '\t', 0) for v, k := range tr.Map { - fmt.Fprintf(tw, "value: \"%s\" \t key: %b \n", v, k) + fmt.Fprintf(tw, "value: \"%s\" \t key: %d \n", v, k) } tw.Flush() }, diff --git a/internal/splitter/objects.go b/internal/splitter/objects.go new file mode 100644 index 0000000..eaeac08 --- /dev/null +++ b/internal/splitter/objects.go @@ -0,0 +1,20 @@ +package splitter + +type RegistryEntry struct { + Name string + ChildEntrys []RegistryEntry + Tokens []string +} + +func (re RegistryEntry) CreateMatrix() [][]string { + if re.ChildEntrys != nil { + mat := [][]string{} + for _, child := range re.ChildEntrys { + mat = addToMatrix(mat, child.CreateMatrix()) + } + return mat + } else { + return [][]string{re.Tokens} + } +} + diff --git a/internal/splitter/splitter.go b/internal/splitter/splitter.go index 50d35bd..c34fec0 100644 --- a/internal/splitter/splitter.go +++ b/internal/splitter/splitter.go @@ -6,10 +6,7 @@ import ( "strings" ) -func SplitFile(path string) [][]string { - if path == "" { - return make([][]string, 0) - } +func SplitFile(path string) RegistryEntry { info, err := os.Stat(path) if err != nil { panic(err) @@ -17,19 +14,27 @@ func SplitFile(path string) [][]string { if info.IsDir() { paths := getFilePathsFromDir(path) - matrix := make([][]string, len(paths)) + arr := make([]RegistryEntry, len(paths)) + for _, filePath := range paths { - matrix = addToMatrix(matrix, SplitFile(filePath)) + if filePath != "" { + arr = append(arr, SplitFile(filePath)) + } + } + return RegistryEntry{ + Name: info.Name(), + Tokens: nil, + ChildEntrys: arr, } - return matrix } else { - matrix := make([][]string, 1) - matrix[0] = tokenize(getFileContent(path)) - return matrix + return RegistryEntry{ + Name: info.Name(), + Tokens: tokenize(getFileContent(path)), + ChildEntrys: nil, + } } } - func getFileContent(path string) string{ data, err := os.ReadFile(path) if err != nil {