Skip to content

Commit

Permalink
feat: setup new nox session for update vendor packages
Browse files Browse the repository at this point in the history
Signed-off-by: loonghao <[email protected]>
  • Loading branch information
loonghao committed May 12, 2024
1 parent 5fa3081 commit fc96b75
Show file tree
Hide file tree
Showing 13 changed files with 52 additions and 83 deletions.
3 changes: 2 additions & 1 deletion .flake8
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ exclude =
# This contains builds of flake8 that we don't want to check
dist,
venv,
docs
docs,
maya_umbrella/_vendor

max-line-length = 120
5 changes: 4 additions & 1 deletion manual_test_in_maya.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,8 @@ def get_virus_files():

def start():
for maya_file in get_virus_files():
open_maya_file(maya_file)
try:
open_maya_file(maya_file)
except RuntimeError:
pass
cmds.file(new=True, force=True)
2 changes: 1 addition & 1 deletion maya_umbrella/cleaner.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import re

# Import local modules
from maya_umbrella.constants import FILE_VIRUS_SIGNATURES
from maya_umbrella.signatures import FILE_VIRUS_SIGNATURES
from maya_umbrella.filesystem import remove_virus_file_by_signature
from maya_umbrella.filesystem import safe_remove_file
from maya_umbrella.filesystem import safe_rmtree
Expand Down
17 changes: 0 additions & 17 deletions maya_umbrella/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,3 @@
LOG_FORMAT = "%(asctime)s [%(levelname)s] %(name)s: %(message)s"

LOG_MAX_BYTES = 1024 * 1024 * 5

FILE_VIRUS_SIGNATURES = [
"import vaccine",
"cmds.evalDeferred.*leukocyte.+",
# https://regex101.com/r/0MNzF7/1
"python(.*);.+exec.+(pyCode).+;",
]

JOB_SCRIPTS_VIRUS_SIGNATURES = [
"petri_dish_path.+cmds.internalVar.+",
"userSetup",
"fuckVirus",
# https://regex101.com/r/0MNzF7/1
"python(.*);.+exec.+(pyCode).+;",
# https://regex101.com/r/2D14UA/1
r"^\['.+']",
]
62 changes: 18 additions & 44 deletions maya_umbrella/filesystem.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
# Import built-in modules
import codecs
from contextlib import contextmanager
import glob
import importlib
Expand All @@ -10,16 +9,12 @@
import re
import shutil
import string
import sys
import tempfile

# Import local modules
from maya_umbrella.constants import FILE_VIRUS_SIGNATURES
from maya_umbrella.signatures import FILE_VIRUS_SIGNATURES
from maya_umbrella.constants import PACKAGE_NAME


PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
from maya_umbrella._vendor import six


def this_root():
Expand All @@ -43,37 +38,24 @@ def safe_rmtree(path):
pass


def _codes_open(path, encoding="utf-8"):
"""Open and read the content of a file using the specified encoding.
def read_file(path):
"""Read the file content.
Args:
path (str): Path to the file.
encoding (str, optional): The encoding to use when reading the file. Defaults to "utf-8".
path (str): File path of source.
Returns:
str: The content of the file, or an empty string if the file could not be read.
"""
try:
with codecs.open(path, "r", encoding) as file_:
return file_.read()
except (OSError, IOError): # noqa: UP024
return ""
str: The contents of the file path.
def read_file(path):
"""Read the content of the file at the given path."""
options = {"encoding": "utf-8"} if PY3 else {}
with open(path, **options) as file_:
try:
content = file_.read()
# maya-2022 UnicodeDecodeError from `plug-ins/mayaHIK.pres.mel`
except UnicodeDecodeError:
return ""
"""
with open(path, "rb") as file_stream:
content = file_stream.read()
return content


