generate.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. package main
  2. import (
  3. "fmt"
  4. "go/ast"
  5. "go/parser"
  6. "go/token"
  7. "os"
  8. "path/filepath"
  9. "regexp"
  10. "sort"
  11. "strings"
  12. "text/template"
  13. )
  14. // Structure to hold extracted notifier information
  15. type NotifierInfo struct {
  16. Name string
  17. Fields []FieldInfo
  18. FileName string
  19. ConfigKey string
  20. }
  21. // Structure to hold field information for notifier
  22. type FieldInfo struct {
  23. Name string
  24. Key string
  25. Title string
  26. }
  27. // Template for the TypeScript config file
  28. const tsConfigTemplate = `// This file is auto-generated by notification generator. DO NOT EDIT.
  29. import type { ExternalNotifyConfig } from './types'
  30. const {{.Name}}Config: ExternalNotifyConfig = {
  31. name: () => $gettext('{{.Name}}'),
  32. config: [
  33. {{- range .Fields}}
  34. {
  35. key: '{{.Key}}',
  36. label: () => $gettext('{{.Title}}'),
  37. },
  38. {{- end}}
  39. ],
  40. }
  41. export default {{.Name}}Config
  42. `
  43. // Regular expression to extract @external_notifier annotation
  44. var externalNotifierRegex = regexp.MustCompile(`@external_notifier\((\w+)\)`)
  45. func main() {
  46. if err := GenerateExternalNotifiers(); err != nil {
  47. fmt.Printf("error generating external notifier configs: %v\n", err)
  48. }
  49. }
  50. // GenerateExternalNotifiers generates TypeScript config files for external notifiers
  51. func GenerateExternalNotifiers() error {
  52. fmt.Println("Generating external notifier configs...")
  53. // Notification package path
  54. notificationPkgPath := "internal/notification"
  55. outputDir := "app/src/views/preference/components/ExternalNotify"
  56. // Create output directory if it doesn't exist
  57. if err := os.MkdirAll(outputDir, 0755); err != nil {
  58. return fmt.Errorf("error creating output directory: %w", err)
  59. }
  60. // Get all Go files in the notification package
  61. files, err := filepath.Glob(filepath.Join(notificationPkgPath, "*.go"))
  62. if err != nil {
  63. return fmt.Errorf("error scanning notification package: %w", err)
  64. }
  65. // Collect all notifier info
  66. notifiers := []NotifierInfo{}
  67. for _, file := range files {
  68. notifier, found := extractNotifierInfo(file)
  69. if found {
  70. notifiers = append(notifiers, notifier)
  71. fmt.Printf("Found notifier: %s in %s\n", notifier.Name, file)
  72. }
  73. }
  74. // Generate TypeScript config files
  75. for _, notifier := range notifiers {
  76. if err := generateTSConfig(notifier, outputDir); err != nil {
  77. return fmt.Errorf("error generating config for %s: %w", notifier.Name, err)
  78. }
  79. }
  80. // Update index.ts
  81. if err := updateIndexFile(notifiers, outputDir); err != nil {
  82. return fmt.Errorf("error updating index.ts: %w", err)
  83. }
  84. fmt.Println("Generation completed successfully!")
  85. return nil
  86. }
  87. // Extract notifier information from a Go file
  88. func extractNotifierInfo(filePath string) (NotifierInfo, bool) {
  89. // Create the FileSet
  90. fset := token.NewFileSet()
  91. // Parse the file
  92. file, err := parser.ParseFile(fset, filePath, nil, parser.ParseComments)
  93. if err != nil {
  94. fmt.Printf("Error parsing file %s: %v\n", filePath, err)
  95. return NotifierInfo{}, false
  96. }
  97. var notifierInfo NotifierInfo
  98. found := false
  99. // Look for the type declaration with the @external_notifier annotation
  100. for _, decl := range file.Decls {
  101. genDecl, ok := decl.(*ast.GenDecl)
  102. if !ok || genDecl.Tok != token.TYPE {
  103. continue
  104. }
  105. for _, spec := range genDecl.Specs {
  106. typeSpec, ok := spec.(*ast.TypeSpec)
  107. if !ok {
  108. continue
  109. }
  110. structType, ok := typeSpec.Type.(*ast.StructType)
  111. if !ok {
  112. continue
  113. }
  114. // Check if we have a comment with @external_notifier
  115. if genDecl.Doc != nil {
  116. for _, comment := range genDecl.Doc.List {
  117. matches := externalNotifierRegex.FindStringSubmatch(comment.Text)
  118. if len(matches) > 1 {
  119. notifierInfo.Name = matches[1]
  120. notifierInfo.ConfigKey = strings.ToLower(typeSpec.Name.Name)
  121. notifierInfo.FileName = strings.ToLower(matches[1])
  122. found = true
  123. // Extract fields
  124. for _, field := range structType.Fields.List {
  125. if len(field.Names) > 0 {
  126. fieldName := field.Names[0].Name
  127. // Get json tag and title from field tags
  128. var jsonKey, title string
  129. if field.Tag != nil {
  130. tagValue := strings.Trim(field.Tag.Value, "`")
  131. // Extract json key
  132. jsonRegex := regexp.MustCompile(`json:"([^"]+)"`)
  133. jsonMatches := jsonRegex.FindStringSubmatch(tagValue)
  134. if len(jsonMatches) > 1 {
  135. jsonKey = jsonMatches[1]
  136. }
  137. // Extract title
  138. titleRegex := regexp.MustCompile(`title:"([^"]+)"`)
  139. titleMatches := titleRegex.FindStringSubmatch(tagValue)
  140. if len(titleMatches) > 1 {
  141. title = titleMatches[1]
  142. }
  143. }
  144. if jsonKey == "" {
  145. jsonKey = strings.ToLower(fieldName)
  146. }
  147. if title == "" {
  148. title = fieldName
  149. }
  150. notifierInfo.Fields = append(notifierInfo.Fields, FieldInfo{
  151. Name: fieldName,
  152. Key: jsonKey,
  153. Title: title,
  154. })
  155. }
  156. }
  157. break
  158. }
  159. }
  160. }
  161. if found {
  162. break
  163. }
  164. }
  165. if found {
  166. break
  167. }
  168. }
  169. return notifierInfo, found
  170. }
  171. // Generate TypeScript config file for a notifier
  172. func generateTSConfig(notifier NotifierInfo, outputDir string) error {
  173. // Create template
  174. tmpl, err := template.New("tsConfig").Parse(tsConfigTemplate)
  175. if err != nil {
  176. return fmt.Errorf("error creating template: %w", err)
  177. }
  178. // Create output file
  179. outputFile := filepath.Join(outputDir, notifier.FileName+".ts")
  180. file, err := os.Create(outputFile)
  181. if err != nil {
  182. return fmt.Errorf("error creating output file %s: %w", outputFile, err)
  183. }
  184. defer file.Close()
  185. // Execute template
  186. err = tmpl.Execute(file, notifier)
  187. if err != nil {
  188. return fmt.Errorf("error executing template: %w", err)
  189. }
  190. fmt.Printf("Generated TypeScript config for %s at %s\n", notifier.Name, outputFile)
  191. return nil
  192. }
  193. // Update index.ts file
  194. func updateIndexFile(notifiers []NotifierInfo, outputDir string) error {
  195. // Create content for index.ts
  196. var imports strings.Builder
  197. var configMap strings.Builder
  198. // Sort notifiers alphabetically by name for stable output
  199. sort.Slice(notifiers, func(i, j int) bool {
  200. return notifiers[i].Name < notifiers[j].Name
  201. })
  202. for _, notifier := range notifiers {
  203. fileName := notifier.FileName
  204. configName := notifier.Name + "Config"
  205. imports.WriteString(fmt.Sprintf("import %s from './%s'\n", configName, fileName))
  206. }
  207. // Generate the map
  208. configMap.WriteString("const configMap = {\n")
  209. for _, notifier := range notifiers {
  210. configMap.WriteString(fmt.Sprintf(" %s: %sConfig", strings.ToLower(notifier.Name), notifier.Name))
  211. configMap.WriteString(",\n")
  212. }
  213. configMap.WriteString("}\n")
  214. content := fmt.Sprintf("// This file is auto-generated by notification generator. DO NOT EDIT.\n%s\n%s\nexport default configMap\n", imports.String(), configMap.String())
  215. // Write to index.ts
  216. indexPath := filepath.Join(outputDir, "index.ts")
  217. err := os.WriteFile(indexPath, []byte(content), 0644)
  218. if err != nil {
  219. return fmt.Errorf("error writing index.ts: %w", err)
  220. }
  221. fmt.Printf("Updated index.ts at %s\n", indexPath)
  222. return nil
  223. }