Skip to content

Commit

Permalink
Don't quote strings that start with 0 when running ansible-lint --fix. (
Browse files Browse the repository at this point in the history
  • Loading branch information
kousu authored May 24, 2024
1 parent ac9ccb6 commit 4588273
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 6 deletions.
27 changes: 21 additions & 6 deletions src/ansiblelint/yaml_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -642,14 +642,29 @@ def choose_scalar_style(self) -> Any:
and self.event.value.startswith("0")
and len(self.event.value) > 1
):
if self.event.tag == "tag:yaml.org,2002:int" and self.event.implicit[0]:
if self.event.value.startswith("0x"):
self.event.tag = "tag:yaml.org,2002:str"
return ""
# ensures that "0123" string does not lose its quoting
# We have an as-yet unquoted token that starts with "0" (but is not itself the digit 0).
# It could be:
# - hexadecimal like "0xF1" or ; comes tagged as int. Should continue unquoted to continue as an int.
# - octal like "0666" or "0o755"; comes tagged as str. **Should** be quoted to be cross-YAML compatible.
# - string like "0.0.0.0" and "00-header". Should not be quoted, unless it has a quote in it.
if (
self.event.value.startswith("0x")
and self.event.tag == "tag:yaml.org,2002:int"
and self.event.implicit[0]
):
# hexadecimal
self.event.tag = "tag:yaml.org,2002:str"
return ""
try:
int(self.event.value, 8)
except ValueError:
pass
# fallthrough to string
else:
# octal
self.event.tag = "tag:yaml.org,2002:str"
self.event.implicit = (True, True, True)
return '"'
return '"'
if style != "'":
# block scalar, double quoted, etc.
return style
Expand Down
7 changes: 7 additions & 0 deletions test/fixtures/formatting-after/fmt-2.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,10 @@
- 10
- 9999
zero: 0 # Not an octal. See #2071

- string:
- 0steps
- 9steps
- 0.0.0.0
- "0"
- "01234"
7 changes: 7 additions & 0 deletions test/fixtures/formatting-before/fmt-2.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,10 @@
- 10
- 9999
zero: 0 # Not an octal. See #2071

- string:
- 0steps
- 9steps
- 0.0.0.0
- "0"
- "01234"
7 changes: 7 additions & 0 deletions test/fixtures/formatting-prettier/fmt-2.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,10 @@
- 10
- 9999
zero: 0 # Not an octal. See #2071

- string:
- 0steps
- 9steps
- 0.0.0.0
- "0"
- "01234"

0 comments on commit 4588273

Please sign in to comment.