Commit 3ad172fb64e351049fdadb2aa02ccfd5abc50fa6

Authored by Marko Tikvić
1 parent 68e590a604
Exists in master

refactored and made public ReadFileLines()

Showing 1 changed file with 26 additions and 17 deletions   Show diff stats
... ... @@ -270,7 +270,7 @@ func initMetadata(project string) error {
270 270 }
271 271  
272 272 func LoadMetadataFromFile(path string) error {
273   - lines, err := getFileLines(path)
  273 + lines, err := ReadFileLines(path)
274 274 if err != nil {
275 275 return err
276 276 }
... ... @@ -281,8 +281,13 @@ func LoadMetadataFromFile(path string) error {
281 281 metadata = make(map[string]Payload)
282 282  
283 283 var name string
284   - for _, l := range lines {
285   - if strings.HasPrefix(l, "[") && strings.HasSuffix(l, "]") {
  284 + for i, l := range lines {
  285 + l = strings.TrimSpace(l)
  286 + if len(l) == 0 {
  287 + continue
  288 + }
  289 +
  290 + if strings.HasPrefix(l, "[") {
286 291 name = strings.Trim(l, "[]")
287 292 metadata[name] = Payload{
288 293 Lang: []Translation{
... ... @@ -295,20 +300,26 @@ func LoadMetadataFromFile(path string) error {
295 300 continue
296 301 }
297 302  
  303 + if name == "" {
  304 + return fmt.Errorf("webutility: LoadMetadataFromFile error on line %d: [no header][%s]\n", i+1, l)
  305 + }
  306 +
298 307 parts := strings.Split(l, ":")
299   - if len(parts) >= 2 {
300   - k := strings.TrimSpace(parts[0])
301   - v := strings.TrimSpace(parts[1])
302   - if v != "-" {
303   - metadata[name].Lang[0].FieldsLabels[k] = v
304   - }
  308 + if len(parts) < 2 {
  309 + return fmt.Errorf("webutility: LoadMetadataFromFile error on line %d: [invalid format][%s]\n", i+1, l)
  310 + }
  311 +
  312 + k := strings.TrimSpace(parts[0])
  313 + v := strings.TrimSpace(parts[1])
  314 + if v != "-" {
  315 + metadata[name].Lang[0].FieldsLabels[k] = v
305 316 }
306 317 }
307 318  
308 319 return nil
309 320 }
310 321  
311   -func getFileLines(path string) ([]string, error) {
  322 +func ReadFileLines(path string) ([]string, error) {
312 323 f, err := os.Open(path)
313 324 if err != nil {
314 325 return nil, err
... ... @@ -318,21 +329,19 @@ func getFileLines(path string) ([]string, error) {
318 329 var s strings.Builder
319 330 for {
320 331 buf := make([]byte, 1024)
321   - _, err := f.Read(buf)
  332 + n, err := f.Read(buf)
322 333 if err != nil {
323 334 if err == io.EOF {
324   - s.Write(buf)
325 335 break
326   - } else {
327   - return nil, err
328 336 }
  337 +
  338 + return nil, err
329 339 }
330 340  
331   - s.Write(buf)
  341 + s.Write(buf[:n])
332 342 }
333 343  
334   - str := s.String()
335   - lines := strings.Split(str, "\n")
  344 + lines := strings.Split(s.String(), "\n")
336 345  
337 346 return lines, nil
338 347 }
... ...