engineclient.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. package client
  2. import (
  3. "bytes"
  4. "compress/gzip"
  5. "encoding/json"
  6. "encoding/xml"
  7. "fmt"
  8. "git.qianqiusoft.com/qianqiusoft/light-apiengine/env"
  9. "git.qianqiusoft.com/qianqiusoft/light-apiengine/utils"
  10. "io"
  11. "io/ioutil"
  12. "mime/multipart"
  13. "net/http"
  14. "os"
  15. "path/filepath"
  16. "strings"
  17. )
  18. type EngineClient struct {
  19. ProjectName string
  20. ServerUrl string
  21. }
  22. type ResponeResult struct {
  23. Code int32 `json:"code"`
  24. //描述
  25. Msg string `json:"msg"`
  26. //数据
  27. Data []GenerateResult `json:"data"`
  28. }
  29. type GenerateResult struct {
  30. Name string `json:"name"`
  31. Content []byte `json:"content"`
  32. Type string `json:"type"`
  33. }
  34. func NewEngineClient(project_name string, server_url string) *EngineClient {
  35. return &EngineClient{project_name, server_url}
  36. }
  37. func (c *EngineClient) InitDefalutFile(project_name string) {
  38. c.ProjectName = project_name
  39. os.MkdirAll("controllers/gen", os.ModePerm)
  40. os.MkdirAll("controllers/partial", os.ModePerm)
  41. os.MkdirAll("models", os.ModePerm)
  42. os.MkdirAll("routers", os.ModePerm)
  43. os.MkdirAll("conf", os.ModePerm)
  44. os.MkdirAll("sqlconfig", os.ModePerm)
  45. //os.MkdirAll("sqlconfig/gen", os.ModePerm)
  46. os.MkdirAll("doc", os.ModePerm)
  47. os.MkdirAll("web", os.ModePerm)
  48. _, err := os.Stat(project_name + ".xml")
  49. if os.IsNotExist(err) {
  50. xml := strings.Replace(DefaultProjectXML, "{project_name}", project_name, -1)
  51. ioutil.WriteFile(project_name+".xml", []byte(xml), os.ModePerm)
  52. }
  53. _, err = os.Stat(project_name + ".xsd")
  54. if os.IsNotExist(err) {
  55. ioutil.WriteFile(project_name+".xsd", []byte(XSD), os.ModePerm)
  56. }
  57. _, err = os.Stat("Dockerfile")
  58. if os.IsNotExist(err) {
  59. xml := strings.Replace(DockerFile, "{project_name}", project_name, -1)
  60. ioutil.WriteFile("Dockerfile", []byte(xml), os.ModePerm)
  61. }
  62. _, err = os.Stat("build_docker.sh")
  63. if os.IsNotExist(err) {
  64. xml := strings.Replace(BuildSH, "{project_name}", project_name, -1)
  65. ioutil.WriteFile("build_docker.sh", []byte(xml), os.ModePerm)
  66. }
  67. _, err = os.Stat("README.md")
  68. if os.IsNotExist(err) {
  69. xml := strings.Replace(MARK_DOWN, "{project_name}", project_name, -1)
  70. xml = strings.Replace(xml, "{!}", "`", -1)
  71. ioutil.WriteFile("README.md", []byte(xml), os.ModePerm)
  72. }
  73. }
  74. func (c *EngineClient) GenerateCurrentProject() {
  75. c.InitDefalutFile(c.ProjectName)
  76. // 0---0
  77. //path, _ := utils.GetCurrentPath()
  78. //c.Generate(path + c.ProjectName + ".xml")
  79. projMainXmlFileTemp := c.MergeXmlToSingle()
  80. if projMainXmlFileTemp == "" {
  81. fmt.Println("projMainXmlFileTemp is empty")
  82. return
  83. }
  84. c.Generate(projMainXmlFileTemp)
  85. path, _ := utils.GetCurrentPath()
  86. CopyDir(env.Get("GOPATH", "")+"/src/git.qianqiusoft.com/qianqiusoft/light-apiengine/sqlconfig", path+"sqlconfig")
  87. }
  88. func (c *EngineClient) GenerateToPath(xmlfile string,dest_path string) {
  89. var result ResponeResult
  90. server := "http://qianqiusoft.com:6166"
  91. if c.ServerUrl != "" {
  92. server = c.ServerUrl
  93. }
  94. server += "/api/v1/develop/generate"
  95. bs := DoRequest(xmlfile, server)
  96. if bs != nil {
  97. err := json.Unmarshal(bs.Bytes(), &result)
  98. if err != nil {
  99. fmt.Println(err.Error())
  100. }
  101. for i := 0; i < len(result.Data); i++ {
  102. var b bytes.Buffer
  103. b.Write(result.Data[i].Content)
  104. unzip := unzipbytes(&b)
  105. result.Data[i].Content = unzip.Bytes()
  106. }
  107. for i := 0; i < len(result.Data); i++ {
  108. path := result.Data[i].Name
  109. //fmt.Println(path)
  110. path = path[len(c.ProjectName)+1:]
  111. path = dest_path + path
  112. fmt.Println(path)
  113. ft := result.Data[i].Type
  114. if result.Data[i].Type == "main" {
  115. } else if ft == "config" || ft == "ci" {
  116. _, err := os.Stat(path)
  117. if err == nil {
  118. fmt.Println(path + "已经存在,忽略...")
  119. } else {
  120. ioutil.WriteFile(path, result.Data[i].Content, os.ModePerm)
  121. }
  122. } else if ft == "controllers" {
  123. os.MkdirAll(filepath.Dir(path), os.ModePerm)
  124. if strings.Index(path, "_gen.go") > 0 {
  125. ioutil.WriteFile(path, result.Data[i].Content, os.ModePerm)
  126. } else {
  127. _, err := os.Stat(path)
  128. if err == nil {
  129. ioutil.WriteFile(path+"_new", result.Data[i].Content, os.ModePerm)
  130. } else if os.IsNotExist(err) {
  131. ioutil.WriteFile(path, result.Data[i].Content, os.ModePerm)
  132. }
  133. }
  134. } else if ft == "routers" {
  135. os.MkdirAll(filepath.Dir(path), os.ModePerm)
  136. ioutil.WriteFile(path, result.Data[i].Content, os.ModePerm)
  137. } else if ft =="sql"{
  138. if strings.Index(path, "_gen.xml") > 0 {
  139. os.MkdirAll(filepath.Dir(path), os.ModePerm)
  140. ioutil.WriteFile(path, result.Data[i].Content, os.ModePerm)
  141. } else {
  142. _, err := os.Stat(path)
  143. if err == nil {
  144. //ioutil.WriteFile(path+"_new", result.Data[i].Content, os.ModePerm)
  145. } else if os.IsNotExist(err) {
  146. os.MkdirAll(filepath.Dir(path), os.ModePerm)
  147. ioutil.WriteFile(path, result.Data[i].Content, os.ModePerm)
  148. }
  149. }
  150. } else{
  151. os.MkdirAll(filepath.Dir(path), os.ModePerm)
  152. err := ioutil.WriteFile(path, result.Data[i].Content, os.ModePerm)
  153. if err != nil {
  154. fmt.Println(err.Error())
  155. }
  156. }
  157. }
  158. }
  159. }
  160. func (c *EngineClient) Generate(xmlfile string) {
  161. c.GenerateToPath(xmlfile, "")
  162. //c.GenSwagger(xmlfile)
  163. }
  164. func (c *EngineClient) GenSwagger(xmlfile string){
  165. server := "http://swagger.pusher.i2erp.cn"
  166. server += "/api/v1/upload"
  167. fmt.Println("===========================================================================>11")
  168. request, err := newfileUploadRequest(server, nil, "xmlfile", xmlfile)
  169. if err != nil {
  170. fmt.Println(err)
  171. }
  172. client := &http.Client{}
  173. resp, err := client.Do(request)
  174. if err != nil{
  175. fmt.Println("===========================================================================>", err.Error())
  176. }else{
  177. defer resp.Body.Close()
  178. bytess, err := ioutil.ReadAll(resp.Body)
  179. if err != nil{
  180. fmt.Println("=======================================>ioutil.ReadAll error", err.Error())
  181. }else{
  182. fmt.Println("=======================================>", string(bytess))
  183. }
  184. }
  185. }
  186. /**
  187. * @brief: merge xml
  188. * @param: none
  189. * @return: the path of final xml
  190. */
  191. func (c *EngineClient)MergeXmlToSingle()string{
  192. path, _ := utils.GetCurrentPath()
  193. // e.g.: c:/gopath/src/hanghua_background_proj
  194. projDir := fmt.Sprintf("%s%s.proj", path, c.ProjectName)
  195. projMainXmlFile := projDir + "/" + c.ProjectName + ".xml"
  196. projMainXmlFileTemp := projDir + "/" + c.ProjectName + "_temp.xml"
  197. _, err := os.Stat(projMainXmlFileTemp)
  198. if os.IsNotExist(err) {
  199. fmt.Println("-------------------------->remove project main file temp")
  200. os.Remove(projMainXmlFileTemp) // remove
  201. }
  202. _, err = os.Stat(projMainXmlFile)
  203. if os.IsNotExist(err) {
  204. fmt.Println("main xml file of " + c.ProjectName + " does not exist")
  205. return ""
  206. }
  207. app := XmlApplication{}
  208. bytess, _ := ioutil.ReadFile(projMainXmlFile)
  209. err = xml.Unmarshal(bytess, &app)
  210. if err != nil{
  211. fmt.Println("xml.Unmarshal(bytess, &app) error " + err.Error())
  212. return ""
  213. }
  214. controllers, err := scanControllers(projDir + "/controllers")
  215. if err != nil{
  216. fmt.Println("scanControllers error " + err.Error())
  217. return ""
  218. }
  219. beans, err := scanBeans(projDir + "/beans")
  220. if err != nil{
  221. fmt.Println("scanBeans error " + err.Error())
  222. return ""
  223. }
  224. tables, err := scanTables(projDir + "/tables")
  225. if err != nil{
  226. fmt.Println("scanTables error " + err.Error())
  227. return ""
  228. }
  229. if app.Controllers.ControllerList == nil{
  230. app.Controllers.ControllerList = []XmlController{}
  231. }
  232. for i := range controllers{
  233. app.Controllers.ControllerList = append(app.Controllers.ControllerList, controllers[i])
  234. }
  235. createVueApisFolder(app.Controllers.ControllerList)
  236. if app.Beans.BeanList == nil{
  237. app.Beans.BeanList = []XmlBean{}
  238. }
  239. for i := range beans{
  240. app.Beans.BeanList = append(app.Beans.BeanList, beans[i])
  241. }
  242. if app.Tables.TableList == nil{
  243. app.Tables.TableList = []XmlTable{}
  244. }
  245. for i := range tables{
  246. app.Tables.TableList = append(app.Tables.TableList, tables[i])
  247. }
  248. bytess, err = xml.Marshal(app)
  249. if err != nil{
  250. fmt.Println("xml.Marshal(app) error " + err.Error())
  251. return ""
  252. }
  253. err = ioutil.WriteFile(projMainXmlFileTemp, bytess,os.ModePerm)
  254. if err != nil{
  255. fmt.Println("ioutil.WriteFile(projMainXmlFileTemp, bytess,os.ModePerm) error " + err.Error())
  256. return ""
  257. }
  258. _, err = os.Stat(projMainXmlFileTemp)
  259. if os.IsNotExist(err) {
  260. fmt.Println("main xml file temp of " + c.ProjectName + " does not exist")
  261. return ""
  262. }else{
  263. fmt.Println("main xml file temp of " + c.ProjectName + " exist")
  264. }
  265. return projMainXmlFileTemp
  266. }
  267. func scanControllers(ctrldir string) ([]XmlController, error){
  268. _, err := os.Stat(ctrldir)
  269. if os.IsNotExist(err) {
  270. fmt.Println("controller dir does not exist", err.Error())
  271. return nil, err
  272. }
  273. controllers := []XmlController{}
  274. filePaths := []string{}
  275. filePaths, err = getAllFile(strings.TrimSuffix(ctrldir, "/"), filePaths)
  276. if err != nil{
  277. fmt.Println("controller getAllFile error", err.Error())
  278. return nil, err
  279. }
  280. for i := range filePaths {
  281. ctrl := XmlController{}
  282. ctrlfile := filePaths[i]
  283. _, err = os.Stat(ctrlfile)
  284. if os.IsNotExist(err) {
  285. fmt.Println("controller xml file " + ctrlfile + " does not exist")
  286. return controllers, err
  287. }
  288. ctrlfile = strings.Replace(ctrlfile, "\\", "/", -1)
  289. arr := strings.Split(ctrlfile, "/")
  290. bytess, _ := ioutil.ReadFile(ctrlfile)
  291. err = xml.Unmarshal(bytess, &ctrl)
  292. if err != nil {
  293. fmt.Println("xml.Unmarshal(bytess, &app) error " + err.Error())
  294. return controllers, err
  295. }
  296. // get sub dir name
  297. if arr[len(arr) - 2] != "controllers"{
  298. // if sub dir is not controllers, set the dir attr
  299. ctrl.Dir = arr[len(arr) - 2]
  300. }
  301. controllers = append(controllers, ctrl)
  302. }
  303. return controllers, nil
  304. //err = filepath.Walk(ctrldir, func(path string, info os.FileInfo, err error) error {
  305. //
  306. // if err != nil {
  307. // return filepath.SkipDir
  308. // }
  309. // if info.IsDir(){
  310. // return nil
  311. // }
  312. //
  313. // ctrl := XmlController{}
  314. // ctrlfile := ctrldir + "/" + info.Name()
  315. // _, err = os.Stat(ctrlfile)
  316. // if os.IsNotExist(err) {
  317. // fmt.Println("controller xml file " + ctrlfile + " does not exist")
  318. // return filepath.SkipDir
  319. // }
  320. // bytess, _ := ioutil.ReadFile(ctrlfile)
  321. // err = xml.Unmarshal(bytess, &ctrl)
  322. // if err != nil{
  323. // fmt.Println("xml.Unmarshal(bytess, &app) error " + err.Error())
  324. // return filepath.SkipDir
  325. // }
  326. // controllers = append(controllers, ctrl)
  327. //
  328. // return nil
  329. //})
  330. //return controllers, err
  331. }
  332. func scanBeans(ctrldir string) ([]XmlBean, error){
  333. _, err := os.Stat(ctrldir)
  334. if os.IsNotExist(err) {
  335. fmt.Println("controller dir does not exist")
  336. return nil, err
  337. }
  338. beans := []XmlBean{}
  339. filePaths := []string{}
  340. filePaths, err = getAllFile(strings.TrimSuffix(ctrldir, "/"), filePaths)
  341. if err != nil{
  342. fmt.Println("controller getAllFile error", err.Error())
  343. return nil, err
  344. }
  345. for i := range filePaths {
  346. ctrl := XmlBean{}
  347. ctrlfile := filePaths[i]
  348. _, err = os.Stat(ctrlfile)
  349. if os.IsNotExist(err) {
  350. fmt.Println("controller xml file " + ctrlfile + " does not exist")
  351. return beans, err
  352. }
  353. bytess, _ := ioutil.ReadFile(ctrlfile)
  354. err = xml.Unmarshal(bytess, &ctrl)
  355. if err != nil {
  356. fmt.Println("xml.Unmarshal(bytess, &app) error " + err.Error())
  357. return beans, err
  358. }
  359. beans = append(beans, ctrl)
  360. }
  361. return beans, nil
  362. //err = filepath.Walk(ctrldir, func(path string, info os.FileInfo, err error) error {
  363. //
  364. // if err != nil {
  365. // return filepath.SkipDir
  366. // }
  367. // if info.IsDir(){
  368. // return nil
  369. // }
  370. //
  371. // bean := XmlBean{}
  372. // beanfile := ctrldir + "/" + info.Name()
  373. // _, err = os.Stat(beanfile)
  374. // if os.IsNotExist(err) {
  375. // fmt.Println("controller xml file " + beanfile + " does not exist")
  376. // return filepath.SkipDir
  377. // }
  378. // bytess, _ := ioutil.ReadFile(beanfile)
  379. // err = xml.Unmarshal(bytess, &bean)
  380. // if err != nil{
  381. // fmt.Println("xml.Unmarshal(bytess, &app) error " + err.Error())
  382. // return filepath.SkipDir
  383. // }
  384. // beans = append(beans, bean)
  385. //
  386. // return nil
  387. //})
  388. //
  389. //return beans, err
  390. }
  391. func scanTables(ctrldir string) ([]XmlTable, error){
  392. _, err := os.Stat(ctrldir)
  393. if os.IsNotExist(err) {
  394. fmt.Println("controller dir does not exist")
  395. return nil, err
  396. }
  397. tables := []XmlTable{}
  398. filePaths := []string{}
  399. filePaths, err = getAllFile(strings.TrimSuffix(ctrldir, "/"), filePaths)
  400. if err != nil{
  401. fmt.Println("controller getAllFile error", err.Error())
  402. return nil, err
  403. }
  404. for i := range filePaths {
  405. ctrl := XmlTable{}
  406. ctrlfile := filePaths[i]
  407. _, err = os.Stat(ctrlfile)
  408. if os.IsNotExist(err) {
  409. fmt.Println("controller xml file " + ctrlfile + " does not exist")
  410. return tables, err
  411. }
  412. bytess, _ := ioutil.ReadFile(ctrlfile)
  413. err = xml.Unmarshal(bytess, &ctrl)
  414. if err != nil {
  415. fmt.Println("xml.Unmarshal(bytess, &app) error " + err.Error())
  416. return tables, err
  417. }
  418. tables = append(tables, ctrl)
  419. }
  420. return tables, nil
  421. //err = filepath.Walk(ctrldir, func(path string, info os.FileInfo, err error) error {
  422. //
  423. // if err != nil {
  424. // return filepath.SkipDir
  425. // }
  426. // if info.IsDir(){
  427. // return nil
  428. // }
  429. //
  430. // table := XmlTable{}
  431. // tablefile := ctrldir + "/" + info.Name()
  432. // _, err = os.Stat(tablefile)
  433. // if os.IsNotExist(err) {
  434. // fmt.Println("controller xml file " + tablefile + " does not exist")
  435. // return filepath.SkipDir
  436. // }
  437. // bytess, _ := ioutil.ReadFile(tablefile)
  438. // err = xml.Unmarshal(bytess, &table)
  439. // if err != nil{
  440. // fmt.Println("xml.Unmarshal(bytess, &app) error " + err.Error())
  441. // return filepath.SkipDir
  442. // }
  443. // tables = append(tables, table)
  444. //
  445. // return nil
  446. //})
  447. //
  448. //return tables, err
  449. }
  450. func createVueApisFolder(controllers []XmlController){
  451. for i := range controllers{
  452. fmt.Println("------------------------------>" + controllers[i].Name)
  453. os.MkdirAll("vue/api/modules/" + controllers[i].Name, os.ModePerm)
  454. }
  455. }
  456. func getAllFile(pathname string, s []string) ([]string, error) {
  457. rd, err := ioutil.ReadDir(pathname)
  458. if err != nil {
  459. fmt.Println("read dir fail:", err)
  460. return s, err
  461. }
  462. for _, fi := range rd {
  463. if fi.IsDir() {
  464. fullDir := pathname + "/" + fi.Name()
  465. s, err = getAllFile(fullDir, s)
  466. if err != nil {
  467. fmt.Println("read dir fail:", err)
  468. return s, err
  469. }
  470. } else {
  471. if strings.HasSuffix(strings.ToLower(fi.Name()), ".xml") {
  472. fullName := pathname + "/" + fi.Name()
  473. s = append(s, fullName)
  474. }
  475. }
  476. }
  477. return s, nil
  478. }
  479. func unzipbytes(bs *bytes.Buffer) bytes.Buffer {
  480. r, _ := gzip.NewReader(bs)
  481. defer r.Close()
  482. var b bytes.Buffer
  483. b.ReadFrom(r)
  484. //undatas, _ := ioutil.ReadAll(r)
  485. //fmt.Println("ungzip size:", len(undatas))
  486. return b
  487. }
  488. func DoRequest(xmlfile string, server string) *bytes.Buffer {
  489. request, err := newfileUploadRequest(server, nil, "xmlfile", xmlfile)
  490. if err != nil {
  491. fmt.Println(err)
  492. }
  493. client := &http.Client{}
  494. resp, err := client.Do(request)
  495. if err != nil {
  496. fmt.Println(err)
  497. } else {
  498. body := &bytes.Buffer{}
  499. _, err := body.ReadFrom(resp.Body)
  500. if err != nil {
  501. fmt.Println(err)
  502. }
  503. resp.Body.Close()
  504. fmt.Println(resp.StatusCode)
  505. fmt.Println(resp.Header)
  506. //fmt.Println(body)
  507. return body
  508. }
  509. return nil
  510. }
  511. func newfileUploadRequest(uri string, params map[string]string, paramName, path string) (*http.Request, error) {
  512. file, err := os.Open(path)
  513. if err != nil {
  514. return nil, err
  515. }
  516. defer file.Close()
  517. body := &bytes.Buffer{}
  518. writer := multipart.NewWriter(body)
  519. part, err := writer.CreateFormFile(paramName, filepath.Base(path))
  520. if err != nil {
  521. return nil, err
  522. }
  523. _, err = io.Copy(part, file)
  524. for key, val := range params {
  525. _ = writer.WriteField(key, val)
  526. }
  527. err = writer.Close()
  528. if err != nil {
  529. return nil, err
  530. }
  531. request, err := http.NewRequest("POST", uri, body)
  532. request.Header.Add("Content-Type", writer.FormDataContentType())
  533. return request, err
  534. }