From 99e657162fde9c0c5d71d4ade486a34d61ef19bd Mon Sep 17 00:00:00 2001
From: Matt Clay <matt@mystile.com>
Date: Sat, 29 Feb 2020 14:11:25 -0800
Subject: [PATCH] Fix ansible-test module_utils analysis.

---
 changelogs/fragments/ansible-test-ast-parse-bytes.yml | 2 ++
 test/lib/ansible_test/_internal/import_analysis.py    | 7 +++++--
 2 files changed, 7 insertions(+), 2 deletions(-)
 create mode 100644 changelogs/fragments/ansible-test-ast-parse-bytes.yml

diff --git a/changelogs/fragments/ansible-test-ast-parse-bytes.yml b/changelogs/fragments/ansible-test-ast-parse-bytes.yml
new file mode 100644
index 00000000000..330ee8f5580
--- /dev/null
+++ b/changelogs/fragments/ansible-test-ast-parse-bytes.yml
@@ -0,0 +1,2 @@
+bugfixes:
+    - "ansible-test - Fix regression introduced in https://github.com/ansible/ansible/pull/67063 which caused module_utils analysis to fail on Python 2.x."
diff --git a/test/lib/ansible_test/_internal/import_analysis.py b/test/lib/ansible_test/_internal/import_analysis.py
index f1cb66353ec..daefe33edab 100644
--- a/test/lib/ansible_test/_internal/import_analysis.py
+++ b/test/lib/ansible_test/_internal/import_analysis.py
@@ -8,7 +8,7 @@ import os
 from . import types as t
 
 from .io import (
-    read_text_file,
+    read_binary_file,
 )
 
 from .util import (
@@ -165,7 +165,10 @@ def extract_python_module_utils_imports(path, module_utils):
     :type module_utils: set[str]
     :rtype: set[str]
     """
-    code = read_text_file(path)
+    # Python code must be read as bytes to avoid a SyntaxError when the source uses comments to declare the file encoding.
+    # See: https://www.python.org/dev/peps/pep-0263
+    # Specifically: If a Unicode string with a coding declaration is passed to compile(), a SyntaxError will be raised.
+    code = read_binary_file(path)
 
     try:
         tree = ast.parse(code)