Introduce EnvSubst()
This commit is contained in:
parent
36ff0e5a19
commit
52d8dfe805
52
src/string.c
52
src/string.c
|
@ -1,5 +1,5 @@
|
|||
/*
|
||||
* Copyright (C) 2008-2015 Kim Woelders
|
||||
* Copyright (C) 2008-2022 Kim Woelders
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to
|
||||
|
@ -70,3 +70,53 @@ Estrcasestr(const char *haystack, const char *needle)
|
|||
return NULL;
|
||||
}
|
||||
#endif
|
||||
|
||||
/*
|
||||
* Substitute $ENV_VAR and ${ENV_VAR} with the environment variable
|
||||
* from str into bptr[blen].
|
||||
*/
|
||||
void
|
||||
EnvSubst(const char *str, char *bptr, unsigned int blen)
|
||||
{
|
||||
char env[128];
|
||||
int nw, len;
|
||||
const char *si, *p1, *p2;
|
||||
|
||||
for (si = str, nw = 0;; si = p2)
|
||||
{
|
||||
p1 = strchr(si, '$');
|
||||
if (!p1)
|
||||
{
|
||||
nw += snprintf(bptr + nw, blen - nw, "%s", si);
|
||||
break;
|
||||
}
|
||||
len = p1 - si;
|
||||
nw += snprintf(bptr + nw, blen - nw, "%.*s", len, si);
|
||||
p1 += 1;
|
||||
p2 = *p1 == '{' ? p1 + 1 : p1;
|
||||
/* $ENV_VAR - Name is validted */
|
||||
for (; *p2 != '\0'; p2++)
|
||||
{
|
||||
if (!(isalnum(*p2) || *p2 == '_'))
|
||||
break;
|
||||
}
|
||||
len = p2 - p1;
|
||||
if (*p1 == '{')
|
||||
{
|
||||
if (*p2 != '}')
|
||||
{
|
||||
p2 = p1;
|
||||
continue;
|
||||
}
|
||||
p1 += 1;
|
||||
p2 += 1;
|
||||
len -= 1;
|
||||
}
|
||||
if (len <= 0)
|
||||
continue;
|
||||
snprintf(env, sizeof(env), "%.*s", len, p1);
|
||||
p1 = getenv(env);
|
||||
if (p1)
|
||||
nw += snprintf(bptr + nw, blen - nw, "%s", p1);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -118,6 +118,9 @@ void Esetenv(const char *name, const char *value);
|
|||
/* misc.c */
|
||||
void __PRINTF__ Eprintf(const char *fmt, ...);
|
||||
|
||||
/* string.c */
|
||||
void EnvSubst(const char *str, char *bptr, unsigned int blen);
|
||||
|
||||
#define Evsnprintf vsnprintf
|
||||
#define Esnprintf snprintf
|
||||
|
||||
|
|
Loading…
Reference in New Issue