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:
1 parent
d85dd1b624
commit
0d6144b2c4
3 files changed
+60
No files matched your search
@@ -29,6 +29,10 @@ TB_API void tb_environ_unset(const char* key);
|
||||
* As pastas do caminho sao criadas se necessario. */
|
||||
TB_API bool tb_environ_export_csv(const char* path);
|
||||
|
||||
/* Le um CSV no formato do export ("chave,valor"; linhas "# ..." e o
|
||||
* cabecalho sao ignorados) e define cada chave. false se nao abriu. */
|
||||
TB_API bool tb_environ_import_csv(const char* path);
|
||||
|
||||
/* Como tb_environ_export_csv, mas escreve antes uma linha de metadados
|
||||
* "# <meta_key>,<meta_value>" (ex.: o caminho do arquivo de configuracao). */
|
||||
TB_API bool tb_environ_export_csv_meta(const char* path,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user