feat(shell): import readline, and add simple history

This commit is contained in:
iridiumR 2022-09-20 21:04:55 +08:00
parent 5c8ed315f7
commit 87eb989d79
No known key found for this signature in database
GPG Key ID: 5574BE4450D55618
3 changed files with 19 additions and 48 deletions

View File

@ -1,6 +1,7 @@
SHELL := /bin/bash
CC = gcc
SRC = main.c loop.c exec.c line.c builtin.c
LINK= -lreadline
OBJ = $(SRC:.c=.ro)
DBGOBJ = $(SRC:.c=.do)
EXE = dish
@ -11,10 +12,10 @@ debug: CFLAGS = -g -O0 -DDEBUG
release: CFLAGS = -Wall -O3
release: $(OBJ)
$(CC) $(CFLAGS) -o $(EXE) $(OBJ)
$(CC) $(CFLAGS) -o $(EXE) $(OBJ) $(LINK)
debug: $(DBGOBJ)
$(CC) $(CFLAGS) -o $(DBGEXE) $(DBGOBJ)
$(CC) $(CFLAGS) -o $(DBGEXE) $(DBGOBJ) $(LINK)
clean:
rm -f *.o *.do *.ro
@ -24,7 +25,7 @@ $(OBJ):$(SRC)
rename .o .ro *.o
$(DBGOBJ):$(SRC)
$(CC) $(CFLAGS) -c $(SRC)
$(CC) $(CFLAGS) -c $(SRC)
rename .o .do *.o
c:clean

48
line.c
View File

@ -1,48 +1,16 @@
/*
* @Author: 1ridic
* @Date: 2022-09-18 14:14:05
* @Last Modified by: 1ridic
* @Last Modified time: 2022-09-18 14:14:05
* @Author: 1ridic
* @Date: 2022-09-18 14:14:05
* @Last Modified by: 1ridic
* @Last Modified time: 2022-09-18 14:14:05
*/
#include "line.h"
#include <stdio.h>
#include <readline/readline.h>
#include <readline/history.h>
#include <stdlib.h>
#include <string.h>
char *readLine(void) {
int bufsize = LINE_BUF_SIZE;
int position = 0;
char *buffer = malloc(sizeof(char) * bufsize);
char c;
if (!buffer) {
fprintf(stderr, "dish: allocation error\n");
exit(EXIT_FAILURE);
}
while (1) {
// read a character
c = getchar();
// repleace EOF with a null character and return
if (c == EOF || c == '\n') {
buffer[position] = '\0';
return buffer;
} else {
buffer[position] = c;
}
position++;
/* if the buffer is full, reallocate */
if (position >= bufsize) {
bufsize += LINE_BUF_SIZE;
buffer = realloc(buffer, bufsize);
if (!buffer) {
fprintf(stderr, "dish: allocation error\n");
exit(EXIT_FAILURE);
}
}
}
}
#include <unistd.h>
#include "line.h"
char **splitLine(char *line) {
int bufsize = LINE_BUF_SIZE, position = 0;

12
loop.c
View File

@ -4,12 +4,14 @@
* @Last Modified by: 1ridic
* @Last Modified time: 2022-09-18 23:32:02
*/
#include <stdio.h>
#include <readline/readline.h>
#include <readline/history.h>
#include <stdlib.h>
#include <string.h>
#include "loop.h"
#include "exec.h"
#include "line.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int status;
@ -17,8 +19,8 @@ int loop() {
char *line;
char **args;
printf(ANSI_COLOR_GREEN"> "ANSI_COLOR_RESET);
line = readLine();
line = readline(ANSI_COLOR_GREEN"> "ANSI_COLOR_RESET);
add_history(line);
args = splitLine(line);
status = commandExec(args);
free(line);