interfaces_base.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package ast
  2. import (
  3. "github.com/flipped-aurora/gin-vue-admin/server/global"
  4. "github.com/pkg/errors"
  5. "go/ast"
  6. "go/format"
  7. "go/parser"
  8. "go/token"
  9. "io"
  10. "os"
  11. "path"
  12. "path/filepath"
  13. "strings"
  14. )
  15. type Base struct{}
  16. func (a *Base) Parse(filename string, writer io.Writer) (file *ast.File, err error) {
  17. fileSet := token.NewFileSet()
  18. if writer != nil {
  19. file, err = parser.ParseFile(fileSet, filename, nil, parser.ParseComments)
  20. } else {
  21. file, err = parser.ParseFile(fileSet, filename, writer, parser.ParseComments)
  22. }
  23. if err != nil {
  24. return nil, errors.Wrapf(err, "[filepath:%s]打开/解析文件失败!", filename)
  25. }
  26. return file, nil
  27. }
  28. func (a *Base) Rollback(file *ast.File) error {
  29. return nil
  30. }
  31. func (a *Base) Injection(file *ast.File) error {
  32. return nil
  33. }
  34. func (a *Base) Format(filename string, writer io.Writer, file *ast.File) error {
  35. fileSet := token.NewFileSet()
  36. if writer == nil {
  37. open, err := os.OpenFile(filename, os.O_WRONLY|os.O_TRUNC, 0666)
  38. defer open.Close()
  39. if err != nil {
  40. return errors.Wrapf(err, "[filepath:%s]打开文件失败!", filename)
  41. }
  42. writer = open
  43. }
  44. err := format.Node(writer, fileSet, file)
  45. if err != nil {
  46. return errors.Wrapf(err, "[filepath:%s]注入失败!", filename)
  47. }
  48. return nil
  49. }
  50. // RelativePath 绝对路径转相对路径
  51. func (a *Base) RelativePath(filePath string) string {
  52. server := filepath.Join(global.GVA_CONFIG.AutoCode.Root, global.GVA_CONFIG.AutoCode.Server)
  53. hasServer := strings.Index(filePath, server)
  54. if hasServer != -1 {
  55. filePath = strings.TrimPrefix(filePath, server)
  56. keys := strings.Split(filePath, string(filepath.Separator))
  57. filePath = path.Join(keys...)
  58. }
  59. return filePath
  60. }
  61. // AbsolutePath 相对路径转绝对路径
  62. func (a *Base) AbsolutePath(filePath string) string {
  63. server := filepath.Join(global.GVA_CONFIG.AutoCode.Root, global.GVA_CONFIG.AutoCode.Server)
  64. keys := strings.Split(filePath, "/")
  65. filePath = filepath.Join(keys...)
  66. filePath = filepath.Join(server, filePath)
  67. return filePath
  68. }