#include "exec.h" #include "comment.h" #include "env.h" #include "../lib/sys/io.h" #include "../lib/cstr/cstr.h" #include "../lib/sys/dup2.h" #include "../lib/sys/exit.h" #include "../lib/malloc/malloc.h" #include "../lib/io/io.h" #include "../lib/sys/errno.h" #define BUFSIZ 16384 char buf[BUFSIZ] = {0}; int io_getline(int fd, char *linebuf) { u64 size = 0; char *line = buf; while (*line && *line != '\n') line++; if (!*line) { u64 s = cstr_length(buf); s = read(fd, buf + s, BUFSIZ - s - 1); if (s == 0) { return -1; } buf[s] = 0; while (*line && *line != '\n') line++; if (!*line) { wf(STDERR_FD, "line too long to handle, exiting.\n"); exit(-1); } } *line = 0; ++line; size = cstr_length(buf); for (int i = 0; buf[i]; ++i) linebuf[i] = buf[i]; linebuf[size] = 0; buf[0] = 0; for (int i = 0; *line; ++i) { buf[i] = *line; buf[i + 1] = 0; ++line; } return size; } int main(int argc, char *argv[]) { char prompt[] = "$ "; i64 line_length; int fd = STDIN_FD; char linebuf[BUFSIZ]; char *line; init_arg_env(argc, (const char**)argv); if (argc > 1) { fd = open(argv[1], OPEN_READ_ONLY, 0); if (fd < 0) { wff(STDERR_FD, "smash: %s\n", errstr[-fd]); return -1; } } while (1) { if (fd == STDIN_FD) wstd(prompt); line_length = io_getline(fd, linebuf); if (line_length == -1) { break; } remove_comment(linebuf); line = new_line_and_replace_vars(linebuf, BUFSIZ); line_length = cstr_length(line); if (line_length > 0) { exec(line); } free(line); } if (fd != STDOUT_FD) close(fd); }