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

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