def read_json(path):
"""Read the content of the file at the given path."""
options = {"encoding": "utf-8"} if PY3 else {}
options = {"encoding": "utf-8"} if six.PY3 else {}
with open(path, **options) as file_:
try:
content = json.load(file_)
Expand All @@ -84,13 +66,12 @@ def read_json(path):

def write_file(path, content):
"""Write the given content to the file at the given path."""
options = {"encoding": "utf-8"} if PY3 else {}
with atomic_writes(path, "w", **options) as file_:
file_.write(content)
with atomic_writes(path, "wb") as file_:
file_.write(six.ensure_binary(content))


@contextmanager
def atomic_writes(src, mode, **options):
def atomic_writes(src, mode):
"""Context manager for atomic writes to a file.
This context manager ensures that the file is only written to disk if the write operation completes without errors.
Expand All @@ -107,15 +88,13 @@ def atomic_writes(src, mode, **options):
AttributeError: If the os module does not have the 'replace' function (Python 2 compatibility).
"""
temp_path = os.path.join(os.path.dirname(src), "._{}".format(id_generator()))
open_func = open if PY3 else codecs.open
with open_func(temp_path, mode, **options) as f:
with open(temp_path, mode) as f:
yield f
try:
os.replace(temp_path, src)
except AttributeError:
shutil.move(temp_path, src)


