2
0

import.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package ast
  2. import (
  3. "go/ast"
  4. "go/token"
  5. "io"
  6. "strings"
  7. )
  8. type Import struct {
  9. Base
  10. ImportPath string // 导包路径
  11. }
  12. func NewImport(importPath string) *Import {
  13. return &Import{ImportPath: importPath}
  14. }
  15. func (a *Import) Parse(filename string, writer io.Writer) (file *ast.File, err error) {
  16. return a.Base.Parse(filename, writer)
  17. }
  18. func (a *Import) Rollback(file *ast.File) error {
  19. if a.ImportPath == "" {
  20. return nil
  21. }
  22. for i := 0; i < len(file.Decls); i++ {
  23. v1, o1 := file.Decls[i].(*ast.GenDecl)
  24. if o1 {
  25. if v1.Tok != token.IMPORT {
  26. break
  27. }
  28. for j := 0; j < len(v1.Specs); j++ {
  29. v2, o2 := v1.Specs[j].(*ast.ImportSpec)
  30. if o2 && strings.HasSuffix(a.ImportPath, v2.Path.Value) {
  31. v1.Specs = append(v1.Specs[:j], v1.Specs[j+1:]...)
  32. if len(v1.Specs) == 0 {
  33. file.Decls = append(file.Decls[:i], file.Decls[i+1:]...)
  34. } // 如果没有import声明,就删除, 如果不删除则会出现import()
  35. break
  36. }
  37. }
  38. }
  39. }
  40. return nil
  41. }
  42. func (a *Import) Injection(file *ast.File) error {
  43. if a.ImportPath == "" {
  44. return nil
  45. }
  46. var has bool
  47. for i := 0; i < len(file.Decls); i++ {
  48. v1, o1 := file.Decls[i].(*ast.GenDecl)
  49. if o1 {
  50. if v1.Tok != token.IMPORT {
  51. break
  52. }
  53. for j := 0; j < len(v1.Specs); j++ {
  54. v2, o2 := v1.Specs[j].(*ast.ImportSpec)
  55. if o2 && strings.HasSuffix(a.ImportPath, v2.Path.Value) {
  56. has = true
  57. break
  58. }
  59. }
  60. if !has {
  61. spec := &ast.ImportSpec{
  62. Path: &ast.BasicLit{Kind: token.STRING, Value: a.ImportPath},
  63. }
  64. v1.Specs = append(v1.Specs, spec)
  65. return nil
  66. }
  67. }
  68. }
  69. if !has {
  70. decls := file.Decls
  71. file.Decls = make([]ast.Decl, 0, len(file.Decls)+1)
  72. decl := &ast.GenDecl{
  73. Tok: token.IMPORT,
  74. Specs: []ast.Spec{
  75. &ast.ImportSpec{
  76. Path: &ast.BasicLit{Kind: token.STRING, Value: a.ImportPath},
  77. },
  78. },
  79. }
  80. file.Decls = append(file.Decls, decl)
  81. file.Decls = append(file.Decls, decls...)
  82. } // 如果没有import声明,就创建一个, 主要要放在第一个
  83. return nil
  84. }
  85. func (a *Import) Format(filename string, writer io.Writer, file *ast.File) error {
  86. return a.Base.Format(filename, writer, file)
  87. }