123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- #include "history.h"
-
- char * history_filename_init(const char *homedir)
- {
- const char fmt[] = "%s/.local/share/asmsh";
- char *path;
- int sz;
- int fd = open("/dev/null", O_WRONLY);
- if(!fd)
- {
- perror("Unable to open /dev/null");
- return NULL;
- }
- const char *home = homedir?homedir:getenv("HOME");
- if(!home)
- {
- dprintf(2, "No $HOME variable found\n");
- return NULL;
- }
- sz = dprintf(fd, fmt, home);
- if(sz < 0)
- {
- perror("Not able to format local share folder");
- return NULL;
- }
-
- path = alloca(sz+1);
- sprintf(path, fmt, home);
- path[sz]='\0';
- if(access(path, F_OK) < 0)
- {
- mkdir(path, 0755);
- }
- char *res = malloc(sz+strlen(ASMSH_HISTORY_FILE)+3);
- if(!res)
- {
- perror("Unable tot allocate history filename");
- return NULL;
- }
- sz = sprintf(res, "%s/%s", path, ASMSH_HISTORY_FILE);
- res[sz] = '\0';
- return res;
- }
-
-
- int save_history(const char *history_path, const char * const *hists)
- {
- int fd = open(history_path, O_WRONLY|O_CREAT|O_TRUNC, 0744);
- if(fd < 0)
- {
- perror("Unable to open history file");
- dprintf(2, "could not save history in %s\n", history_path);
- return -1;
- }
- for(const char * const *hist=hists; *hist; hist++)
- {
- dprintf(fd, "%s\n", *hist);
- }
- close(fd);
- return 0;
- }
-
- int load_history(const char *history_path, add_history_f *add_h)
- {
- if(access(history_path, F_OK) < 0) { return 0; }
-
- int readed, wanted;
- int fd = open(history_path, O_RDONLY);
- char buf[4096], *cur, *line;
- if(fd < 0)
- {
- perror("Unable to open history file");
- return -1;
- }
-
- cur = buf;
- wanted = sizeof(buf)-1;
- do
- {
- readed = read(fd, cur, wanted);
- if(readed < 0)
- {
- perror("Unable to read history file");
- close(fd);
- return -1;
- }
- cur[readed]='\0';
- for(line=cur=buf; *cur; cur++)
- {
- if(*cur=='\n')
- {
- *cur='\0';
- if(cur-line>1 && *line != '#')
- {
- add_h(line);
- }
- line = cur+1;
- }
- }
- if(*line)
- {
- wanted = sizeof(buf) - (strlen(line)+1);
- memmove(buf, line, strlen(line)+1);
- }
- }while(readed && readed == wanted);
- close(fd);
- }
|