initial commit
This commit is contained in:
70
internal/gamefile.go
Normal file
70
internal/gamefile.go
Normal file
@@ -0,0 +1,70 @@
|
||||
package oplcli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func scanGameFileForID(filename string) (string, error) {
|
||||
file, err := os.Open(filename)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to open file: %w", err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
const bufferSize = 1024 * 1024 // 1MB
|
||||
buffer := make([]byte, bufferSize)
|
||||
|
||||
n, err := file.Read(buffer)
|
||||
if err != nil && n == 0 {
|
||||
return "", fmt.Errorf("failed to read file: %w", err)
|
||||
}
|
||||
|
||||
pattern := regexp.MustCompile(`(SLUS|SLES|SLPS|SCUS|SCES|SCPS)[_-]?\d{3}[\._]\d{2}`)
|
||||
|
||||
match := pattern.Find(buffer[:n])
|
||||
if match != nil {
|
||||
gameID := string(match)
|
||||
return normalizeGameID(gameID), nil
|
||||
}
|
||||
|
||||
return "", fmt.Errorf("no PS2 game ID found in file")
|
||||
}
|
||||
|
||||
func normalizeGameID(id string) string {
|
||||
s := strings.ReplaceAll(id, "_", "-")
|
||||
s = strings.ReplaceAll(s, ".", "")
|
||||
s = strings.ToUpper(s)
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
func renameGameFile(filePath, gameName string) (string, error) {
|
||||
ext := filepath.Ext(filePath)
|
||||
dir := filepath.Dir(filePath)
|
||||
|
||||
newPath := filepath.Join(dir, gameName+ext)
|
||||
|
||||
if filePath == newPath {
|
||||
return filePath, nil
|
||||
}
|
||||
|
||||
// Do not overwrite existing files
|
||||
if _, err := os.Stat(newPath); err == nil {
|
||||
return "", fmt.Errorf("file already exists: %s", newPath)
|
||||
} else if !os.IsNotExist(err) {
|
||||
return "", fmt.Errorf("failed to check destination: %w", err)
|
||||
}
|
||||
|
||||
// rename file
|
||||
err := os.Rename(filePath, newPath)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to rename file: %w", err)
|
||||
}
|
||||
|
||||
return newPath, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user