github.com/apcera/util@v0.0.0-20180322191801-7a50bc84ee48/proc/parser.go (about)

     1  // Copyright 2013 Apcera Inc. All rights reserved.
     2  
     3  package proc
     4  
     5  import (
     6  	"io/ioutil"
     7  	"os"
     8  	"strconv"
     9  	"strings"
    10  )
    11  
    12  // ReadInt64 reads one int64 number from the first line of a file.
    13  func ReadInt64(file string) (int64, error) {
    14  	f, err := os.Open(file)
    15  	if err != nil {
    16  		return 0, err
    17  	}
    18  	defer f.Close()
    19  
    20  	buf := make([]byte, 19)
    21  	n, err := f.Read(buf)
    22  	if err != nil {
    23  		return 0, err
    24  	}
    25  
    26  	p := strings.Split(string(buf[0:n]), "\n")
    27  	v, err := strconv.ParseInt(p[0], 10, 64)
    28  	if err != nil {
    29  		return 0, err
    30  	}
    31  
    32  	return v, nil
    33  }
    34  
    35  // Parses the given file into various elements. This function assumes basic
    36  // white space semantics (' ' and '\t' for column splitting, and '\n' for
    37  // row splitting.
    38  func ParseSimpleProcFile(
    39  	filename string,
    40  	lf func(index int, line string) error,
    41  	ef func(line, index int, elm string) error) error {
    42  
    43  	fd, err := os.Open(filename)
    44  	if err != nil {
    45  		return err
    46  	}
    47  	defer fd.Close()
    48  
    49  	contentsBytes, err := ioutil.ReadAll(fd)
    50  	if err != nil {
    51  		return err
    52  	}
    53  
    54  	// Setup base handlers if they were passed in as nil.
    55  	if lf == nil {
    56  		lf = func(index int, line string) error { return nil }
    57  	}
    58  	if ef == nil {
    59  		ef = func(line, index int, elm string) error { return nil }
    60  	}
    61  
    62  	contents := string(contentsBytes)
    63  	lines := strings.Split(contents, "\n")
    64  
    65  	for li, l := range lines {
    66  		for ei, e := range strings.Fields(l) {
    67  			if err := ef(li, ei, e); err != nil {
    68  				return err
    69  			}
    70  		}
    71  		if err := lf(li, l); err != nil {
    72  			return err
    73  		}
    74  	}
    75  
    76  	return nil
    77  }