Skip to content

Add API to allow reading & writing history to file #9

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion include/slash/slash.h
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@

#include <stddef.h>
#include <stdbool.h>
#include <stdio.h>

#include <slash_config.h>

Expand Down Expand Up @@ -161,7 +162,7 @@ struct slash {
char *history_head;
char *history_tail;
char *history_cursor;

FILE *history_file;
/* Command interface */
char **argv;
int argc;
Expand Down Expand Up @@ -239,6 +240,13 @@ void slash_command_description(struct slash *slash, struct slash_command *comman

int slash_run(struct slash *slash, char * filename, int printcmd);

/**
* @brief Populate Slash history buffer with the content of the given file
* @param slash pointer to valid slash context
* @param history_filename filename to use (will be created if it doesn't exist) to read and write history
*/
void slash_init_history_from_file(struct slash *slash, const char *history_filename);

void slash_history_add(struct slash *slash, char *line);

typedef struct slash_list_iterator_s {
Expand Down
26 changes: 25 additions & 1 deletion src/slash.c
Original file line number Diff line number Diff line change
Expand Up @@ -568,8 +568,13 @@ void slash_history_add(struct slash *slash, char *line)
return;

/* Push including trailing zero */
if (!slash_line_empty(line, strlen(line)))
if (!slash_line_empty(line, strlen(line))) {
if(slash->history_file) {
fprintf(slash->history_file, "%s\n", line);
fflush(slash->history_file);
}
slash_history_push(slash, line, strlen(line) + 1);
}
}

static void slash_history_next(struct slash *slash)
Expand Down Expand Up @@ -1056,3 +1061,22 @@ void slash_destroy(struct slash *slash)

free(slash);
}

void slash_init_history_from_file(struct slash *slash, const char *history_filename) {
/* Set this to NULL to disable history, will be set if all goes well */
slash->history_file = NULL;
FILE *history = fopen(history_filename, "a+");
if (history) {
ssize_t read;
char *line;
size_t len = 0;
while ((read = getline(&line, &len, history)) != -1) {
if(line[read - 1] == '\n') {
line[read - 1] = '\0';
}
slash_history_add(slash, line);
}
free(line);
slash->history_file = history;
}
}
Loading