[PATCH 1/2] env: let setenv() take printf arguments

Sascha Hauer s.hauer at pengutronix.de
Fri Jun 17 01:05:32 PDT 2022


It's a common pattern to (ba)sprintf to a string and then call setenv()
with this string. Let setenv() take printf arguments to make that
easier.

Signed-off-by: Sascha Hauer <s.hauer at pengutronix.de>
---
 common/env.c          | 10 +++++++++-
 include/environment.h |  5 +++--
 2 files changed, 12 insertions(+), 3 deletions(-)

diff --git a/common/env.c b/common/env.c
index 05add63f62..d69c86feab 100644
--- a/common/env.c
+++ b/common/env.c
@@ -251,11 +251,18 @@ static int dev_setenv(const char *name, const char *val)
  * Use unsetenv() to unset.
  */
 
-int setenv(const char *_name, const char *value)
+int setenv(const char *_name, const char *fmt, ...)
 {
+	va_list ap;
 	char *name = strdup(_name);
 	int ret = 0;
 	struct list_head *list;
+	char *value;
+	int len;
+
+	va_start(ap, fmt);
+	len = vasprintf(&value, fmt, ap);
+	va_end(ap);
 
 	if (strchr(name, '.')) {
 		ret = dev_setenv(name, value);
@@ -271,6 +278,7 @@ int setenv(const char *_name, const char *value)
 
 	ret = setenv_raw(list, name, value);
 out:
+	free(value);
 	free(name);
 
 	return ret;
diff --git a/include/environment.h b/include/environment.h
index 19e522cfb6..9e1cb5a929 100644
--- a/include/environment.h
+++ b/include/environment.h
@@ -31,7 +31,7 @@ char *var_name(struct variable_d *);
 
 #ifdef CONFIG_ENVIRONMENT_VARIABLES
 const char *getenv(const char *);
-int setenv(const char *, const char *);
+int setenv(const char *, const char *fmt, ...)  __attribute__ ((format(__printf__, 2, 3)));
 void export_env_ull(const char *name, unsigned long long val);
 int getenv_ull(const char *name, unsigned long long *val);
 int getenv_ul(const char *name, unsigned long *val);
@@ -44,7 +44,8 @@ static inline char *getenv(const char *var)
 	return NULL;
 }
 
-static inline int setenv(const char *var, const char *val)
+static inline __attribute__ ((format(__printf__, 2, 3))) int setenv(
+	const char *var, const char *fmt, ...)
 {
 	return 0;
 }
-- 
2.30.2




More information about the barebox mailing list