diff --git a/payload.go b/payload.go index 81b1366..b233e4f 100644 --- a/payload.go +++ b/payload.go @@ -270,7 +270,7 @@ func initMetadata(project string) error { } func LoadMetadataFromFile(path string) error { - lines, err := getFileLines(path) + lines, err := ReadFileLines(path) if err != nil { return err } @@ -281,8 +281,13 @@ func LoadMetadataFromFile(path string) error { metadata = make(map[string]Payload) var name string - for _, l := range lines { - if strings.HasPrefix(l, "[") && strings.HasSuffix(l, "]") { + for i, l := range lines { + l = strings.TrimSpace(l) + if len(l) == 0 { + continue + } + + if strings.HasPrefix(l, "[") { name = strings.Trim(l, "[]") metadata[name] = Payload{ Lang: []Translation{ @@ -295,20 +300,26 @@ func LoadMetadataFromFile(path string) error { continue } + if name == "" { + return fmt.Errorf("webutility: LoadMetadataFromFile error on line %d: [no header][%s]\n", i+1, l) + } + parts := strings.Split(l, ":") - if len(parts) >= 2 { - k := strings.TrimSpace(parts[0]) - v := strings.TrimSpace(parts[1]) - if v != "-" { - metadata[name].Lang[0].FieldsLabels[k] = v - } + if len(parts) < 2 { + return fmt.Errorf("webutility: LoadMetadataFromFile error on line %d: [invalid format][%s]\n", i+1, l) + } + + k := strings.TrimSpace(parts[0]) + v := strings.TrimSpace(parts[1]) + if v != "-" { + metadata[name].Lang[0].FieldsLabels[k] = v } } return nil } -func getFileLines(path string) ([]string, error) { +func ReadFileLines(path string) ([]string, error) { f, err := os.Open(path) if err != nil { return nil, err @@ -318,21 +329,19 @@ func getFileLines(path string) ([]string, error) { var s strings.Builder for { buf := make([]byte, 1024) - _, err := f.Read(buf) + n, err := f.Read(buf) if err != nil { if err == io.EOF { - s.Write(buf) break - } else { - return nil, err } + + return nil, err } - s.Write(buf) + s.Write(buf[:n]) } - str := s.String() - lines := strings.Split(str, "\n") + lines := strings.Split(s.String(), "\n") return lines, nil }