summaryrefslogtreecommitdiff
path: root/42sh/src/utils/env.c
diff options
context:
space:
mode:
Diffstat (limited to '42sh/src/utils/env.c')
-rw-r--r--42sh/src/utils/env.c125
1 files changed, 125 insertions, 0 deletions
diff --git a/42sh/src/utils/env.c b/42sh/src/utils/env.c
new file mode 100644
index 0000000..e3095a4
--- /dev/null
+++ b/42sh/src/utils/env.c
@@ -0,0 +1,125 @@
+#define _DEFAULT_SOURCE
+#define _POSIX_C_SOURCE 200809L
+
+#include "utils/env.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+#include "utils/libstring.h"
+
+void env_set(const char *name, const char *value)
+{
+ if (setenv(name, value, 1) == -1)
+ {
+ fprintf(stderr, "env_set: unable to set \'%s\'=\'%s\'.\n", name, value);
+ }
+}
+
+void env_unset(const char *name)
+{
+ if (unsetenv(name) == -1)
+ {
+ fprintf(stderr, "env_unset: unable to unset \'%s\'.\n", name);
+ }
+}
+
+static void _generate_random(void)
+{
+ int d = rand() % MAX_RAND;
+ char buf[16] = { 0 };
+ sprintf(buf, "%d", d);
+ env_set("RANDOM", buf);
+}
+
+static struct string *_cat_args(void)
+{
+ int nb_args = atoi(env_get("#"));
+ struct string *s = string_create(NULL);
+ for (int i = 1; i <= nb_args; i++)
+ {
+ char buf[16] = { 0 };
+ sprintf(buf, "%d", i);
+ string_pushstr(s, env_get(buf));
+ if (i != nb_args)
+ {
+ string_pushc(s, ' ');
+ }
+ }
+ return s;
+}
+
+char *env_get(const char *name)
+{
+ if (STRINGS_ARE_EQUAL(name, "RANDOM"))
+ {
+ _generate_random();
+ }
+ if (STRINGS_ARE_EQUAL(name, "*"))
+ {
+ struct string *s = _cat_args();
+ env_set("*", s->data);
+ string_free(s);
+ }
+ if (STRINGS_ARE_EQUAL(name, "@"))
+ {
+ struct string *s = string_create(NULL);
+ string_pushc(s, '\"');
+ struct string *args = _cat_args();
+ string_pushstr(s, args->data);
+ string_pushc(s, '\"');
+ if (s->length > 2)
+ {
+ env_set("@", s->data);
+ }
+ string_free(s);
+ string_free(args);
+ }
+ return getenv(name);
+}
+
+void env_clear(void)
+{
+ if (clearenv())
+ {
+ fprintf(stderr, "env_clear: unable to clear the environment.\n");
+ }
+}
+
+static void _set_pwd(void)
+{
+ char buf[MAX_PATH_SIZE] = { 0 };
+ char *path = getcwd(buf, MAX_PATH_SIZE);
+ env_set("PWD", path);
+ env_set("OLDPWD", path);
+}
+
+static void _set_uid(void)
+{
+ uid_t uid = getuid();
+ // Magic value but UID is an integer (POSIX requirement)
+ // So it won't be more that 10 chars long
+ char buf[16] = { 0 };
+ sprintf(buf, "%u", uid);
+ env_set("UID", buf);
+}
+
+static void _set_pid(void)
+{
+ pid_t pid = getpid();
+ // Magic value but PID is an integer (POSIX requirement)
+ // So it won't be more that 10 chars long
+ char buf[16] = { 0 };
+ sprintf(buf, "%d", pid);
+ env_set("$", buf);
+}
+
+void env_setup(void)
+{
+ _set_pwd();
+ _set_uid();
+ _set_pid();
+ env_set("IFS", DEFAULT_IFS);
+ env_set("?", "0");
+}