#include #include #include #include "./djstdlib/core.cpp" const string LOG_FILE_LOCATION = "./log.gtl"_s; const string DB_FILE_LOCATION = "./db.gtd"_s; struct GymLogDbHeader { uint32 nextId; }; struct GymLogDbEntry { uint32 id; uint32 nameLength; }; struct GymLogDbParsedEntry { uint32 id; string name; }; struct GymLogDbParsed { GymLogDbHeader header; list entries; }; struct WeightRepsInfo { uint8 reps; real32 weight; }; struct GymLogEntry { uint64 timestamp; uint32 exerciseId; union { WeightRepsInfo weightRepsInfo; }; }; GymLogDbParsed *parseDb(Arena *arena, string database) { GymLogDbParsed *dbParsed = PushStruct(arena, GymLogDbParsed); dbParsed->header = *((GymLogDbHeader *)database.str); size_t head = sizeof(GymLogDbHeader); uint32 entriesLeft = dbParsed->header.nextId - 1; dbParsed->entries = PushList(arena, GymLogDbParsedEntry, entriesLeft); while (entriesLeft > 0 && head < database.length) { GymLogDbEntry *currentEntry = (GymLogDbEntry *)((byte *)database.str + head); GymLogDbParsedEntry parsedEntry = { currentEntry->id, PushString(arena, currentEntry->nameLength) }; head += sizeof(GymLogDbEntry); memcpy(parsedEntry.name.str, database.str + head, currentEntry->nameLength); appendList(&dbParsed->entries, parsedEntry); head += currentEntry->nameLength; } return dbParsed; } list loadEntryLog(Arena *arena, string fileLocation) { list result = {0}; string logfile = os_readEntireFile(arena, LOG_FILE_LOCATION); if (logfile.length % sizeof(GymLogEntry) != 0) { log("Log file corrupted.\n"); } else { size_t entryCount = logfile.length / sizeof(GymLogEntry); result = { (GymLogEntry *)logfile.str, entryCount, entryCount }; } return result; } struct WorkSummary { real32 totalWork; uint32 restTime; }; WorkSummary workSummaryForExercise(list entries) { WorkSummary result = {0}; UnixTimestamp lastTimestamp = 0; for (EachInReversed(entries, i)) { GymLogEntry logEntry = entries.data[i]; result.totalWork += logEntry.weightRepsInfo.weight * logEntry.weightRepsInfo.reps; if (lastTimestamp > 0) { result.restTime += (uint32)(lastTimestamp - logEntry.timestamp); } lastTimestamp = logEntry.timestamp; } return result; } int gymTrackerWorkToday(Arena *arena, uint32 exerciseId, string exerciseName) { int statusCode = 0; string logfile = os_readEntireFile(arena, LOG_FILE_LOCATION); if (logfile.length % sizeof(GymLogEntry) != 0) { log("Log file corrupted.\n"); statusCode = 1; } else { size_t entryCount = logfile.length / sizeof(GymLogEntry); list logEntries = { (GymLogEntry *)logfile.str, entryCount, entryCount }; UnixTimestamp todayUnix = getSystemUnixTime(); Timestamp todayTs = timestampFromUnixTime(&todayUnix); list todaysEntries = {0}; todaysEntries.data = logEntries.data; for (EachInReversed(logEntries, i)) { GymLogEntry logEntry = logEntries.data[i]; Timestamp logTs = timestampFromUnixTime(&logEntry.timestamp); if (logTs.tm_yday == todayTs.tm_yday && todayTs.tm_year == logTs.tm_year) { todaysEntries.head += 1; todaysEntries.data = &logEntries.data[i]; } } if (todaysEntries.data) { todaysEntries.length = todaysEntries.head; WorkSummary summary = workSummaryForExercise(todaysEntries); log("Total work today for %S:\n%.2fkg in ~%.2fmin.\n", exerciseName, summary.totalWork, (real32)summary.restTime / 60.0f); } } return statusCode; } int gymTrackerStatus(Arena *arena, list args) { int statusCode = 0; string file = os_readEntireFile(arena, LOG_FILE_LOCATION); if (file.length % sizeof(GymLogEntry) != 0) { puts("Log file corrupted."); statusCode = 1; } else { GymLogDbParsed *db = parseDb(arena, os_readEntireFile(arena, DB_FILE_LOCATION)); Timestamp startTs = {0}; int numDays = 1; bool showAll = args.length == 1 && strEql(args.data[0], "--all"_s); if (!showAll) { if (args.length == 2 && (strEql(args.data[0], "--days"_s) || strEql(args.data[0], "-d"_s))) { size_t l; numDays = parsePositiveInt(args.data[1], &l); } if (numDays == -1) { puts("Bad argument for --days (-d) parameter."); statusCode = 1; } else { uint64 todayUnix = getSystemUnixTime(); UnixTimestamp startUnix = todayUnix - numDays * 24 * 60 * 60; startTs = timestampFromUnixTime(&startUnix); } } if (statusCode == 0) { int lastDay = -1; int lastYear = -1; size_t entryCount = file.length / sizeof(GymLogEntry); list logEntries = { (GymLogEntry *)file.str, entryCount, entryCount }; list nameByExercise = PushFullListZero(arena, string, db->header.nextId); list workPerExerciseByDay = PushFullListZero(arena, real32, db->header.nextId); list restPerExerciseByDay = PushFullListZero(arena, uint32, db->header.nextId); list lastTsPerExerciseByDay = PushFullListZero(arena, uint32, db->header.nextId); int dayCount = 0; Timestamp timestamp = {0}; GymLogEntry *prevEntry = 0; GymLogEntry *entry = 0; for (EachIn(logEntries, i)) { prevEntry = entry; entry = &logEntries.data[i]; timestamp = timestampFromUnixTime(&entry->timestamp); if (timestamp.tm_year < startTs.tm_year || timestamp.tm_yday < startTs.tm_yday) { continue; } if (timestamp.tm_yday != lastDay || timestamp.tm_year != lastYear) { if (dayCount > 0) { log("\n"); } log("================ %S =================================\n", formatTimeYmd(arena, ×tamp)); lastDay = timestamp.tm_yday; lastYear = timestamp.tm_year; dayCount++; } workPerExerciseByDay.data[entry->exerciseId] += entry->weightRepsInfo.reps * entry->weightRepsInfo.weight; uint32 lastTsForExercise = lastTsPerExerciseByDay.data[entry->exerciseId]; if (lastTsForExercise > 0) { restPerExerciseByDay.data[entry->exerciseId] += (uint32)(entry->timestamp - lastTsForExercise); } lastTsPerExerciseByDay.data[entry->exerciseId] = (uint32)entry->timestamp; const char *format; if (entry->weightRepsInfo.weight == (int32)entry->weightRepsInfo.weight) { format = "%S: %S %.0fkg X %i\n"; } else { format = "%S: %S %.2fkg X %i\n"; } string *exerciseName = &(nameByExercise.data[entry->exerciseId]); if (exerciseName->str == 0) { for (EachIn(db->entries, j)) { GymLogDbParsedEntry dbEntry = db->entries.data[j]; if (dbEntry.id == entry->exerciseId) { *exerciseName = dbEntry.name; } } } string nameToPrint = {0}; if (prevEntry && entry->exerciseId == prevEntry->exerciseId) { nameToPrint = PushStringFill(arena, exerciseName->length, '.'); } else { nameToPrint = exerciseName->str ? *exerciseName : "unknown-exercise"_s; log("\n"); } log(format, formatTimeHms(arena, ×tamp), nameToPrint, entry->weightRepsInfo.weight, entry->weightRepsInfo.reps); Timestamp nextTimestamp = {0}; if (i < logEntries.head - 1) { nextTimestamp = timestampFromUnixTime(&logEntries.data[i + 1].timestamp); } if (i == logEntries.head + 1 || nextTimestamp.tm_yday != lastDay || nextTimestamp.tm_year != lastYear) { log("\n"); log("Work summary:\n"); for (size_t j = 0; j < workPerExerciseByDay.length; j++) { if (workPerExerciseByDay.data[j] != 0.0f) { log("%S: %.2fkg in %.2fmin\n", nameByExercise.data[j], workPerExerciseByDay.data[j], (real32)restPerExerciseByDay.data[j] / 60.0f); } } zeroListFull(&workPerExerciseByDay); zeroListFull(&restPerExerciseByDay); zeroListFull(&lastTsPerExerciseByDay); } } } } return statusCode; } int gymTrackerDeleteEntries(Arena *arena, list args) { int statusCode = 0; if (args.length == 0) { log("Please pass the number of entries to delete starting from the most recent."); statusCode = 1; } else { size_t position = 0; int numToDelete = parsePositiveInt(args.data[0], &position); if (numToDelete != -1) { list logEntries = loadEntryLog(arena, LOG_FILE_LOCATION); if (numToDelete > logEntries.length) { log("%i is more than the current number of log entries (%i). Aborting.", numToDelete, logEntries.length); statusCode = 1; } else { os_writeEntireFile(arena, LOG_FILE_LOCATION, (byte *)logEntries.data, (logEntries.length - numToDelete) * sizeof(GymLogEntry)); } } else { log("Invalid number to delete.\n"); statusCode = 0; } } return statusCode; } // Syntax: do weightKg reps int gymTrackerDo(Arena *arena, list args) { int statusCode = 0; string exerciseName = {0}; if (args.length < 3 || args.data[0].length == 0) { log("Invalid exercise name and/or number of arguments.\n"); statusCode = 1; } else { exerciseName = args.data[0]; } GymLogDbParsedEntry *existingEntry = 0; if (statusCode == 0) { GymLogDbParsed *db = parseDb(arena, os_readEntireFile(arena, DB_FILE_LOCATION)); for (EachIn(db->entries, i)) { GymLogDbParsedEntry entry = db->entries.data[i]; if (strStartsWith(entry.name, exerciseName)) { existingEntry = &entry; if (entry.name.length != exerciseName.length) { exerciseName = entry.name; log("Assuming exercise \"%S\".\n\n", entry.name); } break; } } if (!existingEntry) { log("The exercise \"%S\" hasn't been registered.", exerciseName); statusCode = 1; } } if (statusCode == 0) { uint32 exerciseId = existingEntry->id; size_t parsedCount = 0; real32 kg = parsePositiveReal32(args.data[1], &parsedCount); uint8 reps = parsePositiveInt(args.data[2], &parsedCount); if (parsedCount == 0 || kg == NAN || reps == 0 || kg == 0) { log("Invalid reps or weight input.\n"); statusCode = 1; } else { GymLogEntry entry = { getSystemUnixTime(), exerciseId, reps, kg, }; os_fileAppend(arena, LOG_FILE_LOCATION, (byte *)&entry, sizeof(entry)); statusCode = gymTrackerWorkToday(arena, exerciseId, exerciseName); } } return statusCode; } int gymTrackerListExercises(Arena *arena, list args) { int statusCode = 0; GymLogDbParsed *db = parseDb(arena, os_readEntireFile(arena, DB_FILE_LOCATION)); if (db->entries.length == 0) { log("No entries currently registered in the exercise database."); } else { log("%i entries currently registered in the exercise database:\n\n", db->entries.length); for (EachIn(db->entries, i)) { log("#%i: %S\n", i + 1, db->entries.data[i].name); } } return statusCode; } int gymTrackerAddExercise(Arena *arena, list args) { int statusCode = 0; string newExerciseName = args.data[0]; if (newExerciseName.length == 0) { log("No exercise name provided.\n"); statusCode = 1; } if (statusCode != 1) { string database = os_readEntireFile(arena, DB_FILE_LOCATION); byte *buf = 0; size_t newEntryStartIndex = 0; if (database.length == 0) { // Initialise DB newEntryStartIndex = sizeof(GymLogDbHeader); buf = PushArray(arena, byte, sizeof(GymLogDbHeader) + sizeof(GymLogDbEntry) + newExerciseName.length); GymLogDbHeader *header = (GymLogDbHeader *)buf; header->nextId = 1; } else { // Validate entry not already present bool invalid = false; GymLogDbHeader *header = (GymLogDbHeader *)database.str; size_t head = sizeof(GymLogDbHeader); uint32 entriesLeft = header->nextId - 1; while (entriesLeft > 0 && head < database.length) { GymLogDbEntry *currentEntry = (GymLogDbEntry *)((byte *)database.str + head); head += sizeof(GymLogDbEntry); string entryName = {(char *)((byte *)database.str + head), currentEntry->nameLength }; if (strEql(entryName, newExerciseName)) { invalid = true; log("Exercise \"%S\" already registered (entry #%i)\n", entryName, currentEntry->id); break; } head += currentEntry->nameLength; } if (!invalid) { newEntryStartIndex = database.length; buf = PushArray(arena, byte, database.length + sizeof(GymLogDbEntry) + newExerciseName.length); memcpy(buf, database.str, database.length); } else { statusCode = 1; } } if (statusCode != 1) { // Add entry GymLogDbHeader *header = (GymLogDbHeader *)buf; GymLogDbEntry *entry = (GymLogDbEntry *)(buf + newEntryStartIndex); entry->id = header->nextId; entry->nameLength = (uint32)newExerciseName.length; header->nextId++; byte *newExerciseNameDb = buf + newEntryStartIndex + sizeof(GymLogDbEntry); memcpy(newExerciseNameDb, newExerciseName.str, newExerciseName.length); size_t bufSize = newEntryStartIndex + sizeof(GymLogDbEntry) + newExerciseName.length; os_writeEntireFile(arena, DB_FILE_LOCATION, buf, bufSize); } } return statusCode; } int main(int argc, char **argv) { initialiseCore(); Arena *arena = arenaAlloc(Megabytes(64)); list args = getArgs(arena, argc, argv); int statusCode = 0; if (args.length < 1) { log("At least one arg is required.\n"); statusCode = 1; } if (statusCode == 0) { string cmd = args.data[0]; list argsRest = listSlice(args, 1); if (strEql("status"_s, cmd)) { statusCode = gymTrackerStatus(arena, argsRest); } else if (strEql("do"_s, cmd)) { statusCode = gymTrackerDo(arena, argsRest); } else if (strEql("delete"_s, cmd)) { statusCode = gymTrackerDeleteEntries(arena, argsRest); } else if (strEql("list"_s, cmd)) { statusCode = gymTrackerListExercises(arena, argsRest); } else if (strEql("add"_s, cmd)) { statusCode = gymTrackerAddExercise(arena, argsRest); } else { log("Unknown command \"%S\"\n", args.data[0]); statusCode = 1; } } return statusCode; }