kwo pushed a commit to branch master.

http://git.enlightenment.org/e16/e16.git/commit/?id=52d8dfe805ea57129161f1250605f5cef24518ea

commit 52d8dfe805ea57129161f1250605f5cef24518ea
Author: Kim Woelders <[email protected]>
Date:   Tue Feb 15 10:03:09 2022 +0100

    Introduce EnvSubst()
---
 src/string.c | 52 +++++++++++++++++++++++++++++++++++++++++++++++++++-
 src/util.h   |  3 +++
 2 files changed, 54 insertions(+), 1 deletion(-)

diff --git a/src/string.c b/src/string.c
index 732842a6..a9e5db80 100644
--- a/src/string.c
+++ b/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);
+     }
+}
diff --git a/src/util.h b/src/util.h
index e4dd73c3..27fea8fb 100644
--- a/src/util.h
+++ b/src/util.h
@@ -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
 

-- 


Reply via email to