history.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // SPDX-License-Identifier: Apache-2.0
  2. /*
  3. * Copyright (C) 2013 Intel Corporation
  4. *
  5. */
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include <stdio.h>
  9. #include <ctype.h>
  10. #include "history.h"
  11. /* Very simple history storage for easy usage of tool */
  12. #define HISTORY_DEPTH 40
  13. #define LINE_SIZE 200
  14. static char lines[HISTORY_DEPTH][LINE_SIZE];
  15. static int last_line = 0;
  16. static int history_size = 0;
  17. /* TODO: Storing history not implemented yet */
  18. void history_store(const char *filename)
  19. {
  20. }
  21. /* Restoring history from file */
  22. void history_restore(const char *filename)
  23. {
  24. char line[1000];
  25. FILE *f = fopen(filename, "rt");
  26. if (f == NULL)
  27. return;
  28. for (;;) {
  29. if (fgets(line, 1000, f) != NULL) {
  30. int l = strlen(line);
  31. while (l > 0 && isspace(line[--l]))
  32. line[l] = 0;
  33. if (l > 0)
  34. history_add_line(line);
  35. } else
  36. break;
  37. }
  38. fclose(f);
  39. }
  40. /* Add new line to history buffer */
  41. void history_add_line(const char *line)
  42. {
  43. if (line == NULL || strlen(line) == 0)
  44. return;
  45. if (strcmp(line, lines[last_line]) == 0)
  46. return;
  47. last_line = (last_line + 1) % HISTORY_DEPTH;
  48. strncpy(&lines[last_line][0], line, LINE_SIZE - 1);
  49. if (history_size < HISTORY_DEPTH)
  50. history_size++;
  51. }
  52. /*
  53. * Get n-th line from history
  54. * 0 - means latest
  55. * -1 - means oldest
  56. * return -1 if there is no such line
  57. */
  58. int history_get_line(int n, char *buf, int buf_size)
  59. {
  60. if (n == -1)
  61. n = history_size - 1;
  62. if (n >= history_size || buf_size == 0 || n < 0)
  63. return -1;
  64. strncpy(buf,
  65. &lines[(HISTORY_DEPTH + last_line - n) % HISTORY_DEPTH][0],
  66. buf_size - 1);
  67. buf[buf_size - 1] = 0;
  68. return n;
  69. }