env-file: add helper for printing a properly escaped env var file assignment

This commit is contained in:
Lennart Poettering
2025-05-19 11:02:41 +02:00
parent d9eadbbca0
commit e27333b2cc
2 changed files with 38 additions and 13 deletions

View File

@@ -570,6 +570,41 @@ int merge_env_file(
return parse_env_file_internal(f, fname, merge_env_file_push, env);
}
static void env_file_fputs_escaped(FILE *f, const char *p) {
assert(f);
assert(p);
flockfile(f);
if (string_has_cc(p, NULL) || chars_intersect(p, WHITESPACE SHELL_NEED_QUOTES)) {
fputc_unlocked('"', f);
for (; *p; p++) {
if (strchr(SHELL_NEED_ESCAPE, *p))
fputc_unlocked('\\', f);
fputc_unlocked(*p, f);
}
fputc_unlocked('"', f);
} else
fputs_unlocked(p, f);
funlockfile(f);
}
void env_file_fputs_assignment(FILE *f, const char *k, const char *v) {
assert(f);
assert(k);
if (!v)
return;
fputs(k, f);
env_file_fputs_escaped(f, v);
fputc('\n', f);
}
static void write_env_var(FILE *f, const char *v) {
const char *p;
@@ -587,19 +622,7 @@ static void write_env_var(FILE *f, const char *v) {
p++;
fwrite_unlocked(v, 1, p-v, f);
if (string_has_cc(p, NULL) || chars_intersect(p, WHITESPACE SHELL_NEED_QUOTES)) {
fputc_unlocked('"', f);
for (; *p; p++) {
if (strchr(SHELL_NEED_ESCAPE, *p))
fputc_unlocked('\\', f);
fputc_unlocked(*p, f);
}
fputc_unlocked('"', f);
} else
fputs_unlocked(p, f);
env_file_fputs_escaped(f, p);
fputc_unlocked('\n', f);
}

View File

@@ -22,3 +22,5 @@ int merge_env_file(char ***env, FILE *f, const char *fname);
int write_env_file(int dir_fd, const char *fname, char **headers, char **l);
int write_vconsole_conf(int dir_fd, const char *fname, char **l);
void env_file_fputs_assignment(FILE *f, const char *k, const char *v);