line-length: Generalize ...-inline-mappings for corner cases

This commit refactors the `allow-non-breakable-inline-mappings` logic to
use YAML tokens and avoid crashes or erroneous reports on cases like:

```yaml
- {a: "http://localhost/very/very/very/very/very/very/long/url"
   }
```

```yaml
dict:
  {a: long long long long long long long, b: nospace}
```

```yaml
- long_line: http://localhost/very/very/long/url
```

```yaml
long_line: and+some+space+at+the+end       <-- extra spaces
```

For reference see:
https://github.com/adrienverge/yamllint/pull/17#issuecomment-247805799
This commit is contained in:
Adrien Vergé
2016-09-17 22:24:12 +02:00
committed by Allan Lewis
parent e56a7c788c
commit d3cd8ba332
2 changed files with 45 additions and 6 deletions

View File

@@ -87,6 +87,7 @@ Use this rule to set a limit to lines length.
http://localhost/very/very/very/very/very/very/very/very/long/url
"""
import yaml
from yamllint.linter import LintProblem
@@ -99,6 +100,18 @@ CONF = {'max': int,
'allow-non-breakable-inline-mappings': bool}
def check_inline_mapping(line):
loader = yaml.SafeLoader(line.content)
while loader.peek_token():
if isinstance(loader.get_token(), yaml.BlockMappingStartToken):
while loader.peek_token():
if isinstance(loader.get_token(), yaml.ValueToken):
t = loader.get_token()
if isinstance(t, yaml.ScalarToken):
return ' ' not in line.content[t.start_mark.column:]
return False
def check(conf, line):
if line.end - line.start > conf['max']:
conf['allow-non-breakable-words'] |= \
@@ -115,11 +128,9 @@ def check(conf, line):
if line.buffer.find(' ', start, line.end) == -1:
return
if conf['allow-non-breakable-inline-mappings']:
line_yaml = yaml.safe_load(line.content)
if (isinstance(line_yaml, dict) and
' ' not in line_yaml.popitem()[1]):
return
if (conf['allow-non-breakable-inline-mappings'] and
check_inline_mapping(line)):
return
yield LintProblem(line.line_no, conf['max'] + 1,
'line too long (%d > %d characters)' %