engineclient.go 15 KB

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