A shell that runs x86_64 assembly
c
x86-64
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

history.c 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. #include "history.h"
  2. char * history_filename_init(const char *homedir)
  3. {
  4. const char fmt[] = "%s/.local/share/asmsh";
  5. int sz;
  6. int fd = open("/dev/null", O_WRONLY);
  7. if(!fd)
  8. {
  9. perror("Unable to open /dev/null");
  10. return NULL;
  11. }
  12. const char *home = homedir?homedir:getenv("HOME");
  13. if(!home)
  14. {
  15. dprintf(2, "No $HOME variable found\n");
  16. return NULL;
  17. }
  18. sz = dprintf(fd, fmt, home);
  19. if(sz < 0)
  20. {
  21. perror("Not able to format local share folder");
  22. return NULL;
  23. }
  24. char path[sz+1];
  25. sprintf(path, fmt, home);
  26. path[sz]='\0';
  27. if(access(path, F_OK) < 0)
  28. {
  29. mkdir(path, 0755);
  30. }
  31. char *res = malloc(sz+strlen(ASMSH_HISTORY_FILE)+3);
  32. if(!res)
  33. {
  34. perror("Unable tot allocate history filename");
  35. return NULL;
  36. }
  37. sz = sprintf(res, "%s/%s", path, ASMSH_HISTORY_FILE);
  38. res[sz] = '\0';
  39. return res;
  40. }
  41. int save_history(const char *history_path, const char * const *hists)
  42. {
  43. int fd = open(history_path, O_WRONLY|O_CREAT|O_TRUNC, 0744);
  44. if(fd < 0)
  45. {
  46. perror("Unable to open history file");
  47. dprintf(2, "could not save history in %s\n", history_path);
  48. return -1;
  49. }
  50. for(const char * const *hist=hists; *hist; hist++)
  51. {
  52. dprintf(fd, "%s\n", *hist);
  53. }
  54. close(fd);
  55. return 0;
  56. }
  57. int load_history(const char *history_path, add_history_f *add_h)
  58. {
  59. if(access(history_path, F_OK) < 0) { return 0; }
  60. int readed, wanted;
  61. int fd = open(history_path, O_RDONLY);
  62. char buf[4096], *cur, *line;
  63. if(fd < 0)
  64. {
  65. perror("Unable to open history file");
  66. return -1;
  67. }
  68. cur = buf;
  69. wanted = sizeof(buf)-1;
  70. do
  71. {
  72. readed = read(fd, cur, wanted);
  73. if(readed < 0)
  74. {
  75. perror("Unable to read history file");
  76. close(fd);
  77. return -1;
  78. }
  79. cur[readed]='\0';
  80. for(line=cur=buf; *cur; cur++)
  81. {
  82. if(*cur=='\n')
  83. {
  84. *cur='\0';
  85. if(cur-line>1 && *line != '#')
  86. {
  87. add_h(line);
  88. }
  89. line = cur+1;
  90. }
  91. }
  92. if(*line)
  93. {
  94. wanted = sizeof(buf) - (strlen(line)+1);
  95. memmove(buf, line, strlen(line)+1);
  96. }
  97. }while(readed && readed == wanted);
  98. close(fd);
  99. return 0;
  100. }