| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | /* | ||
| 2 | ** EPITECH PROJECT, 2024 | ||
| 3 | ** 42sh | ||
| 4 | ** File description: | ||
| 5 | ** The file containing the source builtin | ||
| 6 | */ | ||
| 7 | /** | ||
| 8 | * @file source.c | ||
| 9 | * @brief The file containing the source builtin | ||
| 10 | */ | ||
| 11 | |||
| 12 | #include "../../include/myshell.h" | ||
| 13 | |||
| 14 | /** | ||
| 15 | * @brief Execute a bash file | ||
| 16 | * @param mysh The shell structure | ||
| 17 | * @param file The file descriptor | ||
| 18 | * @param size The size of the file | ||
| 19 | * @return <b>int</b> The exit status of last command if the command succeed, | ||
| 20 | * <u>1</u> otherwise | ||
| 21 | */ | ||
| 22 | 365 | int execute_bash_file(mysh_t *mysh, int file, size_t size) | |
| 23 | { | ||
| 24 | 365 | char **file_content = NULL; | |
| 25 | 365 | char *buffer = CALLOC(size + 1, sizeof(char)); | |
| 26 | 365 | pid_t pid = 0; | |
| 27 | |||
| 28 |
1/2✗ Branch 1 not taken.
✓ Branch 2 taken 365 times.
|
365 | if (read(file, buffer, size) == -1) |
| 29 | ✗ | return 1; | |
| 30 | 365 | pid = fork(); | |
| 31 |
2/2✓ Branch 0 taken 374 times.
✓ Branch 1 taken 365 times.
|
739 | if (pid == 0) { |
| 32 | 374 | file_content = my_str_to_word_array_select(buffer, "\n"); | |
| 33 |
2/2✓ Branch 0 taken 3730 times.
✓ Branch 1 taken 374 times.
|
4104 | for (int i = 0; file_content[i] != NULL; i++) { |
| 34 | 3730 | remove_comments(file_content[i]); | |
| 35 | 3730 | analyse_backticks(mysh, file_content[i]); | |
| 36 | } | ||
| 37 | 374 | FREE_WORD_ARRAY(file_content); | |
| 38 | 374 | my_exit(mysh, mysh->exit_status, ""); | |
| 39 | } | ||
| 40 | 365 | waitpid(pid, &mysh->exit_status, 0); | |
| 41 | 365 | return mysh->exit_status; | |
| 42 | } | ||
| 43 | |||
| 44 | /** | ||
| 45 | * @brief The source builtin | ||
| 46 | * @param mysh The shell structure | ||
| 47 | * @return <b>int</b> <u>0</u> if the command succeed, <u>1</u> otherwise | ||
| 48 | */ | ||
| 49 | ✗ | int exec_source(mysh_t *mysh) | |
| 50 | { | ||
| 51 | struct stat file_infos; | ||
| 52 | int file; | ||
| 53 | |||
| 54 | ✗ | if (mysh->args[1] == NULL) { | |
| 55 | ✗ | my_fprintf(2, "source: Too few arguments.\n"); | |
| 56 | ✗ | return 1; | |
| 57 | } | ||
| 58 | ✗ | file = open(mysh->args[1], O_RDONLY); | |
| 59 | ✗ | if (file == -1 || stat(mysh->args[1], &file_infos) == -1) { | |
| 60 | ✗ | my_fprintf(2, "%s: %s.\n", mysh->args[1], strerror(errno)); | |
| 61 | ✗ | return 1; | |
| 62 | } | ||
| 63 | ✗ | return execute_bash_file(mysh, file, file_infos.st_size); | |
| 64 | } | ||
| 65 |