A static site generator, written in C
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.

cms_page.c 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #include <stddef.h>
  2. #include <string.h>
  3. #include <dirent.h>
  4. #include <sys/types.h>
  5. #include <errno.h>
  6. #include "cms_page.h"
  7. #include "cms_err.h"
  8. #include <stdlib.h>
  9. #define PREFIX_LENGTH 5
  10. cms_page* cms_page_create()
  11. {
  12. cms_page* page = malloc(sizeof(cms_page));
  13. page->_str = NULL;
  14. page->title = NULL;
  15. page->slug = NULL;
  16. page->numposts = 0;
  17. page->numsubs = 0;
  18. page->posts = NULL;
  19. page->subs = NULL;
  20. return page;
  21. }
  22. cms_err* cms_page_parse(cms_page* page, char* str, char* slugstr)
  23. {
  24. //Adding 1 because strlen() returns the length without \0
  25. size_t len = strlen(str) + 1;
  26. page->_str = malloc(len * sizeof(char));
  27. if (page->_str == NULL)
  28. return cms_err_create(CMS_ERR_ALLOC, NULL);
  29. memcpy(page->_str, str, len * sizeof(char));
  30. //The page's title will be the first line.
  31. page->title = page->_str;
  32. //Replace newlines with \0
  33. for (size_t i = 0; i < len; ++i)
  34. {
  35. char c = str[i];
  36. switch (c)
  37. {
  38. case '\n':
  39. case '\r':
  40. page->_str[i] = '\0';
  41. break;
  42. }
  43. }
  44. //Strip out the leading "xxxx-" from slugstr (the filename)
  45. //to get the real slug
  46. size_t slugstrlen = strlen(slugstr);
  47. page->slug = malloc((slugstrlen + 1 - PREFIX_LENGTH) * sizeof(char));
  48. if (page->slug == NULL)
  49. return cms_err_create(CMS_ERR_ALLOC, NULL);
  50. memcpy(page->slug, slugstr + PREFIX_LENGTH, (slugstrlen - PREFIX_LENGTH));
  51. //Add \0 to the end of the string
  52. page->slug[slugstrlen - PREFIX_LENGTH] = '\0';
  53. return cms_err_create(CMS_ERR_NONE, NULL);
  54. }
  55. cms_err* cms_page_add_post(cms_page* page, cms_post* post)
  56. {
  57. page->numposts += 1;
  58. page->posts = realloc(page->posts, page->numposts * sizeof(cms_post));
  59. if (page->posts == NULL)
  60. return cms_err_create(CMS_ERR_ALLOC, NULL);
  61. page->posts[page->numposts - 1] = *post;
  62. return cms_err_create(CMS_ERR_NONE, NULL);
  63. }
  64. cms_err* cms_page_add_sub(cms_page* page, cms_page* sub)
  65. {
  66. page->numsubs += 1;
  67. page->subs = realloc(page->subs, page->numsubs * sizeof(cms_page));
  68. if (page->subs == NULL)
  69. return cms_err_create(CMS_ERR_ALLOC, NULL);
  70. page->subs[page->numsubs - 1] = *sub;
  71. return cms_err_create(CMS_ERR_NONE, NULL);
  72. }