| 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 | 371 | int execute_bash_file(mysh_t *mysh, int file, size_t size) | |
| 23 | { | ||
| 24 | 371 | char **file_content = NULL; | |
| 25 | 371 | char *buffer = CALLOC(size + 1, sizeof(char)); | |
| 26 | 371 | pid_t pid = 0; | |
| 27 | |||
| 28 | 1/2✗ Branch 1 not taken. ✓ Branch 2 taken 371 times. | 371 | if (read(file, buffer, size) == -1) | 
| 29 | ✗ | return 1; | |
| 30 | 371 | pid = fork(); | |
| 31 | 2/2✓ Branch 0 taken 375 times. ✓ Branch 1 taken 371 times. | 746 | if (pid == 0) { | 
| 32 | 375 | file_content = my_str_to_word_array_select(buffer, "\n"); | |
| 33 | 2/2✓ Branch 0 taken 3741 times. ✓ Branch 1 taken 375 times. | 4116 | for (int i = 0; file_content[i] != NULL; i++) { | 
| 34 | 3741 | remove_comments(file_content[i]); | |
| 35 | 3741 | analyse_backticks(mysh, file_content[i]); | |
| 36 | } | ||
| 37 | 375 | FREE_WORD_ARRAY(file_content); | |
| 38 | 375 | my_exit(mysh, mysh->exit_status, ""); | |
| 39 | } | ||
| 40 | 371 | waitpid(pid, &mysh->exit_status, 0); | |
| 41 | 371 | 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 | 6 | int exec_source(mysh_t *mysh) | |
| 50 | { | ||
| 51 | struct stat file_infos; | ||
| 52 | int file; | ||
| 53 | |||
| 54 | 2/2✓ Branch 0 taken 5 times. ✓ Branch 1 taken 1 times. | 6 | if (mysh->args[1] == NULL) { | 
| 55 | 5 | my_fprintf(2, "source: Too few arguments.\n"); | |
| 56 | 5 | return 1; | |
| 57 | } | ||
| 58 | 1 | file = open(mysh->args[1], O_RDONLY); | |
| 59 | 2/4✓ Branch 0 taken 1 times. ✗ Branch 1 not taken. ✗ Branch 3 not taken. ✓ Branch 4 taken 1 times. | 1 | 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 | 1 | return execute_bash_file(mysh, file, file_infos.st_size); | |
| 64 | } | ||
| 65 |