Line | Branch | Exec | Source |
---|---|---|---|
1 | /* | ||
2 | ** EPITECH PROJECT, 2024 | ||
3 | ** 42sh | ||
4 | ** File description: | ||
5 | ** The file containing the unsetenv builtin | ||
6 | */ | ||
7 | /** | ||
8 | * @file unsetenv.c | ||
9 | * @brief The file containing the unsetenv builtin | ||
10 | */ | ||
11 | |||
12 | #include "../../include/myshell.h" | ||
13 | |||
14 | /** | ||
15 | * @brief Skip the variables to delete | ||
16 | * @param args The command arguments | ||
17 | * @param env The actual env | ||
18 | * @param index The index of the env | ||
19 | * @return <b>void</b> | ||
20 | */ | ||
21 | 47 | static void skip_variables(char **args, char **env, int *index) | |
22 | { | ||
23 |
3/4✓ Branch 0 taken 47 times.
✓ Branch 1 taken 47 times.
✓ Branch 2 taken 47 times.
✗ Branch 3 not taken.
|
94 | for (int var_index = 1; args[var_index] != NULL && env[*index] != NULL; |
24 | 47 | var_index++) { | |
25 |
2/2✓ Branch 1 taken 1 times.
✓ Branch 2 taken 46 times.
|
47 | if (my_strncmp(env[*index], args[var_index], |
26 | 47 | my_strlen(args[var_index])) == 0 | |
27 |
1/2✓ Branch 1 taken 1 times.
✗ Branch 2 not taken.
|
1 | && env[*index][my_strlen(args[var_index])] == '=') |
28 | 1 | (*index)++; | |
29 | } | ||
30 | 47 | } | |
31 | |||
32 | /** | ||
33 | * @brief Search and delete the variable in the env | ||
34 | * @param args The command arguments | ||
35 | * @param env The actual env | ||
36 | * @param new_env The new env | ||
37 | * @return <b>void</b> | ||
38 | */ | ||
39 | 27 | static void search_and_delete(char **args, char **env, char **new_env) | |
40 | { | ||
41 | 27 | int index_new = 0; | |
42 | |||
43 |
2/2✓ Branch 0 taken 47 times.
✓ Branch 1 taken 27 times.
|
74 | for (int index = 0; env[index] != NULL; index++) { |
44 | 47 | skip_variables(args, env, &index); | |
45 | 47 | new_env[index_new] = env[index]; | |
46 | 47 | index_new++; | |
47 | } | ||
48 | 27 | new_env[index_new] = NULL; | |
49 | 27 | } | |
50 | |||
51 | /** | ||
52 | * @brief The unsetenv builtin | ||
53 | * @param mysh The shell structure | ||
54 | * @return <b>int</b> <u>0</u> if the command succeed, <u>1</u> otherwise | ||
55 | */ | ||
56 | 27 | int exec_unsetenv(mysh_t *mysh) | |
57 | { | ||
58 | char **new_env; | ||
59 | |||
60 |
1/2✗ Branch 0 not taken.
✓ Branch 1 taken 27 times.
|
27 | if (mysh->args[1] == NULL) { |
61 | ✗ | my_fprintf(2, "unsetenv: Too few arguments.\n"); | |
62 | ✗ | return 1; | |
63 | } | ||
64 | 27 | new_env = CALLOC(my_array_len((void **)mysh->env) + 1, sizeof(char *)); | |
65 | 27 | search_and_delete(mysh->args, mysh->env, new_env); | |
66 | 27 | mysh->env = new_env; | |
67 | 27 | return 0; | |
68 | } | ||
69 |