gochart/chart_parser.go

105 lines
2.1 KiB
Go
Raw Permalink Normal View History

2014-12-26 20:25:03 +08:00
package main
import (
"errors"
2017-03-16 16:44:58 +08:00
"io/ioutil"
"log"
2014-12-26 20:25:03 +08:00
"os"
"path/filepath"
2017-03-16 16:44:58 +08:00
"strings"
2017-03-21 18:34:07 +08:00
"github.com/zieckey/goini"
2014-12-26 20:25:03 +08:00
)
const DataPrefix = "Data|"
2017-03-16 16:44:58 +08:00
const emptyRunes = " \r\t\v"
2014-12-26 20:25:03 +08:00
type ChartIf interface {
2017-03-16 16:44:58 +08:00
Parse(ini *goini.INI, file string) (map[string]string, error)
2014-12-26 20:25:03 +08:00
Template() string
}
type TemplateArgs struct {
args map[string]string
tmpl string
}
func Parse(file string) (tt TemplateArgs, err error) {
2014-12-26 20:25:03 +08:00
ini := goini.New()
err = ini.ParseFile(file)
if err != nil {
return tt, err
2014-12-26 20:25:03 +08:00
}
t, _ := ini.Get("ChartType")
if f, ok := ChartHandlers[t]; ok {
2017-03-16 16:44:58 +08:00
tt.args, err = f.Parse(ini, file)
tt.tmpl = f.Template()
2014-12-26 20:25:03 +08:00
}
return tt, err
2014-12-26 20:25:03 +08:00
}
func LookupChartFiles(dir string) ([]string, error) {
var files []string = make([]string, 0, 5)
err := filepath.Walk(dir, func(path string, f os.FileInfo, err error) error {
if f == nil {
return err
}
if f.IsDir() {
return nil
}
if ok, err := filepath.Match("*.chart", f.Name()); err != nil {
return err
} else if ok {
2017-03-10 19:27:36 +08:00
log.Printf("Add chart file %v", path)
2014-12-26 20:25:03 +08:00
files = append(files, path)
}
return nil
})
if len(files) == 0 {
return files, errors.New("Not found any *.chart files")
}
2014-12-26 20:25:03 +08:00
return files, err
}
2017-03-16 16:44:58 +08:00
/**
* 读取配置文件获取有序map
*
* @return order map
* @param {[type]} ini string [description]
*/
func LoadConfGetOrderMap(configFile string) ([]string, map[string]string, error) {
stream, err := ioutil.ReadFile(configFile)
if err != nil {
return nil, nil, errors.New("cannot load config file")
}
content := string(stream)
confMap := make(map[string]string)
mapkeys := make([]string, 0)
lines := strings.Split(content, "\n")
for _, line := range lines {
line = strings.Trim(line, emptyRunes)
//过滤注释 //过滤非DataPrefix
if line == "" || line[0] == '#' || !strings.HasPrefix(line, DataPrefix) {
continue
}
//过滤
parts := strings.SplitN(line, "=", 2)
if len(parts) == 2 {
key := strings.Trim(parts[0], emptyRunes)
value := strings.Trim(parts[1], emptyRunes)
mapkeys = append(mapkeys, key)
confMap[key] = value
}
}
return mapkeys, confMap, nil
}