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_post.c 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #include <stdlib.h>
  2. #include <stddef.h>
  3. #include <string.h>
  4. #include "cms_post.h"
  5. #include "cms_err.h"
  6. #define PREFIX_LENGTH 5
  7. cms_post* cms_post_create()
  8. {
  9. cms_post* post = malloc(sizeof(cms_post));
  10. post->_str = NULL;
  11. post->title = NULL;
  12. post->slug = NULL;
  13. post->html = NULL;
  14. return post;
  15. }
  16. cms_err* cms_post_parse(cms_post* post, char* str, char* slugstr)
  17. {
  18. //Adding 1 because strlen() returns the length without \0
  19. size_t len = strlen(str) + 1;
  20. post->_str = malloc(len * sizeof(char));
  21. if (post->_str == NULL)
  22. return cms_err_create(CMS_ERR_ALLOC, NULL);
  23. memcpy(post->_str, str, len * sizeof(char));
  24. //The post's title will be the first line.
  25. post->title = post->_str;
  26. size_t line = 0;
  27. for (size_t i = 0; i < len; ++i)
  28. {
  29. char c = str[i];
  30. switch (c)
  31. {
  32. case '\n':
  33. line += 1;
  34. if (line == 2)
  35. {
  36. post->html = (post->_str + i + 1);
  37. }
  38. //falls through
  39. case '\r':
  40. post->_str[i] = '\0';
  41. break;
  42. }
  43. if (line == 2)
  44. break;
  45. }
  46. //Strip out the leading "xxxx-" from slugstr (the filename)
  47. //to get the real slug
  48. size_t slugstrlen = strlen(slugstr);
  49. post->slug = malloc((slugstrlen + 1 - PREFIX_LENGTH) * sizeof(char));
  50. if (post->slug == NULL)
  51. return cms_err_create(CMS_ERR_ALLOC, NULL);
  52. memcpy(post->slug, slugstr + PREFIX_LENGTH, (slugstrlen - PREFIX_LENGTH));
  53. //Add \0 to the end of the string
  54. post->slug[slugstrlen - PREFIX_LENGTH] = '\0';
  55. if (line >= 2)
  56. return cms_err_create(CMS_ERR_NONE, NULL);
  57. else
  58. return cms_err_create(CMS_ERR_PARSE, slugstr);
  59. }