Build tool
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.

compdb.cc 1.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include "compdb.h"
  2. namespace compdb {
  3. std::string escape(const std::string &str) {
  4. std::string out;
  5. out.reserve(str.size() * 1.5);
  6. // TODO: Handle unicode according to JSON spec
  7. for (char ch: str) {
  8. if (ch == '\\' || ch == '\"') {
  9. out += '\\';
  10. out += ch;
  11. } else if (ch == '\r') {
  12. out += '\\';
  13. out += 'r';
  14. } else if (ch == '\n') {
  15. out += '\\';
  16. out += 'n';
  17. } else {
  18. out += ch;
  19. }
  20. }
  21. return out;
  22. }
  23. void Writer::write(
  24. const std::string &dir, const std::string &file,
  25. const std::vector<std::string> &cmd) {
  26. if (first_) {
  27. buf_.put("[\n\t{\n");
  28. first_ = false;
  29. } else {
  30. buf_.put(", {\n");
  31. }
  32. buf_.put("\t\t\"directory\": \"");
  33. buf_.put(escape(dir));
  34. buf_.put("\",\n");
  35. buf_.put("\t\t\"file\": \"");
  36. buf_.put(escape(file));
  37. buf_.put("\",\n");
  38. buf_.put("\t\t\"command\": \"");
  39. buf_.put(escape(cmd[0]));
  40. for (size_t i = 1; i < cmd.size(); ++i) {
  41. buf_.put(' ');
  42. buf_.put(escape('"' + escape(cmd[i]) + '"'));
  43. }
  44. buf_.put("\"\n\t}");
  45. }
  46. Writer::~Writer() {
  47. if (first_) {
  48. buf_.put("[]\n");
  49. } else {
  50. buf_.put("\n]\n");
  51. }
  52. }
  53. }