environ: importar o CSV das configurações (tb_environ_import_csv)

As configurações só eram exportadas; agora o mesmo CSV ("chave,valor",
com aspas e "" escapado; linhas "# ..." e o cabeçalho ignorados) é lido de
volta, então elas sobrevivem a um reinício. Teste de ida e volta.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
mguinhosandClaude Opus 5.5 committed 2026-10-22 17:52:30 -03:00
1 parent d85dd1b624
commit 0d6144b2c4
3 files changed
+60

No files matched your search

@@ -143,6 +143,45 @@ bool tb_environ_export_csv_meta(const char* path, const char* meta_key,
return true;
}
/* Le um campo CSV a partir de *p (aspas com "" escapado); avanca *p ate
depois da virgula ou do fim da linha. */
static void csv_read_field(const char** p, char* out, size_t cap) {
const char* s = *p;
size_t n = 0;
if (*s == '"') {
s++;
while (*s) {
if (*s == '"' && s[1] == '"') { if (n + 1 < cap) out[n++] = '"'; s += 2; continue; }
if (*s == '"') { s++; break; }
if (n + 1 < cap) out[n++] = *s;
s++;
}
} else {
while (*s && *s != ',' && *s != '\n' && *s != '\r') { if (n + 1 < cap) out[n++] = *s; s++; }
}
out[n] = 0;
if (*s == ',') s++;
*p = s;
}
bool tb_environ_import_csv(const char* path) {
s_err[0] = 0;
FILE* f = path ? fopen(path, "rb") : NULL;
if (!f) { snprintf(s_err, sizeof(s_err), "nao foi possivel abrir %s", path ? path : "(nulo)"); return false; }
char line[4096], key[512], val[3584];
bool header_seen = false;
while (fgets(line, sizeof(line), f)) {
if (line[0] == '#' || line[0] == '\n' || line[0] == '\r' || line[0] == 0) continue;
if (!header_seen && strncmp(line, "chave,valor", 11) == 0) { header_seen = true; continue; }
const char* p = line;
csv_read_field(&p, key, sizeof(key));
csv_read_field(&p, val, sizeof(val));
if (key[0]) tb_environ_set(key, val);
}
fclose(f);
return true;
}
bool tb_environ_export_csv(const char* path) {
return tb_environ_export_csv_meta(path, NULL, NULL);
}