MiniDevil As beautiful as a shell
env_utils.c
Go to the documentation of this file.
1 /* ************************************************************************** */
2 /* */
3 /* ::: :::::::: */
4 /* env_utils.c :+: :+: :+: */
5 /* +:+ +:+ +:+ */
6 /* By: baelgadi <baelgadi@student.42.fr> +#+ +:+ +#+ */
7 /* +#+#+#+#+#+ +#+ */
8 /* Created: 2025/12/03 19:31:46 by zotaj-di #+# #+# */
9 /* Updated: 2026/03/04 04:42:13 by baelgadi ### ########.fr */
10 /* */
11 /* ************************************************************************** */
12 
13 #include "env.h"
14 #include "libft.h"
15 
24 void handle_shlvl(t_env **env_list)
25 {
26  char *shlvl_str;
27  int shlvl_num;
28  char *new_shlvl;
29 
30  shlvl_str = get_env_value(*env_list, "SHLVL");
31  if (shlvl_str)
32  {
33  shlvl_num = ft_atoi(shlvl_str);
34  shlvl_num++;
35  }
36  else
37  shlvl_num = 1;
38  new_shlvl = ft_itoa(shlvl_num);
39  set_env_value(env_list, "SHLVL", new_shlvl);
40  free(new_shlvl);
41 }
42 
51 void ensure_pwd(t_env **env_list)
52 {
53  char *pwd;
54  char cwd[PATH_MAX];
55 
56  pwd = get_env_value(*env_list, "PWD");
57  if (!pwd)
58  {
59  if (getcwd(cwd, PATH_MAX))
60  set_env_value(env_list, "PWD", cwd);
61  }
62 }
63 
69 void free_env_list(t_env **env_list)
70 {
71  t_env *current;
72  t_env *next;
73 
74  current = *env_list;
75  while (current)
76  {
77  next = current->next;
78  free(current->key);
79  free(current->value);
80  free(current);
81  current = next;
82  }
83 }
84 
91 int env_list_size(t_env *env_list)
92 {
93  int count;
94  t_env *current;
95 
96  count = 0;
97  current = env_list;
98  while (current)
99  {
100  count++;
101  current = current->next;
102  }
103  return (count);
104 }
Environment variable management prototypes.
int set_env_value(t_env **env_list, char *key, char *value)
Set or create an environment variable.
char * get_env_value(t_env *env_list, char *key)
Look up an environment variable's value by its key.
int env_list_size(t_env *env_list)
Count the number of nodes in the environment list.
Definition: env_utils.c:91
void ensure_pwd(t_env **env_list)
Ensure PWD exists in the environment.
Definition: env_utils.c:51
void handle_shlvl(t_env **env_list)
Increment the SHLVL environment variable.
Definition: env_utils.c:24
void free_env_list(t_env **env_list)
Free all nodes in the env linked list.
Definition: env_utils.c:69
Environment variable (doubly linked list)
Definition: structs.h:87
char * key
Variable name.
Definition: structs.h:88
char * value
Value (NULL if export only)
Definition: structs.h:89
struct s_env * next
Next node.
Definition: structs.h:90