Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/libcst/codemod/commands/unnecessary_format_string.py: 84%
19 statements
« prev ^ index » next coverage.py v7.3.1, created at 2023-09-25 06:43 +0000
« prev ^ index » next coverage.py v7.3.1, created at 2023-09-25 06:43 +0000
1# Copyright (c) Meta Platforms, Inc. and affiliates.
2#
3# This source code is licensed under the MIT license found in the
4# LICENSE file in the root directory of this source tree.
5#
6import libcst
7import libcst.matchers as m
8from libcst.codemod import VisitorBasedCodemodCommand
11class UnnecessaryFormatString(VisitorBasedCodemodCommand):
12 DESCRIPTION: str = (
13 "Converts f-strings which perform no formatting to regular strings."
14 )
16 @m.leave(m.FormattedString(parts=(m.FormattedStringText(),)))
17 def _check_formatted_string(
18 self,
19 _original_node: libcst.FormattedString,
20 updated_node: libcst.FormattedString,
21 ) -> libcst.BaseExpression:
22 old_string_inner = libcst.ensure_type(
23 updated_node.parts[0], libcst.FormattedStringText
24 ).value
25 if "{{" in old_string_inner or "}}" in old_string_inner:
26 # there are only two characters we need to worry about escaping.
27 return updated_node
29 old_string_literal = updated_node.start + old_string_inner + updated_node.end
30 new_string_literal = (
31 updated_node.start.replace("f", "").replace("F", "")
32 + old_string_inner
33 + updated_node.end
34 )
36 old_string_evaled = eval(old_string_literal) # noqa
37 new_string_evaled = eval(new_string_literal) # noqa
38 if old_string_evaled != new_string_evaled:
39 warn_message = (
40 f"Attempted to codemod |{old_string_literal}| to "
41 + f"|{new_string_literal}| but don't eval to the same! First is |{old_string_evaled}| and "
42 + f"second is |{new_string_evaled}|"
43 )
44 self.warn(warn_message)
45 return updated_node
47 return libcst.SimpleString(new_string_literal)