-
Notifications
You must be signed in to change notification settings - Fork 280
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Automatically detect character encoding of YAML files and ignore files #630
Open
Jayman2000
wants to merge
6
commits into
adrienverge:master
Choose a base branch
from
Jayman2000:auto-detect-encoding
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
6703bb3
tests: Use correct encoding for path
Jayman2000 4881789
tests: Restore stdout and stderr
Jayman2000 e5ef039
decoder: Autodetect detect encoding of YAML files
Jayman2000 4f97d1f
decoder: Autodetect encoding for ignore-from-file
Jayman2000 a09f5f0
tests: Stop using open()’s default encoding
Jayman2000 a6031a4
CI: Fail when open()’s default encoding is used
Jayman2000 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -13,20 +13,169 @@ | |
# You should have received a copy of the GNU General Public License | ||
# along with this program. If not, see <http://www.gnu.org/licenses/>. | ||
|
||
import codecs | ||
import contextlib | ||
from io import StringIO | ||
import os | ||
import shutil | ||
import sys | ||
import tempfile | ||
import unittest | ||
import warnings | ||
from codecs import CodecInfo | ||
|
||
import yaml | ||
|
||
from yamllint import linter | ||
from yamllint.config import YamlLintConfig | ||
|
||
|
||
# Encoding related stuff: | ||
UTF_CODECS = ( | ||
'utf_32_be', | ||
'utf_32_be_sig', | ||
'utf_32_le', | ||
'utf_32_le_sig', | ||
'utf_16_be', | ||
'utf_16_be_sig', | ||
'utf_16_le', | ||
'utf_16_le_sig', | ||
'utf_8', | ||
'utf_8_sig' | ||
) | ||
|
||
|
||
def encode_utf_32_be_sig(obj, errors='strict'): | ||
return ( | ||
codecs.BOM_UTF32_BE + codecs.encode(obj, 'utf_32_be', errors), | ||
len(obj) | ||
) | ||
|
||
|
||
def encode_utf_32_le_sig(obj, errors='strict'): | ||
return ( | ||
codecs.BOM_UTF32_LE + codecs.encode(obj, 'utf_32_le', errors), | ||
len(obj) | ||
) | ||
|
||
|
||
def encode_utf_16_be_sig(obj, errors='strict'): | ||
return ( | ||
codecs.BOM_UTF16_BE + codecs.encode(obj, 'utf_16_be', errors), | ||
len(obj) | ||
) | ||
|
||
|
||
def encode_utf_16_le_sig(obj, errors='strict'): | ||
return ( | ||
codecs.BOM_UTF16_LE + codecs.encode(obj, 'utf_16_le', errors), | ||
len(obj) | ||
) | ||
|
||
|
||
test_codec_infos = { | ||
'utf_32_be_sig': CodecInfo(encode_utf_32_be_sig, codecs.getdecoder('utf_32')), # noqa: E501 | ||
'utf_32_le_sig': CodecInfo(encode_utf_32_le_sig, codecs.getdecoder('utf_32')), # noqa: E501 | ||
'utf_16_be_sig': CodecInfo(encode_utf_16_be_sig, codecs.getdecoder('utf_16')), # noqa: E501 | ||
'utf_16_le_sig': CodecInfo(encode_utf_16_le_sig, codecs.getdecoder('utf_16')), # noqa: E501 | ||
} | ||
Comment on lines
+76
to
+81
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I understand these test_codec_infos = {
'utf_32_be_sig':
CodecInfo(encode_utf_32_be_sig, codecs.getdecoder('utf_32')), or this: test_codec_infos = {
'utf_32_be_sig': CodecInfo(encode_utf_32_be_sig,
codecs.getdecoder('utf_32')), ? |
||
|
||
|
||
def register_test_codecs(): | ||
codecs.register(test_codec_infos.get) | ||
|
||
|
||
def unregister_test_codecs(): | ||
if sys.version_info >= (3, 10, 0): | ||
codecs.unregister(test_codec_infos.get) | ||
else: | ||
warnings.warn( | ||
"This version of Python doesn’t allow us to unregister codecs.", | ||
stacklevel=1 | ||
) | ||
|
||
|
||
def is_test_codec(codec): | ||
return codec in test_codec_infos.keys() | ||
|
||
|
||
def test_codec_built_in_equivalent(test_codec): | ||
return_value = test_codec | ||
for suffix in ('_sig', '_be', '_le'): | ||
return_value = return_value.replace(suffix, '') | ||
return return_value | ||
|
||
|
||
def uses_bom(codec): | ||
for suffix in ('_32', '_16', '_sig'): | ||
if codec.endswith(suffix): | ||
return True | ||
return False | ||
|
||
|
||
def encoding_detectable(string, codec): | ||
""" | ||
Returns True if encoding can be detected after string is encoded | ||
|
||
Encoding detection only works if you’re using a BOM or the first character | ||
is ASCII. See yamllint.decoder.auto_decode()’s docstring. | ||
""" | ||
return uses_bom(codec) or (len(string) > 0 and string[0].isascii()) | ||
|
||
|
||
# Workspace related stuff: | ||
class Blob: | ||
def __init__(self, text, encoding): | ||
self.text = text | ||
self.encoding = encoding | ||
|
||
|
||
def build_temp_workspace(files): | ||
tempdir = tempfile.mkdtemp(prefix='yamllint-tests-') | ||
|
||
for path, content in files.items(): | ||
path = os.fsencode(os.path.join(tempdir, path)) | ||
if not os.path.exists(os.path.dirname(path)): | ||
os.makedirs(os.path.dirname(path)) | ||
|
||
if isinstance(content, list): | ||
os.mkdir(path) | ||
elif isinstance(content, str) and content.startswith('symlink://'): | ||
os.symlink(content[10:], path) | ||
else: | ||
if isinstance(content, Blob): | ||
content = content.text.encode(content.encoding) | ||
elif isinstance(content, str): | ||
content = content.encode('utf_8') | ||
with open(path, 'wb') as f: | ||
f.write(content) | ||
|
||
return tempdir | ||
|
||
|
||
@contextlib.contextmanager | ||
def temp_workspace(files): | ||
"""Provide a temporary workspace that is automatically cleaned up.""" | ||
backup_wd = os.getcwd() | ||
wd = build_temp_workspace(files) | ||
|
||
try: | ||
os.chdir(wd) | ||
yield | ||
finally: | ||
os.chdir(backup_wd) | ||
shutil.rmtree(wd) | ||
|
||
|
||
def temp_workspace_with_files_in_many_codecs(path_template, text): | ||
workspace = {} | ||
for codec in UTF_CODECS: | ||
if encoding_detectable(text, codec): | ||
workspace[path_template.format(codec)] = Blob(text, codec) | ||
return workspace | ||
|
||
|
||
# Miscellaneous stuff: | ||
class RuleTestCase(unittest.TestCase): | ||
def build_fake_config(self, conf): | ||
if conf is None: | ||
|
@@ -81,37 +230,3 @@ def __exit__(self, *exc_info): | |
@property | ||
def returncode(self): | ||
return self._raises_ctx.exception.code | ||
|
||
|
||
def build_temp_workspace(files): | ||
tempdir = tempfile.mkdtemp(prefix='yamllint-tests-') | ||
|
||
for path, content in files.items(): | ||
path = os.path.join(tempdir, path).encode('utf-8') | ||
if not os.path.exists(os.path.dirname(path)): | ||
os.makedirs(os.path.dirname(path)) | ||
|
||
if isinstance(content, list): | ||
os.mkdir(path) | ||
elif isinstance(content, str) and content.startswith('symlink://'): | ||
os.symlink(content[10:], path) | ||
else: | ||
mode = 'wb' if isinstance(content, bytes) else 'w' | ||
with open(path, mode) as f: | ||
f.write(content) | ||
|
||
return tempdir | ||
|
||
|
||
@contextlib.contextmanager | ||
def temp_workspace(files): | ||
"""Provide a temporary workspace that is automatically cleaned up.""" | ||
backup_wd = os.getcwd() | ||
wd = build_temp_workspace(files) | ||
|
||
try: | ||
os.chdir(wd) | ||
yield | ||
finally: | ||
os.chdir(backup_wd) | ||
shutil.rmtree(wd) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It looks like
errors='strict'
is already the default: https://docs.python.org/3/library/codecs.html#codecs.encode and no yamllint code uses this argument anywhere.But I'm OK to keep it if you think it's better to be explicit.