def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
"""Generate a random string of the given size using the given characters."""
return "".join(random.choice(chars) for _ in range(size))
Expand Down Expand Up @@ -203,12 +182,7 @@ def remove_virus_file_by_signature(file_path, signatures, output_file_path=None,
auto_remove: If True, remove the input file if the output file is empty.
"""
try:
data = read_file(file_path)
except (OSError, IOError): # noqa: UP024
return False
except UnicodeDecodeError:
data = _codes_open(file_path)
data = read_file(file_path)
if check_virus_by_signature(data, signatures):
fixed_data = replace_content_by_signatures(data, signatures).strip()
if fixed_data:
Expand All @@ -230,7 +204,7 @@ def replace_content_by_signatures(content, signatures):
str: The cleaned content.
"""
for signature in signatures:
content = re.sub(signature, "", content)
content = re.sub(*map(six.ensure_binary, [signature, "", content]))
return content


Expand All @@ -250,7 +224,7 @@ def check_virus_file_by_signature(file_path, signatures=None):
except (OSError, IOError): # noqa: UP024
return False
except UnicodeDecodeError:
data = _codes_open(file_path)
data = ""
return check_virus_by_signature(data, signatures)


Expand All @@ -266,7 +240,7 @@ def check_virus_by_signature(content, signatures=None):
"""
signatures = signatures or FILE_VIRUS_SIGNATURES
for signature in signatures:
if re.search(signature, content):
if re.search(*map(six.ensure_binary, [signature, content])):
return True
return False

Expand Down
7 changes: 6 additions & 1 deletion maya_umbrella/scanner.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from maya_umbrella.filesystem import get_backup_path
from maya_umbrella.filesystem import read_file
from maya_umbrella.maya_funs import cmds

from maya_umbrella._vendor.six import PY2

class MayaVirusScanner(object):
"""A class to scan and fix Maya files containing viruses.
Expand Down Expand Up @@ -55,8 +55,13 @@ def scan_files_from_pattern(self, pattern, glob_options=None):
glob_options (dict): Optional keyword arguments for the glob module.
if py3, we can pass a dict with the keyword arguments. {"recursive": True}
Raises:
ValueError: If py2, recursive is not supported.
"""
glob_options = glob_options or {}
if "recursive" in glob_options and PY2:
raise ValueError("recursive is not supported in python2")
os.environ.update(self._env)
return self.scan_files_from_list(glob.iglob(pattern, **glob_options))

Expand Down
15 changes: 14 additions & 1 deletion maya_umbrella/signatures.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,23 @@
# Import built-in modules
from collections import namedtuple


VirusSignature = namedtuple("VirusSignature", ["name", "signature"])

# https://regex101.com/r/0MNzF7/1
virus20240430_sig1 = VirusSignature("virus20240430", "python(.*);.+exec.+(pyCode).+;")
# https://regex101.com/r/2D14UA/1
virus20240430_sig2 = VirusSignature("virus20240430", r"^\['.+']")

JOB_SCRIPTS_VIRUS_SIGNATURES = [
"petri_dish_path.+cmds.internalVar.+",
"userSetup",
"fuckVirus",
virus20240430_sig1.signature,
virus20240430_sig2.signature,
]

FILE_VIRUS_SIGNATURES = [
"import vaccine",
"cmds.evalDeferred.*leukocyte.+",
virus20240430_sig1.signature,
]
2 changes: 1 addition & 1 deletion maya_umbrella/vaccines/vaccine2.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import os

# Import local modules
from maya_umbrella.constants import JOB_SCRIPTS_VIRUS_SIGNATURES
from maya_umbrella.signatures import JOB_SCRIPTS_VIRUS_SIGNATURES
from maya_umbrella.filesystem import check_virus_by_signature
from maya_umbrella.filesystem import check_virus_file_by_signature
from maya_umbrella.maya_funs import check_reference_node_exists
Expand Down
2 changes: 1 addition & 1 deletion maya_umbrella/vaccines/vaccine3.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import os

# Import local modules
from maya_umbrella.constants import JOB_SCRIPTS_VIRUS_SIGNATURES
from maya_umbrella.signatures import JOB_SCRIPTS_VIRUS_SIGNATURES
from maya_umbrella.filesystem import check_virus_by_signature
from maya_umbrella.filesystem import check_virus_file_by_signature
from maya_umbrella.maya_funs import cmds
Expand Down
10 changes: 0 additions & 10 deletions nox_actions/release.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,13 +102,3 @@ def pinned_requirements(path: Path) -> Iterator[Tuple[str, str]]:

# synchronize the contents
session.run("vendoring", "sync", ".")

# Determine the correct message
message = f"Upgrade {name} to {new_version}"

# Write our news fragment
news_file = Path("news") / (name + ".vendor.rst")
news_file.write_text(message + "\n") # "\n" appeases end-of-line-fixer

# Commit the changes
# release.commit_file(session, ".", message=message)
2 changes: 1 addition & 1 deletion noxfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,4 @@
nox.session(lint.lint_fix, name="lint-fix")
nox.session(release.make_install_zip, name="make-zip")
nox.session(codetest.pytest, name="pytest")
nox.session(release.vendoring)
nox.session(release.vendoring, name="vendoring")
2 changes: 1 addition & 1 deletion tests/test_filesystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import pytest

# Import local modules
from maya_umbrella.constants import FILE_VIRUS_SIGNATURES
from maya_umbrella.signatures import FILE_VIRUS_SIGNATURES
from maya_umbrella.filesystem import check_virus_file_by_signature
from maya_umbrella.filesystem import get_backup_path
from maya_umbrella.filesystem import get_maya_install_root
Expand Down
6 changes: 3 additions & 3 deletions tests/test_scanner.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@
from maya_umbrella.scanner import MayaVirusScanner


def test_scan_files_from_pattern(this_root):
scanner = MayaVirusScanner()
def test_scan_files_from_pattern(this_root, tmpdir):
scanner = MayaVirusScanner(output_path=str(tmpdir.join("test")))
root = os.path.join(this_root, "virus")
assert scanner.scan_files_from_pattern(os.path.join(root, "*.m[ab]")) == []


def test_scanner_from_file(this_root, tmpdir):
scanner = MayaVirusScanner()
scanner = MayaVirusScanner(output_path=str(tmpdir.join("test")))
root = os.path.join(this_root, "virus")
text_file = str(tmpdir.join("test.txt"))
write_file(text_file, "\n".join(glob.glob(os.path.join(root, "*.m[ab]"))))
Expand Down

0 comments on commit fc96b75

Please sign in to comment.