Implement writing "already seen" to source

This commit is contained in:
2025-05-21 13:10:33 +02:00
parent 4301294b66
commit 70c417e7f4

48
main.go
View File

@@ -102,21 +102,13 @@ func saveAchievementsToSourceFiles(luaStates *sync.Map, achievements *sync.Map)
state.SetField(achievementTable, "alreadySeen", seenTable)
}
wg.Add(1)
go func() {
defer wg.Done()
updateSeenTable(state, seenTable, achievements)
// State itself should now be updated
}()
fixSource(path, state)
fixSource(path, achievements)
return true
})
wg.Wait()
}
func fixSource(path string, state *lua.LState) {
func fixSource(path string, achievements *sync.Map) {
log := logger.Default.WithPrefix(path)
log.Info("Reading source file")
fileContent, err := os.ReadFile(path)
@@ -130,6 +122,9 @@ func fixSource(path string, state *lua.LState) {
strContent = removeAchievements(strContent)
log.Info("Removed achievements, now %d bytes", len(strContent))
strContent = addAlreadySeen(strContent, achievements)
log.Info("Added alreadySeen, now %d bytes", len(strContent))
log.Info("Writing file")
err = os.WriteFile(path, []byte(strContent), 0644)
if err != nil {
@@ -164,22 +159,23 @@ func removeAchievements(sourceContent string) string {
return strings.Join(lines[:writeIndex], "\n")
}
func updateSeenTable(state *lua.LState, seenTable lua.LValue, achievements *sync.Map) {
achievements.Range(func(k, v any) bool {
playerName := k.(string)
state.SetField(seenTable, playerName, lua.LBool(true))
return true
})
// Debug confirmation
// seenTableLua, ok := seenTable.(*lua.LTable)
// if !ok {
// log.Error("seenTable is not a table")
// return
// }
// state.ForEach(seenTableLua, func(k, v lua.LValue) {
// log.Info("Seen: %s", k)
// })
func addAlreadySeen(strContent string, achievements *sync.Map) string {
lines := strings.Split(strContent, "\n")
modifiedLines := make([]string, 0, len(lines))
for _, line := range lines {
if strings.HasPrefix(line, "\t[\"alreadySeen\"] = {") {
modifiedLines = append(modifiedLines, line)
achievements.Range(func(k, v any) bool {
logger.Trace("Adding alreadySeen for %s", k)
playerName := k.(string)
modifiedLines = append(modifiedLines, fmt.Sprintf("\t\t[\"%s\"] = true,", playerName))
return true
})
continue
}
modifiedLines = append(modifiedLines, line)
}
return strings.Join(modifiedLines, "\n")
}
func saveAchievementsToDB(db *DB, achievements *sync.Map) {