cgf.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package cgf
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "os"
  7. "path/filepath"
  8. "sync"
  9. "sync/atomic"
  10. "git.wecise.com/wecise/cgimport/cgf/reader"
  11. "git.wecise.com/wecise/util/filewalker"
  12. "git.wecise.com/wecise/util/rc"
  13. )
  14. func ImportDir(datapath string, parallel int) (filescount, recordscount int64, err error) {
  15. // 遍历文件目录
  16. var cgirc = rc.NewRoutinesController("", parallel)
  17. var wg sync.WaitGroup
  18. fw, e := filewalker.NewFileWalker([]string{datapath}, ".*")
  19. if e != nil {
  20. err = e
  21. return
  22. }
  23. e = fw.List(func(basedir string, fpath string) bool {
  24. if err != nil {
  25. return false
  26. }
  27. filename := filepath.Join(basedir, fpath)
  28. wg.Add(1)
  29. cgirc.ConcurCall(1,
  30. func() {
  31. defer wg.Done()
  32. records, e := ImportFile(filename)
  33. if e != nil {
  34. err = e
  35. return
  36. }
  37. atomic.AddInt64(&filescount, 1)
  38. atomic.AddInt64(&recordscount, int64(records))
  39. },
  40. )
  41. return true
  42. })
  43. wg.Wait()
  44. if e != nil {
  45. err = e
  46. return
  47. }
  48. return
  49. }
  50. func ImportFile(filepath string) (blockcount int, err error) {
  51. f, e := os.Open(filepath)
  52. if e != nil {
  53. return blockcount, e
  54. }
  55. defer f.Close()
  56. return importReader(f)
  57. }
  58. func importReader(buf io.Reader) (blockcount int, err error) {
  59. br := reader.NewBlockReader(buf)
  60. for {
  61. block, e := br.ReadBlock()
  62. if e != nil {
  63. return blockcount, e
  64. }
  65. if block == nil {
  66. return
  67. }
  68. e = importBlock(block)
  69. if e != nil {
  70. return blockcount, e
  71. }
  72. blockcount++
  73. }
  74. }
  75. func importBlock(block map[string]any) (err error) {
  76. bs, e := json.MarshalIndent(block, "", " ")
  77. if e != nil {
  78. return e
  79. }
  80. fmt.Println("import:", string(bs))
  81. return
  82. }