parseStructsFromPackage finds and parses structs from a package
(pkg *packages.Package, targetTypes []string)
| 120 | |
| 121 | // parseStructsFromPackage finds and parses structs from a package |
| 122 | func parseStructsFromPackage(pkg *packages.Package, targetTypes []string) ([]*StructInfo, error) { |
| 123 | var structs []*StructInfo |
| 124 | |
| 125 | // Check if package has types |
| 126 | if pkg.Types == nil { |
| 127 | return nil, fmt.Errorf("package %s has no type information", pkg.PkgPath) |
| 128 | } |
| 129 | |
| 130 | // Iterate through all types in the package |
| 131 | scope := pkg.Types.Scope() |
| 132 | allNames := scope.Names() |
| 133 | |
| 134 | for _, name := range allNames { |
| 135 | obj := scope.Lookup(name) |
| 136 | if obj == nil { |
| 137 | continue |
| 138 | } |
| 139 | |
| 140 | // Check if it's a named type |
| 141 | named, ok := obj.Type().(*types.Named) |
| 142 | if !ok { |
| 143 | continue |
| 144 | } |
| 145 | |
| 146 | // Check if underlying type is struct |
| 147 | structType, ok := named.Underlying().(*types.Struct) |
| 148 | if !ok { |
| 149 | continue |
| 150 | } |
| 151 | |
| 152 | // Check if we should generate code for this type |
| 153 | shouldGenerate := false |
| 154 | if len(targetTypes) > 0 { |
| 155 | for _, t := range targetTypes { |
| 156 | if strings.TrimSpace(t) == name { |
| 157 | shouldGenerate = true |
| 158 | break |
| 159 | } |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | if !shouldGenerate { |
| 164 | continue |
| 165 | } |
| 166 | |
| 167 | // Extract struct information |
| 168 | structInfo, err := extractStructInfo(name, structType) |
| 169 | if err != nil { |
| 170 | return nil, fmt.Errorf("extracting struct info for %s: %w", name, err) |
| 171 | } |
| 172 | |
| 173 | structs = append(structs, structInfo) |
| 174 | } |
| 175 | |
| 176 | return structs, nil |
| 177 | } |
no test coverage detected