diff --git a/src/ansiblelint/yaml_utils.py b/src/ansiblelint/yaml_utils.py index 6a479211bea..3fe5b8d58a6 100644 --- a/src/ansiblelint/yaml_utils.py +++ b/src/ansiblelint/yaml_utils.py @@ -642,14 +642,26 @@ def choose_scalar_style(self) -> Any: and self.event.value.startswith("0") and len(self.event.value) > 1 ): + # 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.tag == "tag:yaml.org,2002:int" and self.event.implicit[0]: if self.event.value.startswith("0x"): + # hexadecimal self.event.tag = "tag:yaml.org,2002:str" return "" - # ensures that "0123" string does not lose its quoting + try: + int(self.event.value, 8) + # octal self.event.tag = "tag:yaml.org,2002:str" self.event.implicit = (True, True, True) - return '"' + return '"' + except ValueError: + pass + # fallthrough to string if style != "'": # block scalar, double quoted, etc. return style diff --git a/test/fixtures/formatting-after/fmt-2.yml b/test/fixtures/formatting-after/fmt-2.yml index a162721772b..3601acc225f 100644 --- a/test/fixtures/formatting-after/fmt-2.yml +++ b/test/fixtures/formatting-after/fmt-2.yml @@ -22,3 +22,10 @@ - 10 - 9999 zero: 0 # Not an octal. See #2071 + +- string: + - 0steps + - 9steps + - 0.0.0.0 + - "0" + - "01234" diff --git a/test/fixtures/formatting-before/fmt-2.yml b/test/fixtures/formatting-before/fmt-2.yml index 294166327ca..dbfb7774139 100644 --- a/test/fixtures/formatting-before/fmt-2.yml +++ b/test/fixtures/formatting-before/fmt-2.yml @@ -22,3 +22,10 @@ - 10 - 9999 zero: 0 # Not an octal. See #2071 + + - string: + - 0steps + - 9steps + - 0.0.0.0 + - "0" + - "01234" diff --git a/test/fixtures/formatting-prettier/fmt-2.yml b/test/fixtures/formatting-prettier/fmt-2.yml index 90ac484e322..037c9dd73b8 100644 --- a/test/fixtures/formatting-prettier/fmt-2.yml +++ b/test/fixtures/formatting-prettier/fmt-2.yml @@ -22,3 +22,10 @@ - 10 - 9999 zero: 0 # Not an octal. See #2071 + +- string: + - 0steps + - 9steps + - 0.0.0.0 + - "0" + - "01234"