Skip to content

Commit

Permalink
Handle quotes in annotations codemod
Browse files Browse the repository at this point in the history
Summary: We encounter this for cpp.methods, which sometimes injects constructors with default string arguments

Reviewed By: yoney

Differential Revision: D68931171

fbshipit-source-id: 928c9a104f0bce14d2f76cca89c668f86484f264
  • Loading branch information
iahs authored and facebook-github-bot committed Jan 31, 2025
1 parent 3ba2e26 commit 347fb04
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,22 @@ bool is_container(const t_type& type) {
return true_type && true_type->is_container();
}

std::string quote(std::string_view str) {
if (str.find('"') == std::string::npos) {
return fmt::format("\"{}\"", str);
} else if (str.find('\'') == std::string::npos) {
return fmt::format("'{}'", str);
} else {
std::string out(str);
size_t start_pos = 0;
while ((start_pos = out.find('"', start_pos)) != std::string::npos) {
out.replace(start_pos, 1, "\\\"");
start_pos += 2;
}
return fmt::format("\"{}\"", out);
}
}

class structure_annotations {
public:
structure_annotations(source_manager& sm, t_program& program)
Expand Down Expand Up @@ -516,7 +532,7 @@ class structure_annotations {
std::vector<std::string> annotations_for_catch_all_strs;
for (const auto& [name, value] : annotations_for_catch_all) {
annotations_for_catch_all_strs.push_back(
fmt::format(R"("{}": "{}")", name, value));
fmt::format(R"("{}": {})", name, quote(value)));
}
to_add.insert(fmt::format(
"@thrift.DeprecatedUnvalidatedAnnotations{{items = {{{}}}}}",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -489,7 +489,7 @@ def test_remaining(self):
include "thrift.thrift"
struct S {
1: i32 field1 (foo);
1: i32 field1 (foo, quote = '"', both_quotes = "'\\"'");
}(foo, bar = "baz")
typedef i32 (foo, hs.type = "hs") T (bar = "baz", hs.category = "value")
Expand Down Expand Up @@ -530,7 +530,7 @@ def test_remaining(self):
@thrift.DeprecatedUnvalidatedAnnotations{items = {"bar": "baz", "foo": "1"}}
struct S {
@thrift.DeprecatedUnvalidatedAnnotations{items = {"foo": "1"}}
@thrift.DeprecatedUnvalidatedAnnotations{items = {"both_quotes": "'\\"'", "foo": "1", "quote": '"'}}
1: i32 field1 ;
}
Expand Down

0 comments on commit 347fb04

Please sign in to comment.