Skip to content

Commit

Permalink
[generator] Improve code quality
Browse files Browse the repository at this point in the history
  • Loading branch information
IceflowRE committed Nov 4, 2023
1 parent c8cb04c commit 910bc1d
Show file tree
Hide file tree
Showing 5 changed files with 44 additions and 27 deletions.
13 changes: 7 additions & 6 deletions tools/generator/internal/endpoint.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package internal

import (
"cmp"
"path"
"slices"
"sort"
"strings"
Expand Down Expand Up @@ -33,13 +34,13 @@ func newEndpointFromDoc(doc *wgMethodDoc, game string, id string) (*endpoint, er
ep := endpoint{
Id: id,
Game: snakeToCamelLower(game),
Url: doc.Url,
Url: doc.URL,

Name: snakeToCamel(id),
MetaType: nil,
Documentation: strings.TrimPrefix(cleanDocumentation(doc.Description), "Method "),
Deprecated: doc.Deprecated,
HttpMethods: doc.AllowedHttpMethods,
HttpMethods: doc.AllowedHTTPMethods,
OtherImports: map[string]struct{}{"context": {}},
OptionsType: nil,
}
Expand Down Expand Up @@ -121,7 +122,7 @@ func (ep *endpoint) MethodImports() []string {
imports = append(imports, imp)
}
if ep.OptionsType != nil || ep.DataType != nil && ep.DataType.IsStruct() {
imports = append(imports, wgModuleName+"/wargaming/"+ep.Game)
imports = append(imports, path.Join(wgModuleName, "wargaming", ep.Game))
}
sort.Strings(imports)
return imports
Expand All @@ -136,13 +137,13 @@ func wgToGoType(name string) *goType {
"list of integers": {TypeStr: "[]int", Imports: make(map[string]struct{})},
"numeric": {TypeStr: "int", Imports: make(map[string]struct{})},
"string": {TypeStr: "string", Imports: make(map[string]struct{})},
"timestamp": {TypeStr: "wgnTime.UnixTime", Imports: map[string]struct{}{wgModuleName + "/wargaming/wgnTime": {}}},
"timestamp": {TypeStr: "wgnTime.UnixTime", Imports: map[string]struct{}{path.Join(wgModuleName, "wargaming", "wgnTime"): {}}},

"list of strings": {TypeStr: "[]string", Imports: make(map[string]struct{})},
"list of timestamps": {TypeStr: "[]wgnTime.UnixTime", Imports: map[string]struct{}{wgModuleName + "/wargaming/wgnTime": {}}},
"list of timestamps": {TypeStr: "[]wgnTime.UnixTime", Imports: map[string]struct{}{path.Join(wgModuleName, "wargaming", "wgnTime"): {}}},
"list of dicts": {TypeStr: "map[string]string", Imports: make(map[string]struct{})},
"object": {TypeStr: "struct", Imports: make(map[string]struct{})},
"timestamp/date": {TypeStr: "wgnTime.UnixTime", Imports: map[string]struct{}{wgModuleName + "/wargaming/wgnTime": {}}},
"timestamp/date": {TypeStr: "wgnTime.UnixTime", Imports: map[string]struct{}{path.Join(wgModuleName, "wargaming", "wgnTime"): {}}},

// used in Parameters
"numeric, list": {TypeStr: "[]int", Imports: make(map[string]struct{})},
Expand Down
11 changes: 5 additions & 6 deletions tools/generator/internal/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (
)

type Generator struct {
moduleName string
outputPath string
verbose bool
}
Expand Down Expand Up @@ -54,18 +53,18 @@ func (gen *Generator) Generate() (err error) {
}
for _, section := range game.Sections {
for _, method := range section.Methods {
processedMethods += 1
processedMethods++
gen.printf("(%03d/%03d) Generating %s\n", processedMethods, maxMethods, method.Key)
doc, err := getWgMethodDoc(method.Key, "all")
if err != nil {
return err
}
// collect sections
sec, _ := sectionsMap[snakeToCamel(game.Slug)]
if sec.ApiUrlFormat != "" && sec.ApiUrlFormat != doc.ApiUrl {
return fmt.Errorf("%s has multiple API URLs!? (%s | %s)", game.Slug, sec.ApiUrlFormat, doc.ApiUrl)
if sec.ApiUrlFormat != "" && sec.ApiUrlFormat != doc.ApiURL {
return fmt.Errorf("%s has multiple API URLs!? (%s | %s)", game.Slug, sec.ApiUrlFormat, doc.ApiURL)
}
sec.ApiUrlFormat = doc.ApiUrl
sec.ApiUrlFormat = doc.ApiURL
// collect realm indices
for _, realmIdx := range doc.AvailableDisplayIndices {
if _, ok := realmIdcs[realmIdx]; !ok {
Expand Down Expand Up @@ -148,7 +147,7 @@ func collectRealms(realmIdcs map[string]string, realmDocs []*realmDoc) ([]*realm
return nil, err
}
realm := &realmData{
Tld: rxApiUrl.FindAllStringSubmatch(doc.ApiUrl, 1)[0][2],
Tld: rxApiUrl.FindAllStringSubmatch(doc.ApiURL, 1)[0][2],
Index: strings.ToLower(idx),
}
for _, doc := range realmDocs {
Expand Down
26 changes: 21 additions & 5 deletions tools/generator/internal/templates.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
_ "embed"
"go/format"
"os"
"path/filepath"
"regexp"
"slices"
"sort"
Expand Down Expand Up @@ -80,8 +81,11 @@ func genMethod(ep *endpoint, outputPath string) error {

buf := &bytes.Buffer{}
err = templ.Execute(buf, ep)
if err != nil {
return err
}

return formatWriteFile(buf.Bytes(), outputPath+ep.Id+".go")
return formatWriteFile(buf.Bytes(), filepath.Join(outputPath, ep.Id+".go"))
}

//go:embed templates/structBase.tmpl
Expand Down Expand Up @@ -149,9 +153,12 @@ func genStructs(ep *endpoint, outputPath string) error {

buf := &bytes.Buffer{}
err = templ.ExecuteTemplate(buf, "structBase", ep)
if err != nil {
return err
}

filename := strings.TrimPrefix(ep.Id, ep.Game+"_")
return formatWriteFile(buf.Bytes(), outputPath+ep.Game+"/"+filename+".go")
return formatWriteFile(buf.Bytes(), filepath.Join(outputPath, ep.Game, filename+".go"))
}

//go:embed templates/services.tmpl
Expand All @@ -172,8 +179,11 @@ func genServices(services []serviceData, outputPath string) error {

buf := &bytes.Buffer{}
err = templ.Execute(buf, services)
if err != nil {
return err
}

return formatWriteFile(buf.Bytes(), outputPath+"services.go")
return formatWriteFile(buf.Bytes(), filepath.Join(outputPath, "services.go"))
}

//go:embed templates/sections.tmpl
Expand All @@ -200,8 +210,11 @@ func genSections(sections []*sectionData, outputPath string) error {

buf := &bytes.Buffer{}
err = templ.Execute(buf, sections)
if err != nil {
return err
}

return formatWriteFile(buf.Bytes(), outputPath+"sections.go")
return formatWriteFile(buf.Bytes(), filepath.Join(outputPath, "sections.go"))
}

//go:embed templates/realms.tmpl
Expand All @@ -224,6 +237,9 @@ func genRealms(realms []*realmData, outputPath string) error {

buf := &bytes.Buffer{}
err = templ.Execute(buf, realms)
if err != nil {
return err
}

return formatWriteFile(buf.Bytes(), outputPath+"realms.go")
return formatWriteFile(buf.Bytes(), filepath.Join(outputPath, "realms.go"))
}
4 changes: 2 additions & 2 deletions tools/generator/internal/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,10 @@ func camelLowerToCamel(name string) string {
return string(unicode.ToUpper(rune(name[0]))) + name[1:]
}

var rxHtml = regexp.MustCompile(`<.*?>`)
var rxHTML = regexp.MustCompile(`<.*?>`)

func cleanDocumentation(text string) string {
doc := html.UnescapeString(strings.TrimPrefix(rxHtml.ReplaceAllString(text, ""), "\n"))
doc := html.UnescapeString(strings.TrimPrefix(rxHTML.ReplaceAllString(text, ""), "\n"))
doc = strings.ReplaceAll(doc, "—", "-")
doc = strings.ReplaceAll(doc, "“", "\"")
doc = strings.ReplaceAll(doc, "”", "\"")
Expand Down
17 changes: 9 additions & 8 deletions tools/generator/internal/wg_docs.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,14 @@ type wgFieldDoc struct {
type wgMethodDoc struct {
AvailableDisplayIndices []string `json:"available_display_indices"`
AllowedProtocols []string `json:"allowed_protocols"`
AllowedHttpMethods []string `json:"allowed_http_methods"`
AllowedHTTPMethods []string `json:"allowed_http_methods"`
Name string
Description string
Deprecated bool
Realm string
DisplayIndex string `json:"display_index"`
ApiUrl string `json:"api_url"`
Url string
ApiURL string `json:"api_url"`
URL string
Section string
Errors []struct {
Message string
Expand All @@ -65,16 +65,17 @@ func getWgDoc(path string, realm string) ([]byte, error) {
req.Header.Set("X-Requested-With", "XMLHttpRequest")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, nil
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("status was not OK")
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
//os.WriteFile("method.json", body, 0644)
// os.WriteFile("method.json", body, 0644)
return body, nil
}

Expand All @@ -89,8 +90,8 @@ func getWgMethodsDoc() ([]*wgMethodsDoc, []*realmDoc, error) {
return nil, nil, err
}
tmp := struct {
Data []*wgMethodsDoc
Realms []*realmDoc
Data []*wgMethodsDoc `json:"Data"`
Realms []*realmDoc `json:"Realms"`
}{}
err = json.Unmarshal(body, &tmp)
if err != nil {
Expand All @@ -105,7 +106,7 @@ func getWgMethodDoc(id string, realm string) (*wgMethodDoc, error) {
return nil, err
}
tmp := struct {
Data *wgMethodDoc
Data *wgMethodDoc `json:"Data"`
}{}
err = json.Unmarshal(body, &tmp)
if err != nil {
Expand Down

0 comments on commit 910bc1d

Please sign in to comment.