├── .gitignore ├── LICENSE ├── README.md ├── makefile └── src ├── chad-history.c ├── chad-history.h ├── chad-readline.c ├── chad-readline.h ├── chell.c ├── chell.h ├── commands.c ├── commands.h └── defs.h /.gitignore: -------------------------------------------------------------------------------- 1 | chell 2 | 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Chell 2 | #### The chad shell. 3 | 4 | #### Why? 5 | 6 | I want to practice C and Vim. That's literally it. That's kinda the whole purpose of the project. I am using Vim as my main text editor and wanted to try it out in an actual small project. 7 | 8 | #### Should I use it? 9 | 10 | I don't think so. But go ahead if you want. 11 | 12 | #### How is it chad? 13 | 14 | It's not. 15 | 16 | #### Running Chell 17 | 18 | Just run ```gcc -Wall -o chell src/*.c``` and then ```./chell``` or ```make run``` from any existing shell and you will get the chell "bash-like" prompt. 19 | 20 | #### Demo 21 | 22 | ![Demo](https://media.giphy.com/media/dCWrvGnZh2R7GVvMEd/giphy.gif) 23 | -------------------------------------------------------------------------------- /makefile: -------------------------------------------------------------------------------- 1 | CFLAGS = -Wall -fsanitize=address -fno-omit-frame-pointer 2 | LDFLAGS = 3 | PROG = chell 4 | CXX = gcc 5 | 6 | FILES = chell.c chad-readline.c chad-history.c commands.c 7 | SOURCE_FILES = $(foreach file, $(FILES), src/$(file)) 8 | 9 | HFILES = defs.h chad-history.h chad-readline.h chell.h commands.h 10 | HEADER_FILES = $(foreach file, $(HFILES), src/$(file)) 11 | 12 | 13 | # top-level rule to create the program. 14 | all: $(PROG) 15 | 16 | # compile chell 17 | $(PROG): $(SOURCE_FILES) $(HEADER_FILES) 18 | $(CXX) $(CFLAGS) $(SOURCE_FILES) -o $(PROG) $(LDFLAGS) 19 | 20 | # cleaning everything that can be automatically recreated with "make" 21 | clean: 22 | rm $(PROG) 23 | 24 | run: 25 | @echo ----- building $(PROG) ----- 26 | @make all 27 | @echo ----- running $(PROG) ----- 28 | @./$(PROG) 29 | -------------------------------------------------------------------------------- /src/chad-history.c: -------------------------------------------------------------------------------- 1 | #include "chad-history.h" 2 | #include "chell.h" 3 | 4 | 5 | char *history_file = (char *)NULL; 6 | int history_file_length; 7 | 8 | struct history_handler historyHandler = {NULL, NULL, NULL}; 9 | 10 | struct history_manager 11 | { 12 | char **history_list; 13 | int history_index; 14 | unsigned int history_size; 15 | char *current_buffer; 16 | }; 17 | 18 | struct history_manager history; 19 | 20 | void constructHistoryFilePath() 21 | { 22 | history_file_length = strlen(getenv("HOME")) + strlen(HISTORY_FILE) + 1; 23 | history_file = (char *) malloc(sizeof(char)*history_file_length); 24 | 25 | snprintf(history_file, history_file_length, "%s%s", getenv("HOME"), HISTORY_FILE); 26 | printf("%s\n", history_file); 27 | } 28 | 29 | void initHistory() 30 | { 31 | constructHistoryFilePath(); 32 | 33 | history.history_list = calloc(HISTORY_SIZE, sizeof(char *)); 34 | history.history_index = 0; 35 | history.history_size = 0; 36 | history.current_buffer = (char *) malloc(sizeof(char)*ARG_MAX); 37 | strcpy(history.current_buffer, ""); 38 | loadHistory(); 39 | 40 | historyHandler.getNext = *getNext; 41 | historyHandler.getPrev = *getPrev; 42 | historyHandler.add = *addHistory; 43 | } 44 | 45 | char *getNext(char *command) 46 | { 47 | if (history.history_index < history.history_size) 48 | history.history_index++; 49 | 50 | return (history.history_index == history.history_size) ? history.current_buffer : history.history_list[history.history_index]; 51 | } 52 | 53 | char *getPrev(char *command) 54 | { 55 | if(history.history_index == history.history_size) strcpy(history.current_buffer, command); 56 | if (history.history_index > 0) 57 | history.history_index--; 58 | 59 | 60 | return (history.history_index == history.history_size) ? history.current_buffer : history.history_list[history.history_index]; 61 | } 62 | 63 | void addHistory(char *command) 64 | { 65 | history.history_size %= HISTORY_SIZE; 66 | 67 | // Not saving if successively repeated command 68 | if(!(history.history_size != 0 && strcmp(history.history_list[(history.history_size - 1)%HISTORY_SIZE], command) == 0)) { 69 | if (history.history_list[history.history_size] == NULL) 70 | history.history_list[history.history_size] = (char *) malloc(sizeof(char)*ARG_MAX); 71 | strcpy(history.history_list[history.history_size], command); 72 | history.history_size++; 73 | } 74 | 75 | history.history_index = history.history_size; 76 | strcpy(history.current_buffer, ""); 77 | } 78 | 79 | void loadHistory() 80 | { 81 | FILE *file; 82 | 83 | file = fopen(history_file, "r"); 84 | if(file != NULL) 85 | { 86 | while(1) 87 | { 88 | history.history_index = history.history_size; 89 | history.history_list[history.history_index] = (char *) malloc(sizeof(char)*ARG_MAX); 90 | 91 | if (fgets(history.history_list[history.history_index], ARG_MAX, file)) 92 | { 93 | //Remove the '\n' character from the string 94 | history.history_list[history.history_index][strlen(history.history_list[history.history_index])-1] = '\0'; 95 | 96 | history.history_size++; 97 | } 98 | else break; 99 | } 100 | fclose(file); 101 | } 102 | } 103 | 104 | void saveHistory() 105 | { 106 | FILE *file; 107 | file = fopen(history_file, "w"); 108 | if(file != NULL) 109 | { 110 | for (int i = history.history_size; i < HISTORY_SIZE; i++) 111 | { 112 | if (history.history_list[i] != NULL) 113 | fprintf(file, "%s\n", history.history_list[i]); 114 | 115 | } 116 | for (int i = 0; i < history.history_size; i++) 117 | { 118 | if (history.history_list[i] != NULL) 119 | fprintf(file, "%s\n", history.history_list[i]); 120 | } 121 | fclose(file); 122 | } 123 | } 124 | 125 | void freeHistory() 126 | { 127 | for (int i = 0; i < history.history_size; i++) 128 | free(history.history_list[i]); 129 | 130 | free(history.history_list); 131 | free(history.current_buffer); 132 | free(history_file); 133 | } 134 | 135 | char isNumeric(char *str) 136 | { 137 | int len = strlen(str); 138 | for (int i = 0; i < len; i++) 139 | { 140 | if (str[i] < '0' || str[i] > '9') 141 | return 0; 142 | } 143 | return 1; 144 | } 145 | 146 | void historyCommand(char *arg) 147 | { 148 | if (arg == NULL) 149 | { 150 | printf("History Size: %d\n", history.history_size); 151 | 152 | for (int i = 0; i < history.history_size; i++) 153 | printf("%d:\t%s\n", i+1, history.history_list[i]); 154 | return; 155 | } 156 | else 157 | { 158 | if (strncmp(arg, "clear", 5) == 0) 159 | { 160 | FILE *file; 161 | file = fopen(history_file, "w"); 162 | if(file != NULL) 163 | fclose(file); 164 | 165 | freeHistory(); 166 | initHistory(); 167 | printf("%s\n", "History cleared."); 168 | *arg = '\0'; 169 | return; 170 | } 171 | 172 | if (isNumeric(arg)) 173 | { 174 | int index = atoi(arg); 175 | if (index > 0 && index < HISTORY_SIZE) 176 | strcpy(arg, history.history_list[index-1]); 177 | } 178 | else //The parameter isn't numeric 179 | *arg = '\0'; 180 | } 181 | 182 | 183 | 184 | } 185 | -------------------------------------------------------------------------------- /src/chad-history.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #include "defs.h" 8 | 9 | #ifndef CHAD_HISTORY 10 | #define CHAD_HISTORY 11 | 12 | struct history_handler 13 | { 14 | char *(*getNext)(); 15 | char *(*getPrev)(); 16 | void (*add)(char *); 17 | }; 18 | 19 | void constructHistoryFilePath(); 20 | void initHistory(void); 21 | void loadHistory(void); 22 | void saveHistory(void); 23 | void freeHistory(); 24 | 25 | char *getNext(char *command); 26 | char *getPrev(char *command); 27 | void addHistory(char *command); 28 | 29 | char isNumeric(char *str); 30 | 31 | void historyCommand(char *arg); 32 | 33 | extern struct history_handler historyHandler; 34 | #endif 35 | -------------------------------------------------------------------------------- /src/chad-readline.c: -------------------------------------------------------------------------------- 1 | #include "chad-readline.h" 2 | 3 | char isWhiteSpaces(char *str) 4 | { 5 | int strLen = strlen(str); 6 | for (int i = 0; i < strLen; i++) 7 | { 8 | if (str[i] != ' ' && str[i] != '\t') 9 | return 0; 10 | } 11 | return 1; 12 | } 13 | 14 | /* Function to detect arrow key pressed in incoming stream 15 | Returns: 2 if finished checked, 1 if still checking, 0 if initially checked, -1 if there are no special characters 16 | arrow codes: 17 | 0 -> up arrow 18 | 1 -> down arrow 19 | 2 -> right arrow 20 | 3 -> left arrow 21 | */ 22 | char escape_detected(char input, unsigned char *escapeCharacter) 23 | { 24 | //Arrows are ANSI escapes that produce the sequence 27(ESC), 91([), (A|B|C|D) 25 | //Where number is the value of the arrow itself. 26 | static unsigned char characterBeingChecked; 27 | 28 | if ((input == 27 && characterBeingChecked == 0) || (input == 91 && characterBeingChecked == 1)) 29 | { 30 | return characterBeingChecked++; 31 | } 32 | else if (characterBeingChecked == 2) //Special key (ANSI ESC) 33 | { 34 | //Arrow keys are ESC[(A|B|C|D), End and Home are ESC[(F|H) 35 | if (('A' <= input && input <= 'D') || (input == 'F') || (input == 'H')) 36 | { 37 | *escapeCharacter = input - 'A'; 38 | } 39 | //Del, Ins, etc.. are ESC[X~ where X is an int 40 | else if (getch() == '~') 41 | { 42 | *escapeCharacter = input; 43 | } 44 | else 45 | *escapeCharacter = 0xFF; //Not an arrow or a navigation key for now, could add more options later. 46 | characterBeingChecked = 0; 47 | return 2; 48 | } 49 | else 50 | { 51 | characterBeingChecked = 0; 52 | } 53 | return -1; 54 | } 55 | 56 | char handle_special(char input, char *line, int* cursor, int *currentLength) 57 | { 58 | if (input == 127) //Backspace 59 | { 60 | if (*cursor > 0) 61 | { 62 | if ((*cursor) == (*currentLength)-1) 63 | { 64 | line[--*cursor] = '\0'; 65 | (*currentLength)--; 66 | printf("%s", "\b \b"); 67 | } 68 | else //not at the end 69 | { 70 | //Shift all to the left 71 | for (int i = *cursor; i < *currentLength; i++) 72 | line[i-1] = line[i]; 73 | 74 | //decrement the length 75 | (*currentLength)--; 76 | 77 | //calculate the number of movements needed forward 78 | int forward = *currentLength - *cursor; 79 | //move to the right 80 | for (int i = 0; i < forward; i++) 81 | { 82 | printf("%c%c%c", 27, 91, RIGHT_ARROW + 'A'); 83 | } 84 | //go back and delete on the way 85 | for (int i = 0; i < *currentLength; i++) 86 | { 87 | printf("%s", "\b \b"); 88 | } 89 | 90 | //move the cursor back 91 | (*cursor)--; 92 | 93 | //print the new line 94 | printf("%.*s", (*currentLength)-1, line); 95 | 96 | //Go back to the original cursor position 97 | for (int i = 0; i < forward; i++) 98 | printf("%c%c%c", 27, 91, LEFT_ARROW + 'A'); 99 | } 100 | } 101 | } 102 | else if (input == '\t') 103 | { 104 | //code for autocomplete 105 | } 106 | else return 0; 107 | 108 | return 1; 109 | } 110 | 111 | int cursor = 0; //Where the cursor is respective to line. 112 | int currentLength = 1; 113 | char *line; 114 | void clearBuffer() 115 | { 116 | cursor = 0; 117 | currentLength = 1; 118 | strcpy(line, ""); 119 | } 120 | 121 | char *readline(char *prompt) 122 | { 123 | printf("%s", prompt); 124 | line = (char*) calloc(ARG_MAX, sizeof(char)); //Current input 125 | 126 | cursor = 0; 127 | currentLength = 1; 128 | 129 | char input; 130 | unsigned char escapeCharacter; 131 | 132 | while((input = getch())) 133 | { 134 | char status = escape_detected(input, &escapeCharacter); 135 | if (status == 0 || status == 1) continue; 136 | else if(status == 2) //Finished checking 137 | { 138 | if (escapeCharacter == LEFT_ARROW) //Move Left 139 | { 140 | if (cursor > 0) 141 | { 142 | cursor--; 143 | printf("%c%c%c", 27, 91, LEFT_ARROW + 'A'); 144 | } 145 | 146 | } 147 | else if (escapeCharacter == RIGHT_ARROW) //Move right 148 | { 149 | if (cursor < currentLength-1) 150 | { 151 | printf("%c%c%c", 27, 91, RIGHT_ARROW + 'A'); 152 | cursor++; 153 | } 154 | } 155 | else if (escapeCharacter == UP_ARROW) //History up 156 | { 157 | char *cmd = historyHandler.getPrev(line); 158 | if(cmd != NULL) 159 | replaceCommandDisplay(prompt, cmd, line); 160 | } 161 | else if (escapeCharacter == DOWN_ARROW) //History down 162 | { 163 | char *cmd = historyHandler.getNext(line); 164 | if(cmd != NULL) 165 | replaceCommandDisplay(prompt, cmd, line); 166 | } 167 | else if (escapeCharacter == DELETE) 168 | { 169 | 170 | } 171 | else if (escapeCharacter == HOME) 172 | { 173 | //Go to the start 174 | } 175 | else if (escapeCharacter == END) 176 | { 177 | //Go to the end 178 | } 179 | else if (escapeCharacter == INSERT) 180 | { 181 | //TODO: Maybe later, implement INSERT mode 182 | } 183 | } 184 | else 185 | { 186 | if (input == 0xA) //Enter 187 | { 188 | line[currentLength-1] = '\0'; 189 | printf("\n"); 190 | 191 | //Do not add empty commands to history 192 | if (strlen(line) != 0 && !isWhiteSpaces(line)) 193 | historyHandler.add(line); 194 | 195 | char *returnValue = strdup(line); 196 | clearBuffer(); 197 | free(line); 198 | return returnValue; 199 | } 200 | else if(!handle_special(input, line, &cursor, ¤tLength)) 201 | { 202 | if (cursor < ARG_MAX) 203 | { 204 | if (cursor == currentLength-1) 205 | { 206 | line[cursor] = input; 207 | putchar(input); 208 | currentLength++; 209 | cursor++; 210 | } 211 | else 212 | { 213 | //Save the location of the cursor 214 | printf("%c%c%c", 27, 91, 's'); 215 | //Shift all of the characters after the cursor to the right. 216 | for (int i = currentLength; i > cursor; i--) 217 | line[i] = line[i-1]; 218 | 219 | //Increment the length for the newly added character. 220 | currentLength++; 221 | 222 | //Place the new character. 223 | line[cursor] = input; 224 | 225 | //print the rest of the new characters 226 | for (int i = cursor; i < currentLength; i++) 227 | putchar(line[i]); 228 | 229 | //Load the location of the cursor 230 | printf("%c%c%c", 27, 91, 'u'); 231 | 232 | //Emulate a right key press 233 | printf("%c%c%c", 27, 91, RIGHT_ARROW + 'A'); 234 | cursor++; 235 | } 236 | } 237 | } 238 | } 239 | } 240 | return NULL; 241 | } 242 | 243 | void replaceCommandDisplay(char *prompt, char *command, char *line) 244 | { 245 | // Clear the current line 246 | int len = strlen(prompt) + strlen(line); 247 | while(len) 248 | { 249 | printf("\b \b"); 250 | len--; 251 | } 252 | 253 | // Print new prompt + command 254 | printf("%s%s", prompt, command); 255 | 256 | // Set the current line to the command 257 | currentLength = strlen(command) + 1; 258 | strcpy(line, command); 259 | cursor = strlen(line); 260 | } 261 | 262 | static struct termios old, newi; 263 | /* 264 | The following is a small implementation for getch() taken from 265 | https://www.includehelp.com/c-programs/gotoxy-clrscr-getch-getche-for-gcc-linux.aspx 266 | */ 267 | void initTermios(int echo) 268 | { 269 | tcgetattr(0, &old); // grab old terminal i/o settings 270 | newi = old; // make new settings same as old settings 271 | newi.c_lflag &= ~ICANON; // disable buffered i/o 272 | 273 | if (echo) 274 | newi.c_lflag |= ECHO; // set echo mode 275 | else 276 | newi.c_lflag &= ~ECHO; // set no echo mode 277 | 278 | tcsetattr(0, TCSANOW, &newi); // use these new terminal i/o settings now 279 | } 280 | 281 | char _getch(int echo) 282 | { 283 | char ch; 284 | initTermios(echo); 285 | ch = getchar(); 286 | //Restore old terminal i/o settings 287 | tcsetattr(0, TCSANOW, &old); 288 | return ch; 289 | } 290 | 291 | char getch(void) 292 | { 293 | return _getch(0); 294 | } 295 | 296 | char getche(void) 297 | { 298 | return _getch(1); 299 | } 300 | 301 | -------------------------------------------------------------------------------- /src/chad-readline.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include "defs.h" 7 | #include "chad-history.h" 8 | 9 | char isWhiteSpaces(char *str); 10 | 11 | /* Function to detect arrow key pressed in incoming stream 12 | Returns: 2 if finished checked, 1 if still checking, 0 if initially checked, -1 if there are no special characters 13 | arrow codes: 14 | 0 -> up arrow 15 | 1 -> down arrow 16 | 2 -> right arrow 17 | 3 -> left arrow 18 | */ 19 | char escape_detected(char input, unsigned char *escapeCharacter); 20 | 21 | //Returns 1 if handled a key, returns 0 otherwise. 22 | char handle_special(char input, char *line, int* cursor, int *currentLength); 23 | 24 | void clearBuffer(); 25 | 26 | char *readline(char *prompt); 27 | 28 | // Initialize new terminal i/o settings 29 | void initTermios(int echo); 30 | 31 | // Read 1 character - echo defines echo mode 32 | char _getch(int echo); 33 | 34 | // Read 1 character without echo 35 | char getch(void); 36 | 37 | // Read 1 character with echo 38 | char getche(void); 39 | 40 | void replaceCommandDisplay(char *prompt, char *command, char *line); 41 | -------------------------------------------------------------------------------- /src/chell.c: -------------------------------------------------------------------------------- 1 | #include "chell.h" 2 | #include "commands.h" 3 | 4 | static int nExecutables = 0; 5 | 6 | int main() 7 | { 8 | signal(SIGINT, sigintHandler); 9 | int numberOfDirs = getPATHLocationCount(getenv("PATH")); 10 | char *PATHdirs[numberOfDirs]; 11 | 12 | for (int i = 0; i < numberOfDirs; i++) 13 | PATHdirs[i] = (char*) malloc(sizeof(char *)*PATH_MAX); 14 | 15 | getPATHLocations(PATHdirs, getenv("PATH")); 16 | struct executable *executables = getFilesFromDirectories(PATHdirs, numberOfDirs); 17 | 18 | // Initialize command history handling functions 19 | initHistory(); 20 | 21 | char *command; 22 | char status = 0; 23 | while (status == 0) 24 | { 25 | initPrompt(); 26 | //Command input 27 | command = readline(""); 28 | 29 | //If not an empty command 30 | if (command && strlen(command) != 0 && !isWhiteSpaces(command)) 31 | status = executeCommand(command, executables); 32 | } 33 | 34 | free(command); 35 | 36 | for (int i = 0; i < numberOfDirs; i++) 37 | free(PATHdirs[i]); 38 | 39 | free(executables); 40 | } 41 | 42 | int getPATHLocationCount(char *PATH) 43 | { 44 | int j = 0; 45 | int pathLen = strlen(PATH); 46 | for (int i = 0; i < pathLen; i++) 47 | { 48 | if (PATH[i] == ':') j++; 49 | } 50 | return j+1; 51 | } 52 | 53 | void getPATHLocations(char *directories[], char *PATH) 54 | { 55 | splitString(directories, PATH, ":"); 56 | } 57 | 58 | struct executable *getFilesFromDirectories(char **dir, int numberOfDirectory) 59 | { 60 | struct executable *executables = malloc(numberOfDirectory*8192*sizeof(struct executable)); 61 | 62 | int j = 0; 63 | for(int i = 0; i < numberOfDirectory; i++) 64 | { 65 | DIR *dirPointer; 66 | struct dirent *ep; 67 | dirPointer = opendir(dir[i]); 68 | 69 | if (dirPointer != NULL) 70 | { 71 | while ((ep = readdir(dirPointer))) 72 | { 73 | if (!strncmp(ep->d_name, ".", 1) || !strncmp(ep->d_name, "..", 1)) 74 | continue; 75 | 76 | strncpy(executables[j].name, ep->d_name, strlen(ep->d_name)); 77 | strncpy(executables[j].path, dir[i], strlen(dir[i])); 78 | j++; 79 | } 80 | (void) closedir (dirPointer); 81 | } 82 | } 83 | nExecutables = j; 84 | 85 | return executables; 86 | } 87 | 88 | void initPrompt() 89 | { 90 | //Get environment variables for the prompt 91 | char *home = getenv("HOME"); 92 | char *user = getenv("USER"); 93 | char *pwd = getenv("PWD"); 94 | 95 | //If any of them are undefined 96 | if (pwd == NULL) strncpy(pwd, "", 1); 97 | if (home == NULL) 98 | { 99 | if (user == NULL) 100 | strncpy(home, "", 1); 101 | else 102 | { 103 | snprintf(home, strlen(user) + 6, "/home/%s", user); 104 | setenv("HOME", home, 1); 105 | } 106 | } 107 | if (user == NULL) snprintf(user, 16, "%s-v%.2f", SHELL_NAME, VERSION); 108 | 109 | //If the current working dir is home 110 | if (strncmp(pwd, home, max(strlen(pwd), strlen(home))) == 0) 111 | strncpy(pwd, "~", strlen(pwd)); 112 | 113 | //If the current working dir has /home/USER in it 114 | if (strstr(pwd, home) != NULL) 115 | { 116 | //Skip /home/user 117 | char *actualpath = strstr(pwd+strlen(user), "/"); 118 | snprintf(pwd, strlen(actualpath) + 3, "~%s", actualpath); 119 | } 120 | 121 | char prompt; 122 | if (getuid() == 0) 123 | prompt = '#'; 124 | else 125 | prompt = '$'; 126 | 127 | printf("%s:%s%c ", user, pwd, prompt); 128 | } 129 | 130 | int splitString(char *split[], char *string, char *delim) 131 | { 132 | char *stringDup = strdup(string); 133 | char *arg = strtok(stringDup, delim); 134 | 135 | int argc = 0; 136 | while (arg != NULL) 137 | { 138 | strncpy(split[argc], arg, PATH_MAX); 139 | argc++; 140 | arg = strtok(NULL, delim); 141 | } 142 | free(stringDup); 143 | return argc; 144 | } 145 | 146 | int splitCommand(char *argv[], char *command) 147 | { 148 | return splitString(argv, command, "\t "); 149 | } 150 | 151 | char executeCommand(char *commandString, struct executable *executables) 152 | { 153 | if (strlen(commandString) == 0 || commandString == NULL) 154 | return 0; 155 | 156 | if (strncmp(commandString, "exit", strlen(commandString)) == 0 || 157 | (strncmp(commandString, "quit", strlen(commandString)) == 0 && strlen(commandString) == 4)|| 158 | (strncmp(commandString, "q", strlen(commandString)) == 0 && strlen(commandString) == 1)) 159 | { 160 | saveHistory(); 161 | freeHistory(); 162 | return 1; 163 | } 164 | 165 | pid_t processID; 166 | char *argv[PATH_MAX]; 167 | struct command* builtin; 168 | 169 | //Allocate the argv array 170 | for (int i = 0; i < PATH_MAX; i++) 171 | argv[i] = malloc(sizeof(char)*PATH_MAX); 172 | 173 | //Split the command and get the number of arguments 174 | int argc = splitCommand(argv, commandString); 175 | 176 | //Set the bounds for the last argument 177 | free(argv[argc]); 178 | argv[argc] = NULL; 179 | 180 | //Get the actual command path 181 | char *commandPath = malloc(PATH_MAX*sizeof(char)); 182 | char programExists = 0; 183 | 184 | // Check if it's a relative / full path first 185 | if (realpath(argv[0], commandPath) != NULL && strstr(argv[0], "/") != NULL) 186 | { 187 | programExists = 1; 188 | } 189 | else 190 | { 191 | for (int i = 0; i < nExecutables; i++) 192 | { 193 | if (strncmp(argv[0], executables[i].name, max(strlen(executables[i].name), strlen(argv[0]))) == 0) 194 | { 195 | snprintf(commandPath, NAME_MAX + PATH_MAX + 2,"%s/%s", executables[i].path, executables[i].name); 196 | programExists = 1; 197 | break; 198 | } 199 | } 200 | } 201 | 202 | // check if the executed command is built into Chell 203 | if ((builtin = is_builtin(argv[0]))) 204 | { 205 | if (argv[1] != NULL && (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0)) 206 | printf("\t%s - %s\n", builtin->name, builtin->help); 207 | else 208 | { 209 | builtin->func(argv[1]); 210 | 211 | if (builtin->returnsValue) 212 | { 213 | if (strcmp(argv[0], "history") == 0 && argv[1] != NULL) 214 | { 215 | executeCommand(argv[1], executables); 216 | } 217 | } 218 | } 219 | } 220 | else if (programExists) 221 | { 222 | processID = fork(); 223 | if (processID == 0) 224 | { 225 | //Create a new process for the command 226 | execv(commandPath, argv); 227 | exit(0); 228 | } 229 | else 230 | waitpid(processID, 0, 0); 231 | } 232 | else if (!programExists) 233 | { 234 | printf("%s: Command not found.\n", argv[0]); 235 | } 236 | 237 | //Free the argv array 238 | for (int i = 0; i < PATH_MAX; i++) 239 | free(argv[i]); 240 | 241 | free (commandPath); 242 | free (commandString); 243 | return 0; 244 | 245 | } 246 | 247 | void sigintHandler(int signal_number) 248 | { 249 | signal(SIGINT, sigintHandler); 250 | printf("\n"); 251 | initPrompt(); 252 | clearBuffer(); 253 | fflush(stdout); 254 | } 255 | 256 | 257 | -------------------------------------------------------------------------------- /src/chell.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #include "defs.h" 9 | #include "chad-readline.h" 10 | #include "chad-history.h" 11 | 12 | struct executable 13 | { 14 | char name[NAME_MAX + 1]; 15 | char path[PATH_MAX + 1]; 16 | }; 17 | 18 | int getPATHLocationCount(char *PATH); 19 | void getPATHLocations(char *directories[], char *PATH); 20 | 21 | struct executable *getFilesFromDirectories(char **dir, int numberOfDirectory); 22 | 23 | 24 | void initPrompt(); 25 | 26 | int splitString(char *split[], char *string, char *delim); 27 | int splitCommand(char *argv[], char *command); 28 | 29 | char executeCommand(char *commandString, struct executable *executables); 30 | 31 | void sigintHandler(int signal_number); 32 | 33 | 34 | -------------------------------------------------------------------------------- /src/commands.c: -------------------------------------------------------------------------------- 1 | #include "commands.h" 2 | #include "chad-history.h" 3 | 4 | struct command commands[] = { 5 | { "cd", cd, "change directory\n\tUsage: cd [path]\n\n\t\tChanges the working directory to the specified path.\n", 0}, 6 | { "history", historyCommand, "manage the history\n\n\tUsage: history [arg]\n\t\tPrints or clears the history. It can also execute a previous command.\n\t\targ can be:\n\t\t\tclear - clear the history entirely.\n\t\t\tn - execute command number \"n\" from the history.", 1}, 7 | { NULL, NULL, NULL, 0} 8 | }; 9 | 10 | struct command *is_builtin(char *name) 11 | { 12 | for (int i = 0; commands[i].name; ++i) 13 | { 14 | if (strcmp(name, commands[i].name) == 0) 15 | return &commands[i]; 16 | } 17 | 18 | return NULL; 19 | } 20 | 21 | void cd(char *path) 22 | { 23 | if (path == NULL) 24 | { 25 | path = getenv("HOME"); 26 | } 27 | 28 | int status = chdir(path); 29 | 30 | if (status == 0) 31 | setenv("PWD", getcwd(NULL, 0), 1); 32 | else if (status == -1) 33 | { 34 | if (errno == EACCES) 35 | printf("%s: Permission denied.\n", path); 36 | else if (errno == ENOENT) 37 | printf("%s: Doesn't exist.\n", path); 38 | else if (errno == ENOTDIR) 39 | printf("%s: Not a directory.\n", path); 40 | } 41 | } 42 | 43 | -------------------------------------------------------------------------------- /src/commands.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | struct command { 9 | char *name; 10 | void (*func)(char*); 11 | char *help; 12 | char returnsValue; 13 | }; 14 | 15 | struct command *is_builtin(char *name); 16 | void cd(char *path); 17 | 18 | extern struct command commands[]; 19 | -------------------------------------------------------------------------------- /src/defs.h: -------------------------------------------------------------------------------- 1 | #ifndef DEFS 2 | #define DEFS 3 | 4 | #define VERSION 0.07 5 | #define SHELL_NAME "Chell" 6 | #define HISTORY_SIZE 1024 7 | #define HISTORY_FILE "/.chell_history" 8 | 9 | #ifndef ARG_MAX // it's already defined in sys/syslimits.h on macos 10 | #define ARG_MAX sysconf(_SC_ARG_MAX) 11 | #endif 12 | 13 | #define max(a,b) \ 14 | ({ __typeof__ (a) _a = (a); \ 15 | __typeof__ (b) _b = (b); \ 16 | _a > _b ? _a : _b; }) 17 | 18 | #define UP_ARROW 0 19 | #define DOWN_ARROW 1 20 | #define RIGHT_ARROW 2 21 | #define LEFT_ARROW 3 22 | #define HOME 7 23 | #define END 5 24 | #define INSERT 0x32 //The character '2' in [2~ 25 | #define DELETE 0x33 //The character '3' in [3~ 26 | 27 | #endif 28 | --------------------------------------------------------------------------------