internal/gamepaddb: simplify controller platform logic

also naming, removing some wrapped errors
This commit is contained in:
Kenny Goodin 2024-03-28 10:27:21 -04:00
parent 466f0c000c
commit 6d5e5ff30f

View File

@ -93,7 +93,7 @@ func run() error {
buildConstraints string
}
supported := map[string]gamePadPlatform{
platforms := map[string]gamePadPlatform{
"Windows": {
filenameSuffix: "windows",
buildConstraints: "//go:build windows && !microsoftgdk",
@ -121,27 +121,22 @@ func run() error {
return err
}
for sdlName, platform := range supported {
controllerDB, ok := controllerDBs[sdlName]
for sdlPlatformName, platform := range platforms {
controllerDB, ok := controllerDBs[sdlPlatformName]
if !ok {
return fmt.Errorf("failed to find controller db for platform %s in gamecontrollerdb_txt", sdlName)
return fmt.Errorf("failed to find controller db for platform %s in gamecontrollerdb_txt", sdlPlatformName)
}
// write each chunk into separate text file for embedding into respective generated files
txtFile, err := os.Create(fmt.Sprintf("gamecontrollerdb_%s.txt", platform.filenameSuffix))
err = os.WriteFile(fmt.Sprintf("gamecontrollerdb_%s.txt", platform.filenameSuffix), []byte(controllerDB), 0666)
if err != nil {
return fmt.Errorf("failed to open file: %v", err)
}
defer txtFile.Close()
written, err := txtFile.Write(controllerDB)
if err != nil {
return fmt.Errorf("failed to write controller db for %s, expected to write %d bytes, wrote %d: %v", sdlName, len(controllerDB), written, err)
return err
}
path := fmt.Sprintf("db_%s.go", platform.filenameSuffix)
tmpl, err := template.New(path).Parse(dbTemplate)
if err != nil {
return fmt.Errorf("failed to parse template: %v", err)
return err
}
f, err := os.Create(path)
@ -169,46 +164,23 @@ func run() error {
return nil
}
func splitControllersByPlatform(controllerDB []byte) (map[string][]byte, error) {
func splitControllersByPlatform(controllerDB []byte) (map[string]string, error) {
s := bufio.NewScanner(bytes.NewReader(controllerDB))
dbs := map[string][]byte{}
dbs := map[string]string{}
var currentPlatform string
buf := bytes.Buffer{}
for s.Scan() {
chunk := s.Bytes()
if len(chunk) == 0 {
line := s.Text()
if len(line) == 0 {
continue
}
if chunk[0] == '#' {
if currentPlatform != "" && buf.Len() > 0 {
dbs[currentPlatform] = bytes.Clone(buf.Bytes())
buf.Reset()
}
platform := strings.Replace(string(chunk), "# ", "", 1)
switch platform {
case "Windows":
currentPlatform = "Windows"
case "Mac OS X":
currentPlatform = "Mac OS X"
case "iOS":
currentPlatform = "iOS"
case "Android":
currentPlatform = "Android"
case "Linux":
currentPlatform = "Linux"
default:
continue
}
} else {
buf.Write(chunk)
buf.WriteByte('\n')
if line[0] == '#' {
currentPlatform = strings.Replace(line, "# ", "", 1)
continue
}
}
if currentPlatform != "" && buf.Len() > 0 {
dbs[currentPlatform] = bytes.Clone(buf.Bytes())
dbs[currentPlatform] += line + "\n"
}
if err := s.Err(); err != nil {
return nil, err