/
unnecessary_format_string.py
47 lines (40 loc) · 1.76 KB
/
unnecessary_format_string.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
# pyre-strict
import libcst
import libcst.matchers as m
from libcst.codemod import VisitorBasedCodemodCommand
class UnnecessaryFormatString(VisitorBasedCodemodCommand):
DESCRIPTION: str = "Converts f-strings which perform no formatting to regular strings."
@m.leave(m.FormattedString(parts=(m.FormattedStringText(),)))
def _check_formatted_string(
self,
_original_node: libcst.FormattedString,
updated_node: libcst.FormattedString,
) -> libcst.BaseExpression:
old_string_inner = libcst.ensure_type(
updated_node.parts[0], libcst.FormattedStringText
).value
if "{{" in old_string_inner or "}}" in old_string_inner:
# there are only two characters we need to worry about escaping.
return updated_node
old_string_literal = updated_node.start + old_string_inner + updated_node.end
new_string_literal = (
updated_node.start.replace("f", "").replace("F", "")
+ old_string_inner
+ updated_node.end
)
old_string_evaled = eval(old_string_literal) # noqa
new_string_evaled = eval(new_string_literal) # noqa
if old_string_evaled != new_string_evaled:
warn_message = (
f"Attempted to codemod |{old_string_literal}| to "
+ f"|{new_string_literal}| but dont eval to the same! First is |{old_string_evaled}| and "
+ f"second is |{new_string_evaled}|"
)
self.warn(warn_message)
return updated_node
return libcst.SimpleString(new_string_literal)