diff --git a/3-ShellP1/questions.md b/3-ShellP1/questions.md new file mode 100644 index 0000000000000000000000000000000000000000..588a178dad2968b7d011eab3920097126bada498 --- /dev/null +++ b/3-ShellP1/questions.md @@ -0,0 +1,39 @@ +1. In this assignment I suggested you use `fgets()` to get user input in the main while loop. Why is `fgets()` a good choice for this application? + + > **Answer**: `fgets()` is a good choice because it safely reads user input line-by-line, which is ideal for a shell where commands are entered one line at a time. `fgets()` prevents buffer overflows by limiting the number of characters read, based on the buffer size provided. Additionally, it can handle EOF conditions. + +2. You needed to use `malloc()` to allocte memory for `cmd_buff` in `dsh_cli.c`. Can you explain why you needed to do that, instead of allocating a fixed-size array? + + > **Answer**: Using `malloc()` allows for dynamic memory allocation, which allow flexible allocation of exact amount of memory needed at runtime. This is beneficial if the shell is expected to handle variable-sized commands. In contrast, a fixed-size array would waste memory if the commands are short or risk overflow if the commands exceed the predefined limit. Dynamic allocation also improves scalability for future features. + +3. In `dshlib.c`, the function `build_cmd_list()` must trim leading and trailing spaces from each command before storing it. Why is this necessary? If we didn't trim spaces, what kind of issues might arise when executing commands in our shell? + + > **Answer**: Trimming spaces ensures that commands and arguments are parsed accurately. If we didn’t trim: + > - Commands like `" ls "` would include spaces, causing the shell to fail when trying to execute them since no such command exists. + > - Piping issues could occur, where pipes (`|`) might not be detected correctly if surrounded by spaces. + + +4. For this question you need to do some research on STDIN, STDOUT, and STDERR in Linux. We've learned this week that shells are "robust brokers of input and output". Google _"linux shell stdin stdout stderr explained"_ to get started. + +- One topic you should have found information on is "redirection". Please provide at least 3 redirection examples that we should implement in our custom shell, and explain what challenges we might have implementing them. + + > **Answer**: Here are some redirections that should be implemented in our custom shell: + > - Redirecting output to a file, challenge: we have to redirect file descriptors before executing the command. + > - Appending output to a file, challenge: requires opening the file in append mode and handling file permissions correctly. + > - Redirecting input from a file, challenge: requires properly managing file descriptors and ensuring the file exists before processing. + + +- You should have also learned about "pipes". Redirection and piping both involve controlling input and output in the shell, but they serve different purposes. Explain the key differences between redirection and piping. + + > **Answer**: Redirection purpose is to redirects input/output to or from files. While pipes purpose is to connects the STDOUT of one command directly to the STDIN of another command. + +- STDERR is often used for error messages, while STDOUT is for regular output. Why is it important to keep these separate in a shell? + + > **Answer**: + > - STDOUT is for regular output (results). + > - STDERR is for error messages (problems). + > This separation helps users identify errors easily without mixing them with normal output. + +- How should our custom shell handle errors from commands that fail? Consider cases where a command outputs both STDOUT and STDERR. Should we provide a way to merge them, and if so, how? + + > **Answer**: Our custom shell should display clear error messages when commands fail and not to execute it. We can merge STDOUT and STDERR by doing something like `command > output.txt 2>&1` to redirects STDERR to the same location as STDOUT. \ No newline at end of file diff --git a/3-ShellP1/readme.md b/3-ShellP1/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..71e93196b684cf295958a5f79a003c69c0e16e0a --- /dev/null +++ b/3-ShellP1/readme.md @@ -0,0 +1,223 @@ +# Assignment: Custom Shell Part 1 - Command Line Parser + +This week we will begin the first of a multi-part assignment to build a **custom shell** called `dsh` (Drexel shell). + +# What is a Shell? + +A "shell" is a type of user interface for interacting with an operating system. You are already familiar with Linux command line shells in this course - the integrated terminal in vscode runs a shell (probably "bash" if you are using any of the Linux virtualization options suggested). + +When we say your terminal "runs the bash shell" it means this: a shell is a generalized term for a binary that provides a terminal-based interface; "bash" is the name of a specific shell that you can install and run as a binary. Linux distributions have default shell configurations, and most of them default to `bash`. You can install new shells and use them as your default shell upon login; `zsh` is a popular shell that many users prefer over bash. + +The purpose of the shell is to broker inputs and outputs to built-in shell commands, other binaries, and kernel operations like syscalls. When you open a terminal in vscode, the shell is interactive and you must provide inputs by typing in the terminal. Shells are also a part of "headless" processes like cron jobs (in Linux cron jobs run binaries on a schedule automatically, even if you are not logged in); these background jobs still execute in the context of a shell. The shell provides the job the same interface to the operating system, and the job can use the output that the shell brokers. + +# Shell built-in vs. external commands + +Most "commands" you run are not implemented in the shell logic; they are usually other binaries on the filesystem that are invoked when you refer to them from your shell. + +However ... there several (50+) commands that are built in to the logic of the shell itself. Here are some examples: + +* cd: change the current working directory +* exit: exit from the shell process +* echo: print text to STDOUT +* export: set environment variable in the current shell + +In this assignment, we will implement one "built in" command: `exit`. There is also an optional `dragon` command for extra credit. + +Future assignments will generally follow the pattern of other popular shells and implement some of the common builtin commands. + +# What else does the shell do? + +Beyond implementing built-in commands, a shell acts as a robust broker of input and output. Shells must provide a lot of "glue" to handle streams; for example this is a common sequence you might see in a linux shell: + +```sh +run-some-command | grep "keyword" +``` + +The `|` symbol is called a pipe, and it serves to stream the output of the first command (`run-some-command`) into the input of the second command (`grep`). We'll implement much of this "glue" logic in future assignments in this course. + +# Assignment Details + +In this assignment you will implement the first part of `dsh`: a command line parser to interpret commands and their arguments. + +You will not implement any command logic, other than exiting when the `exit` command is provided. There is also one optional extra credit for implementing the `dragon` command. + +### Step 1 - Review [./starter/dshlib.h](./starter/dshlib.h) + +The file [./starter/dshlib.h](./starter/dshlib.h) contains some useful definitions and types. Review the available resources in this file before you start coding - these are intended to make your work easier and more robust! + +### Step 2 - Implement [./starter/dsh_cli.c](./starter/dsh_cli.c) + +This contains the entrypoint of your shell. Detailed comments are provided to implement `main`. + +Shells usually run in a forever loop until a command is issued to exit the shell (usually `exit`); an example is provided in comments to get you started: + +```c + while (1) + { + printf("%s", SH_PROMPT); + if (fgets(cmd_buff, ARG_MAX, stdin) == NULL) + { + printf("\n"); + break; + } + // remove the trailing \n from cmd_buff + cmd_buff[strcspn(cmd_buff, "\n")] = '\0'; + + // IMPLEMENT THE REST OF THE REQUIREMENTS + } +``` + +The libc `fgets` function is a good choice here due to being "lines of input" based. This excerpt from `man 3 fgets` explains why: + +> fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer. + +Key point, `Reading stops after an EOF or a newline` - which makes it essentially a "line by line" processor. This is an important detail for step 3! + +### Step 2a - Implement the built-in function `exit` + +Inside the main loop in `main()` you can check for and implement the logic for the `exit` command. When this command is issued, your process should exit with a `0` exit code. + +This is also similar to how you would implement the extra credit - instead of existing, you would print more output to STDOUT. + +### Step 3 - Implement [./starter/dshlib.c](./starter/dshlib.c) + +In this file you need to complete the implementation for `build_cmd_list`: + +```c +int build_cmd_list(char *cmd_line, command_list_t *clist) +{ + printf(M_NOT_IMPL); + return EXIT_NOT_IMPL; +} +``` + +This takes two parameters: + +* cmd_line - one complete "line" of user input from the shell; remember `dsh_cli.c` should use EOF / newline (i.e. `fgets()`) to read one line at a time +* clist - pointer to a `command_list_t`; you must populate this structure with parsed commands + +Remember - the goal of this assignment is not to implement command logic, but to parse the input string and populate `clist` with parsed commands and their arguments. The comments provide details on logic and references to some helpful definitions. + +### Step 4 - Answer Questions + +Answer the questions located in [./questions.md](./questions.md). + +### Sample Run with Sample Output +The below shows a sample run executing multiple commands and the expected program output: + +```bash +➜ solution git:(main) ✗ ./dsh +dsh> cmd +PARSED COMMAND LINE - TOTAL COMMANDS 1 +<1> cmd +dsh> cmd_args a1 a2 -a3 --a4 +PARSED COMMAND LINE - TOTAL COMMANDS 1 +<1> cmd_args [a1 a2 -a3 --a4] +dsh> dragon +[DRAGON for extra credit would print here] +dsh> cmd1 | cmd2 +PARSED COMMAND LINE - TOTAL COMMANDS 2 +<1> cmd1 +<2> cmd2 +dsh> cmda1 a1 a2 | cmda2 a3 a4 | cmd3 +PARSED COMMAND LINE - TOTAL COMMANDS 3 +<1> cmda1 [a1 a2] +<2> cmda2 [a3 a4] +<3> cmd3 +dsh> +warning: no commands provided +dsh> c1 | c2 | c3 | c4 | c5 | c6 | c7 | c8 +PARSED COMMAND LINE - TOTAL COMMANDS 8 +<1> c1 +<2> c2 +<3> c3 +<4> c4 +<5> c5 +<6> c6 +<7> c7 +<8> c8 +dsh> c1 | c2 | c3 | c4 | c5 | c6 | c7 | c8 | c9 +error: piping limited to 8 commands +dsh> pipe1|pipe2|pipe3 |pipe4 +PARSED COMMAND LINE - TOTAL COMMANDS 4 +<1> pipe1 +<2> pipe2 +<3> pipe3 +<4> pipe4 +dsh> pipe1|pipe2 |pipe3 pipe4| pipe5 +PARSED COMMAND LINE - TOTAL COMMANDS 4 +<1> pipe1 +<2> pipe2 +<3> pipe3 [pipe4] +<4> pipe5 +dsh> exit +➜ solution git:(main) ✗ +``` + +### Extra Credit: +5 + +Add logic to detect the command "`dragon`" and print the Drexel dragon in ascii art. + +Drexel dragon in ascii with spaces preserved: + +``` + @%%%% + %%%%%% + %%%%%% + % %%%%%%% @ + %%%%%%%%%% %%%%%%% + %%%%%%% %%%%@ %%%%%%%%%%%%@ %%%%%% @%%%% + %%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%% + %%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%% %%%%%%%%%%%%%%% + %%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%% %%% + %%%%%%%%%%%%%%%%%%%%%%%%%%%%@ @%%%%%%%%%%%%%%%%%% %% + %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%% + %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@%%%%%%@ + %%%%%%%%@ %%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%% %% + %%%%%%%%%%%%% %%@%%%%%%%%%%%% %%%%%%%%%%% %%%%%%%%%%%% @% + %%%%%%%%%% %%% %%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%% + %%%%%%%%% % %%%%%%%%%%%%% %%%%%%%%%%%%@%%%%%%%%%%% +%%%%%%%%%@ % %%%%%%%%%%%%% @%%%%%%%%%%%%%%%%%%%%%%%%% +%%%%%%%%@ %%@%%%%%%%%%%%% @%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%%%%%%%@ %%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%%%%%%%%%% %%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% +%%%%%%%%%@ @%%%%%%%%%%%%%% %%%%%%%%%%%%@ %%%% %%%%%%%%%%%%%%%%% %%%%%%%% +%%%%%%%%%% %%%%%%%%%%%%%%%%% %%%%%%%%%%%%% %%%%%%%%%%%%%%%%%% %%%%%%%%% +%%%%%%%%%@%%@ %%%%%%%%%%%%%%%%@ %%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%% %% + %%%%%%%%%% % %%%%%%%%%%%%%%@ %%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%% %% + %%%%%%%%%%%% @ %%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% + %%%%%%%%%%%%% %% % %@ %%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% + %%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%% @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%% + %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% + @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%% + %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%% %%%%%%% + %%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%% @%%%%%%%%% + %%%%%%%%%%%%%%%%%%%% @%@% @%%%%%%%%%%%%%%%%%% %%% + %%%%%%%%%%%%%%% %%%%%%%%%% %%%%%%%%%%%%%%% % + %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%% + %%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%% %%%%%%%%%% %%%@ + %%%%%%%%%%%%%%%%%%% %%%%%% %% %%%%%%%%%%%%%@ + %%%%%%%@ +``` + +### Extra Credit: ++5 + +Implement the extra credit for the `/dragon` using compressed/binary data in your code to represent the dragon (i.e. not just using strings/defines). + +#### Grading Rubric + +This assignment will be weighted 50 points. + +- 25 points: Correct implementation of required functionality +- 5 points: Code quality (how easy is your solution to follow) +- 15 points: Answering the written questions: [questions.md](./questions.md) +- 5 points: [EXTRA CREDIT] Implementation of the `dragon` command +- 5 points: [EXTRA CREDIT++] Implementation of the `dragon` command where the representation of the dragon is compressed in your code + +Total points achievable is 60/50. + +#### Automated Testing + +In order to help you out the starter package provides a testing script called `test.sh`. You should expect your tests to fail when running the starter and then start to pass as you implement the required functionality. Also note a few of the test cases are commented out. + diff --git a/3-ShellP1/starter/dragon.bin b/3-ShellP1/starter/dragon.bin new file mode 100644 index 0000000000000000000000000000000000000000..cce2d5afea01f25637612a3ea87396c38ff931a1 --- /dev/null +++ b/3-ShellP1/starter/dragon.bin @@ -0,0 +1,3 @@ +x���A�� �=�`�{����J +�L���Ek!�HDm�5��F��#�HB<���\ƌ�ÈXs=_ 6����[�w�-�`ز1�J��'Y~R�D����ڹW�@2AϺ���@�4X*����'rUP!bA Q�c�gj� +�{c�"d �+�)#+{�>dN��`P4!�`?$\wH���$t�Pz>RA� �J��O���IJ@D�3!e�Ʉ�n�ܧk�m0���|���W��U��W�@܃a��k��[r<�<|����Ʀr���,�� ��f_�=y��uE"e\\+'P��![>#Ф�(!�4�_{��}y��?����h&{ )�����q[!DZ&��}a"L+�_�3�v�G \ No newline at end of file diff --git a/3-ShellP1/starter/dsh b/3-ShellP1/starter/dsh new file mode 100755 index 0000000000000000000000000000000000000000..bf8a6f9f628431b104fe182d5354b5deba6d7493 Binary files /dev/null and b/3-ShellP1/starter/dsh differ diff --git a/3-ShellP1/starter/dsh_cli.c b/3-ShellP1/starter/dsh_cli.c new file mode 100644 index 0000000000000000000000000000000000000000..3131276d633d00381771c7c9893045f33245e193 --- /dev/null +++ b/3-ShellP1/starter/dsh_cli.c @@ -0,0 +1,158 @@ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <zlib.h> // For decompression + +#include "dshlib.h" + +/* + * Implement your main function by building a loop that prompts the + * user for input. Use the SH_PROMPT constant from dshlib.h and then + * use fgets to accept user input. Since we want fgets to also handle + * end of file so we can run this headless for testing we need to check + * the return code of fgets. I have provided an example below of how + * to do this assuming you are storing user input inside of the cmd_buff + * variable. + * + * while(1){ + * printf("%s", SH_PROMPT); + * if (fgets(cmd_buff, ARG_MAX, stdin) == NULL){ + * printf("\n"); + * break; + * } + * //remove the trailing \n from cmd_buff + * cmd_buff[strcspn(cmd_buff,"\n")] = '\0'; + * + * //IMPLEMENT THE REST OF THE REQUIREMENTS + * } + * + * Also, use the constants in the dshlib.h in this code. + * SH_CMD_MAX maximum buffer size for user input + * EXIT_CMD constant that terminates the dsh program + * SH_PROMPT the shell prompt + * OK the command was parsed properly + * WARN_NO_CMDS the user command was empty + * ERR_TOO_MANY_COMMANDS too many pipes used + * + * Expected output: + * + * CMD_OK_HEADER if the command parses properly. You will + * follow this by the command details + * + * CMD_WARN_NO_CMD if the user entered a blank command + * CMD_ERR_PIPE_LIMIT if the user entered too many commands using + * the pipe feature, e.g., cmd1 | cmd2 | ... | + * + * See the provided test cases for output expectations. + */ + +#define DRAGON_FILE "dragon.bin" +#define DRAGON_BUFFER_SIZE 100000 + +void print_dragon_from_file() { + FILE *file = fopen(DRAGON_FILE, "rb"); + if (!file) { + fprintf(stderr, "Error: Could not open %s\n", DRAGON_FILE); + return; + } + + // Determine the size of the compressed file + fseek(file, 0, SEEK_END); + long file_size = ftell(file); + rewind(file); + + unsigned char *compressed_data = (unsigned char *)malloc(file_size); + if (!compressed_data) { + fprintf(stderr, "Memory allocation failed!\n"); + fclose(file); + return; + } + + // Read the compressed data from the file + fread(compressed_data, 1, file_size, file); + fclose(file); + + unsigned char *decompressed_data = (unsigned char *)malloc(DRAGON_BUFFER_SIZE); + if (!decompressed_data) { + fprintf(stderr, "Memory allocation failed!\n"); + free(compressed_data); + return; + } + + // Decompress the data + uLongf decompressed_size = DRAGON_BUFFER_SIZE; + if (uncompress(decompressed_data, &decompressed_size, compressed_data, file_size) != Z_OK) { + fprintf(stderr, "Decompression failed!\n"); + free(compressed_data); + free(decompressed_data); + return; + } + + printf("%s", decompressed_data); + + free(compressed_data); + free(decompressed_data); +} + +int main() +{ + char *cmd_buff = (char *)malloc(SH_CMD_MAX * sizeof(char)); + if (cmd_buff == NULL) { + fprintf(stderr, "Memory allocation failed!\n"); + return -1; + } + + command_list_t clist; + + while (1) { + printf("%s", SH_PROMPT); + if (fgets(cmd_buff, SH_CMD_MAX, stdin) == NULL) { + printf("\n"); + break; + } + + // Remove the trailing newline character + cmd_buff[strcspn(cmd_buff, "\n")] = '\0'; + + // Check for empty command + if (strlen(cmd_buff) == 0) { + printf(CMD_WARN_NO_CMD); + continue; + } + + // Exit command + if (strcmp(cmd_buff, EXIT_CMD) == 0) { + break; + } + + // Check for dragon command + if (strcmp(cmd_buff, "dragon") == 0) { + print_dragon_from_file(); + continue; + } + + // Parse the command line + int rc = build_cmd_list(cmd_buff, &clist); + + if (rc == ERR_TOO_MANY_COMMANDS) { + printf(CMD_ERR_PIPE_LIMIT, CMD_MAX); + continue; + } else if (rc == ERR_CMD_OR_ARGS_TOO_BIG) { + fprintf(stderr, "Error: Command or arguments too big.\n"); + continue; + } + + // Display parsed commands + printf(CMD_OK_HEADER, clist.num); + for (int i = 0; i < clist.num; i++) { + printf("<%d> %s", i + 1, clist.commands[i].exe); + if (strlen(clist.commands[i].args) > 0) { + printf(" [%s]", clist.commands[i].args); + } + printf("\n"); + } + } + + free(cmd_buff); + return OK; +} diff --git a/3-ShellP1/starter/dshlib.c b/3-ShellP1/starter/dshlib.c new file mode 100644 index 0000000000000000000000000000000000000000..2570a180d5a653ce8fa808369618e070e6eccac5 --- /dev/null +++ b/3-ShellP1/starter/dshlib.c @@ -0,0 +1,81 @@ +#include <stdlib.h> +#include <stdio.h> +#include <string.h> +#include <ctype.h> + +#include "dshlib.h" + +/* + * build_cmd_list + * cmd_line: the command line from the user + * clist *: pointer to clist structure to be populated + * + * This function builds the command_list_t structure passed by the caller + * It does this by first splitting the cmd_line into commands by spltting + * the string based on any pipe characters '|'. It then traverses each + * command. For each command (a substring of cmd_line), it then parses + * that command by taking the first token as the executable name, and + * then the remaining tokens as the arguments. + * + * NOTE your implementation should be able to handle properly removing + * leading and trailing spaces! + * + * errors returned: + * + * OK: No Error + * ERR_TOO_MANY_COMMANDS: There is a limit of CMD_MAX (see dshlib.h) + * commands. + * ERR_CMD_OR_ARGS_TOO_BIG: One of the commands provided by the user + * was larger than allowed, either the + * executable name, or the arg string. + * + * Standard Library Functions You Might Want To Consider Using + * memset(), strcmp(), strcpy(), strtok(), strlen(), strchr() + */ +int build_cmd_list(char *cmd_line, command_list_t *clist) +{ + + memset(clist, 0, sizeof(command_list_t)); + + char *token; + int cmd_count = 0; + + // Split the command line into commands + token = strtok(cmd_line, PIPE_STRING); + while (token != NULL) + { + // Trim spaces + while (*token == SPACE_CHAR) + token++; + + char *end = token + strlen(token) - 1; + while (end > token && *end == SPACE_CHAR) + *end-- = '\0'; + + // Ensure the command count does not exceed CMD_MAX + if (cmd_count >= CMD_MAX) + return ERR_TOO_MANY_COMMANDS; + + char *arg_start = strchr(token, SPACE_CHAR); + if (arg_start) + { + *arg_start = '\0'; + arg_start++; // Move to the first argument + } + + // Check size + if (strlen(token) >= EXE_MAX || (arg_start && strlen(arg_start) >= ARG_MAX)) + return ERR_CMD_OR_ARGS_TOO_BIG; + + // Store parsed command + strcpy(clist->commands[cmd_count].exe, token); + if (arg_start) + strcpy(clist->commands[cmd_count].args, arg_start); + + cmd_count++; + token = strtok(NULL, PIPE_STRING); + } + + clist->num = cmd_count; + return OK; +} diff --git a/3-ShellP1/starter/dshlib.h b/3-ShellP1/starter/dshlib.h new file mode 100644 index 0000000000000000000000000000000000000000..1353bbd3ba39a4099cdf58ab8f8827e2d3e4e5aa --- /dev/null +++ b/3-ShellP1/starter/dshlib.h @@ -0,0 +1,50 @@ +#ifndef __DSHLIB_H__ +#define __DSHLIB_H__ + +// Constants for command structure sizes +#define EXE_MAX 64 +#define ARG_MAX 256 +#define CMD_MAX 8 +// Longest command that can be read from the shell +#define SH_CMD_MAX EXE_MAX + ARG_MAX + +typedef struct command +{ + char exe[EXE_MAX]; + char args[ARG_MAX]; +} command_t; + +typedef struct command_list +{ + int num; + command_t commands[CMD_MAX]; +} command_list_t; + +// Special character #defines +#define SPACE_CHAR ' ' +#define PIPE_CHAR '|' +#define PIPE_STRING "|" + +#define SH_PROMPT "dsh> " +#define EXIT_CMD "exit" + +// Standard Return Codes +#define OK 0 +#define WARN_NO_CMDS -1 +#define ERR_TOO_MANY_COMMANDS -2 +#define ERR_CMD_OR_ARGS_TOO_BIG -3 + +// starter code +#define M_NOT_IMPL "The requested operation is not implemented yet!\n" +#define EXIT_NOT_IMPL 3 +#define NOT_IMPLEMENTED_YET 0 + +// prototypes +int build_cmd_list(char *cmd_line, command_list_t *clist); + +// output constants +#define CMD_OK_HEADER "PARSED COMMAND LINE - TOTAL COMMANDS %d\n" +#define CMD_WARN_NO_CMD "warning: no commands provided\n" +#define CMD_ERR_PIPE_LIMIT "error: piping limited to %d commands\n" + +#endif \ No newline at end of file diff --git a/3-ShellP1/starter/makefile b/3-ShellP1/starter/makefile new file mode 100644 index 0000000000000000000000000000000000000000..b79ff3d2e56442aaa5358ff0368419305a939124 --- /dev/null +++ b/3-ShellP1/starter/makefile @@ -0,0 +1,29 @@ +# Compiler settings +CC = gcc +CFLAGS = -Wall -Wextra -g +LDFLAGS = -lz # Link zlib library + +# Target executable name +TARGET = dsh + +# Find all source and header files +SRCS = $(wildcard *.c) +HDRS = $(wildcard *.h) + +# Default target +all: $(TARGET) + +# Compile source to executable +$(TARGET): $(SRCS) $(HDRS) + $(CC) $(CFLAGS) -o $(TARGET) $(SRCS) $(LDFLAGS) + +# Clean up build files +clean: + rm -f $(TARGET) + +# Run tests +test: + ./test.sh + +# Phony targets +.PHONY: all clean test diff --git a/3-ShellP1/starter/test.sh b/3-ShellP1/starter/test.sh new file mode 100755 index 0000000000000000000000000000000000000000..6d586dbabea1cf80d3862450f1c62c8664db13d4 --- /dev/null +++ b/3-ShellP1/starter/test.sh @@ -0,0 +1,212 @@ +#!/usr/bin/env bats + +@test "Simple Command" { + run ./dsh <<EOF +test_command +exit +EOF + + # Strip all whitespace (spaces, tabs, newlines) from the output + stripped_output=$(echo "$output" | tr -d '[:space:]') + + # Expected output with all whitespace removed for easier matching + expected_output="dsh>PARSEDCOMMANDLINE-TOTALCOMMANDS1<1>test_commanddsh>" + + # These echo commands will help with debugging and will only print + #if the test fails + echo "Captured stdout:" + echo "Output: $output" + echo "Exit Status: $status" + + # Check exact match + [ "$stripped_output" = "$expected_output" ] + + # Assertions + [ "$status" -eq 0 ] + +} + +@test "Simple Command with Args" { + run ./dsh <<EOF +cmd -a1 -a2 +exit +EOF + + # Strip all whitespace (spaces, tabs, newlines) from the output + stripped_output=$(echo "$output" | tr -d '[:space:]') + + # Expected output + expected_output="dsh>PARSEDCOMMANDLINE-TOTALCOMMANDS1<1>cmd[-a1-a2]dsh>" + + # These echo commands will help with debugging and will only print + #if the test fails + echo "Captured stdout:" + echo "Output: $output" + echo "Exit Status: $status" + + # Check exact match + [ "$stripped_output" = "$expected_output" ] + + # Assertions + [ "$status" -eq 0 ] + +} + + +@test "No command provided" { + run ./dsh <<EOF + +exit +EOF + + # Strip all whitespace (spaces, tabs, newlines) from the output + stripped_output=$(echo "$output" | tr -d '[:space:]') + + # Expected output with all whitespace removed for easier matching + expected_output="dsh>warning:nocommandsprovideddsh>" + + # These echo commands will help with debugging and will only print + #if the test fails + echo "Captured stdout:" + echo "Output: $output" + echo "Exit Status: $status" + + # Check exact match + [ "$stripped_output" = "$expected_output" ] + + # Assertions + [ "$status" -eq 0 ] + +} + +@test "Two commands" { + run ./dsh <<EOF +command_one | command_two +exit +EOF + + # Strip all whitespace (spaces, tabs, newlines) from the output + stripped_output=$(echo "$output" | tr -d '[:space:]') + + # Expected output with all whitespace removed for easier matching + expected_output="dsh>PARSEDCOMMANDLINE-TOTALCOMMANDS2<1>command_one<2>command_twodsh>" + + # These echo commands will help with debugging and will only print + #if the test fails + echo "Captured stdout:" + echo "Output: $output" + echo "Exit Status: $status" + + # Check exact match + [ "$stripped_output" = "$expected_output" ] + + # Assertions + [ "$status" -eq 0 ] + +} + +@test "three commands with args" { + run ./dsh <<EOF +cmd1 a1 a2 a3 | cmd2 a4 a5 a6 | cmd3 a7 a8 a9 +exit +EOF + + # Strip all whitespace (spaces, tabs, newlines) from the output + stripped_output=$(echo "$output" | tr -d '[:space:]') + + # Expected output with all whitespace removed for easier matching + expected_output="dsh>PARSEDCOMMANDLINE-TOTALCOMMANDS3<1>cmd1[a1a2a3]<2>cmd2[a4a5a6]<3>cmd3[a7a8a9]dsh>" + + # These echo commands will help with debugging and will only print + #if the test fails + echo "Captured stdout:" + echo "Output: $output" + echo "Exit Status: $status" + + # Check exact match + [ "$stripped_output" = "$expected_output" ] + + # Assertions + [ "$status" -eq 0 ] + +} + +@test "try max (8) commands" { + run ./dsh <<EOF +cmd1 | cmd2 | cmd3 | cmd4 | cmd5 | cmd6 | cmd7 | cmd8 +exit +EOF + + # Strip all whitespace (spaces, tabs, newlines) from the output + stripped_output=$(echo "$output" | tr -d '[:space:]') + + # Expected output with all whitespace removed for easier matching + expected_output="dsh>PARSEDCOMMANDLINE-TOTALCOMMANDS8<1>cmd1<2>cmd2<3>cmd3<4>cmd4<5>cmd5<6>cmd6<7>cmd7<8>cmd8dsh>" + + # These echo commands will help with debugging and will only print + #if the test fails + echo "Captured stdout:" + echo "Output: $output" + echo "Exit Status: $status" + + # Check exact match + [ "$stripped_output" = "$expected_output" ] + + # Assertions + [ "$status" -eq 0 ] + +} + +@test "try too many commands" { + run ./dsh <<EOF +cmd1 | cmd2 | cmd3 | cmd4 | cmd5 | cmd6 | cmd7 | cmd8 | cmd9 +exit +EOF + + # Strip all whitespace (spaces, tabs, newlines) from the output + stripped_output=$(echo "$output" | tr -d '[:space:]') + + # Expected output with all whitespace removed for easier matching + expected_output="dsh>error:pipinglimitedto8commandsdsh>" + + # These echo commands will help with debugging and will only print + #if the test fails + echo "Captured stdout:" + echo "Output: $output" + echo "Exit Status: $status" + + # Check exact match + [ "$stripped_output" = "$expected_output" ] + + # Assertions + [ "$status" -eq 0 ] + +} + +@test "kitchen sink - multiple commands" { + run ./dsh <<EOF +cmd1 +cmd2 arg arg2 +p1 | p2 +p3 p3a1 p3a2 | p4 p4a1 p4a2 +EOF + + # Strip all whitespace (spaces, tabs, newlines) from the output + stripped_output=$(echo "$output" | tr -d '[:space:]') + + # Expected output with all whitespace removed for easier matching + expected_output="dsh>PARSEDCOMMANDLINE-TOTALCOMMANDS1<1>cmd1dsh>PARSEDCOMMANDLINE-TOTALCOMMANDS1<1>cmd2[argarg2]dsh>PARSEDCOMMANDLINE-TOTALCOMMANDS2<1>p1<2>p2dsh>PARSEDCOMMANDLINE-TOTALCOMMANDS2<1>p3[p3a1p3a2]<2>p4[p4a1p4a2]dsh>" + + # These echo commands will help with debugging and will only print + #if the test fails + echo "Captured stdout:" + echo "Output: $output" + echo "Exit Status: $status" + + # Check exact match + [ "$stripped_output" = "$expected_output" ] + + # Assertions + [ "$status" -eq 0 ] + +} \ No newline at end of file