1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- package cgf
- import (
- "encoding/json"
- "fmt"
- "io"
- "os"
- "path/filepath"
- "sync"
- "sync/atomic"
- "git.wecise.com/wecise/cgimport/cgf/reader"
- "git.wecise.com/wecise/util/filewalker"
- "git.wecise.com/wecise/util/merrs"
- "git.wecise.com/wecise/util/rc"
- )
- func ImportDir(datapath string, parallel int) (filescount, recordscount int64, err error) {
- // 遍历文件目录
- var cgirc = rc.NewRoutinesController("", parallel)
- var wg sync.WaitGroup
- fw, e := filewalker.NewFileWalker([]string{datapath}, ".*")
- if e != nil {
- err = e
- return
- }
- e = fw.List(func(basedir string, fpath string) bool {
- if err != nil {
- return false
- }
- filename := filepath.Join(basedir, fpath)
- wg.Add(1)
- cgirc.ConcurCall(1,
- func() {
- defer wg.Done()
- records, e := ImportFile(filename)
- if e != nil {
- err = e
- return
- }
- atomic.AddInt64(&filescount, 1)
- atomic.AddInt64(&recordscount, int64(records))
- },
- )
- return true
- })
- wg.Wait()
- if e != nil {
- err = e
- return
- }
- return
- }
- func ImportFile(filepath string) (blockcount int, err error) {
- f, e := os.Open(filepath)
- if e != nil {
- return blockcount, merrs.NewError(e, merrs.SSMaps{{"filename": filepath}})
- }
- defer f.Close()
- return importReader(filepath, f)
- }
- func importReader(filename string, buf io.Reader) (blockcount int, err error) {
- br, e := reader.NewBlockReader(filename, buf)
- if e != nil {
- return blockcount, merrs.NewError(e, merrs.SSMaps{{"filename": filename}})
- }
- for {
- block, linecount, e := br.ReadBlock()
- if e != nil {
- return blockcount, merrs.NewError(e, merrs.SSMaps{{"filename": filename}, {"line": fmt.Sprint(linecount)}})
- }
- if block == nil {
- return
- }
- e = importBlock(block, filename, linecount)
- if e != nil {
- return blockcount, merrs.NewError(e, merrs.SSMaps{{"filename": filename}, {"line": fmt.Sprint(linecount)}})
- }
- blockcount++
- }
- }
- func importBlock(block map[string]any, filename string, linecount int) (err error) {
- bs, e := json.MarshalIndent(block, "", " ")
- if e != nil {
- return e
- }
- fmt.Println(fmt.Sprint("import ", filename, "[", linecount, "]:", string(bs)))
- return
- }
|