Skip to content

Commit

Permalink
Enable pyflake ruff lint rules (#1340)
Browse files Browse the repository at this point in the history
  • Loading branch information
huchenlei authored Dec 18, 2024
1 parent 445affd commit 7b812de
Show file tree
Hide file tree
Showing 12 changed files with 111 additions and 80 deletions.
23 changes: 23 additions & 0 deletions .github/workflows/ruff.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: Python Linting

on: [push, pull_request]

jobs:
ruff:
name: Run Ruff
runs-on: ubuntu-latest

steps:
- name: Checkout repository
uses: actions/checkout@v4

- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: 3.x

- name: Install Ruff
run: pip install ruff

- name: Run Ruff
run: ruff check .
6 changes: 3 additions & 3 deletions __init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@

if not os.path.exists(cli_mode_flag):
sys.path.append(os.path.join(os.path.dirname(__file__), "glob"))
import manager_server
import share_3rdparty
import manager_server # noqa: F401
import share_3rdparty # noqa: F401
WEB_DIRECTORY = "js"
else:
print(f"\n[ComfyUI-Manager] !! cli-only-mode is enabled !!\n")
print("\n[ComfyUI-Manager] !! cli-only-mode is enabled !!\n")

NODE_CLASS_MAPPINGS = {}
__all__ = ['NODE_CLASS_MAPPINGS']
Expand Down
17 changes: 8 additions & 9 deletions cm-cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
comfy_path = os.environ.get('COMFYUI_PATH')

if comfy_path is None:
print(f"\n[bold yellow]WARN: The `COMFYUI_PATH` environment variable is not set. Assuming `custom_nodes/ComfyUI-Manager/../../` as the ComfyUI path.[/bold yellow]", file=sys.stderr)
print("\n[bold yellow]WARN: The `COMFYUI_PATH` environment variable is not set. Assuming `custom_nodes/ComfyUI-Manager/../../` as the ComfyUI path.[/bold yellow]", file=sys.stderr)
comfy_path = os.path.abspath(os.path.join(comfyui_manager_path, '..', '..'))

startup_script_path = os.path.join(comfyui_manager_path, "startup-scripts")
Expand All @@ -48,7 +48,6 @@ def check_comfyui_hash():
repo = git.Repo(comfy_path)
core.comfy_ui_revision = len(list(repo.iter_commits('HEAD')))

comfy_ui_hash = repo.head.commit.hexsha
cm_global.variables['comfyui.revision'] = core.comfy_ui_revision

core.comfy_ui_commit_datetime = repo.head.commit.committed_datetime
Expand Down Expand Up @@ -141,7 +140,7 @@ def restore_dependencies(self):
total = len(node_paths)
i = 1
for x in node_paths:
print(f"----------------------------------------------------------------------------------------------------")
print("----------------------------------------------------------------------------------------------------")
print(f"Restoring [{i}/{total}]: {x}")
self.post_install(x)
i += 1
Expand Down Expand Up @@ -754,13 +753,13 @@ def cli_only_mode(
)):
cli_mode_flag = os.path.join(os.path.dirname(__file__), '.enable-cli-only-mode')
if mode.lower() == 'enable':
with open(cli_mode_flag, 'w') as file:
with open(cli_mode_flag, 'w'):
pass
print(f"\nINFO: `cli-only-mode` is enabled\n")
print("\nINFO: `cli-only-mode` is enabled\n")
elif mode.lower() == 'disable':
if os.path.exists(cli_mode_flag):
os.remove(cli_mode_flag)
print(f"\nINFO: `cli-only-mode` is disabled\n")
print("\nINFO: `cli-only-mode` is disabled\n")
else:
print(f"\n[bold red]Invalid value for cli-only-mode: {mode}[/bold red]\n")
exit(1)
Expand Down Expand Up @@ -896,7 +895,7 @@ def extract_infos(msg):
elif 'APPLY SNAPSHOT: False' in x:
is_failed = True

print(f"Restore snapshot.")
print("Restore snapshot.")
cmd_str = [sys.executable, git_script_path, '--apply-snapshot', snapshot_path] + extras
output = subprocess.check_output(cmd_str, cwd=custom_nodes_path, text=True)
msg_lines = output.split('\n')
Expand Down Expand Up @@ -935,7 +934,7 @@ def restore_dependencies():
total = len(node_paths)
i = 1
for x in node_paths:
print(f"----------------------------------------------------------------------------------------------------")
print("----------------------------------------------------------------------------------------------------")
print(f"Restoring [{i}/{total}]: {x}")
cm_ctx.post_install(x)
i += 1
Expand Down Expand Up @@ -1028,4 +1027,4 @@ def export_custom_node_ids(
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(app())

print(f"")
print("")
2 changes: 1 addition & 1 deletion git_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def download_url(url, dest_folder, filename=None):
working_directory = os.getcwd()

if os.path.basename(working_directory) != 'custom_nodes':
print(f"WARN: This script should be executed in custom_nodes dir")
print("WARN: This script should be executed in custom_nodes dir")
print(f"DBG: INFO {working_directory}")
print(f"DBG: INFO {sys.argv}")
# exit(-1)
Expand Down
18 changes: 9 additions & 9 deletions glob/manager_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
sys.path.append(glob_path)

import cm_global
from manager_util import *
from manager_util import PIPFixer, StrictVersion

version = [2, 55, 5]
version_str = f"V{version[0]}.{version[1]}" + (f'.{version[2]}' if len(version) > 2 else '')
Expand Down Expand Up @@ -116,8 +116,8 @@ def get_installed_packages():
continue

pip_map[y[0]] = y[1]
except subprocess.CalledProcessError as e:
print(f"[ComfyUI-Manager] Failed to retrieve the information of installed pip packages.")
except subprocess.CalledProcessError:
print("[ComfyUI-Manager] Failed to retrieve the information of installed pip packages.")
return set()

return pip_map
Expand Down Expand Up @@ -351,7 +351,7 @@ def try_install_script(url, repo_path, install_cmd, instant_execution=False):
if comfy_ui_commit_datetime.date() < comfy_ui_required_commit_datetime.date():
print("\n\n###################################################################")
print(f"[WARN] ComfyUI-Manager: Your ComfyUI version ({comfy_ui_revision})[{comfy_ui_commit_datetime.date()}] is too old. Please update to the latest version.")
print(f"[WARN] The extension installation feature may not work properly in the current installed ComfyUI version on Windows environment.")
print("[WARN] The extension installation feature may not work properly in the current installed ComfyUI version on Windows environment.")
print("###################################################################\n\n")
except:
pass
Expand Down Expand Up @@ -390,7 +390,7 @@ def __win_check_git_update(path, do_fetch=False, do_update=False):
output, _ = process.communicate()
output = output.decode('utf-8').strip()
except Exception:
print(f'[ComfyUI-Manager] failed to fixing')
print('[ComfyUI-Manager] failed to fixing')

if 'detected dubious' in output:
print(f'\n[ComfyUI-Manager] Failed to fixing repository setup. Please execute this command on cmd: \n'
Expand Down Expand Up @@ -468,7 +468,7 @@ def execute_install_script(url, repo_path, lazy_mode=False, instant_execution=Fa
pip_fixer.fix_broken()

if os.path.exists(install_script_path):
print(f"Install: install script")
print("Install: install script")
install_cmd = [sys.executable, "install.py"]
try_install_script(url, repo_path, install_cmd, instant_execution=instant_execution)

Expand Down Expand Up @@ -663,7 +663,7 @@ async def get_data(uri, silent=False):

json_obj = json.loads(json_text)
if not silent:
print(f" [DONE]")
print(" [DONE]")
return json_obj


Expand Down Expand Up @@ -942,7 +942,7 @@ def update_path(repo_path, instant_execution=False):
remote.fetch()
except Exception as e:
if 'detected dubious' in str(e):
print(f"[ComfyUI-Manager] Try fixing 'dubious repository' error on 'ComfyUI' repository")
print("[ComfyUI-Manager] Try fixing 'dubious repository' error on 'ComfyUI' repository")
safedir_path = comfy_path.replace('\\', '/')
subprocess.run(['git', 'config', '--global', '--add', 'safe.directory', safedir_path])
try:
Expand Down Expand Up @@ -1084,7 +1084,7 @@ def get_current_snapshot():
repo_path = comfy_path

if not os.path.exists(os.path.join(repo_path, '.git')):
print(f"ComfyUI update fail: The installed ComfyUI does not have a Git repository.")
print("ComfyUI update fail: The installed ComfyUI does not have a Git repository.")
return {}

repo = git.Repo(repo_path)
Expand Down
52 changes: 26 additions & 26 deletions glob/manager_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import re
import shutil
import git
from datetime import datetime

from server import PromptServer
import manager_core as core
Expand All @@ -20,9 +21,9 @@

comfy_ui_hash = "-"

SECURITY_MESSAGE_MIDDLE_OR_BELOW = f"ERROR: To use this action, a security_level of `middle or below` is required. Please contact the administrator.\nReference: https://github.com/ltdrdata/ComfyUI-Manager#security-policy"
SECURITY_MESSAGE_NORMAL_MINUS = f"ERROR: To use this feature, you must either set '--listen' to a local IP and set the security level to 'normal-' or lower, or set the security level to 'middle' or 'weak'. Please contact the administrator.\nReference: https://github.com/ltdrdata/ComfyUI-Manager#security-policy"
SECURITY_MESSAGE_GENERAL = f"ERROR: This installation is not allowed in this security_level. Please contact the administrator.\nReference: https://github.com/ltdrdata/ComfyUI-Manager#security-policy"
SECURITY_MESSAGE_MIDDLE_OR_BELOW = "ERROR: To use this action, a security_level of `middle or below` is required. Please contact the administrator.\nReference: https://github.com/ltdrdata/ComfyUI-Manager#security-policy"
SECURITY_MESSAGE_NORMAL_MINUS = "ERROR: To use this feature, you must either set '--listen' to a local IP and set the security level to 'normal-' or lower, or set the security level to 'middle' or 'weak'. Please contact the administrator.\nReference: https://github.com/ltdrdata/ComfyUI-Manager#security-policy"
SECURITY_MESSAGE_GENERAL = "ERROR: This installation is not allowed in this security_level. Please contact the administrator.\nReference: https://github.com/ltdrdata/ComfyUI-Manager#security-policy"

def handle_stream(stream, prefix):
stream.reconfigure(encoding=locale.getpreferredencoding(), errors='replace')
Expand Down Expand Up @@ -196,7 +197,7 @@ def print_comfyui_version():

del cm_global.variables['cm.on_revision_detected_handler']
else:
print(f"[ComfyUI-Manager] Some features are restricted due to your ComfyUI being outdated.")
print("[ComfyUI-Manager] Some features are restricted due to your ComfyUI being outdated.")
# <--

if current_branch == "master":
Expand Down Expand Up @@ -243,7 +244,6 @@ def setup_environment():

# Expand Server api

import server
from aiohttp import web
import aiohttp
import json
Expand Down Expand Up @@ -289,7 +289,7 @@ def resolve_custom_node(save_path):
if folder_paths.folder_names_and_paths.get("text_encoders"):
base_model = folder_paths.folder_names_and_paths["text_encoders"][0][0]
else:
print(f"[ComfyUI-Manager] Your ComfyUI is outdated version.")
print("[ComfyUI-Manager] Your ComfyUI is outdated version.")
base_model = folder_paths.folder_names_and_paths["clip"][0][0] # outdated version
elif model_type == "VAE":
base_model = folder_paths.folder_names_and_paths["vae"][0][0]
Expand All @@ -313,7 +313,7 @@ def resolve_custom_node(save_path):
if folder_paths.folder_names_and_paths.get("diffusion_models"):
base_model = folder_paths.folder_names_and_paths["diffusion_models"][0][1]
else:
print(f"[ComfyUI-Manager] Your ComfyUI is outdated version.")
print("[ComfyUI-Manager] Your ComfyUI is outdated version.")
base_model = folder_paths.folder_names_and_paths["unet"][0][0] # outdated version
else:
base_model = os.path.join(models_base, "etc")
Expand Down Expand Up @@ -345,15 +345,15 @@ def process_custom_node(item):
executor.submit(process_custom_node, item)

if do_fetch:
print(f"\x1b[2K\rFetching done.")
print("\x1b[2K\rFetching done.")
elif do_update:
update_exists = any(item['installed'] == 'Update' for item in json_obj['custom_nodes'])
if update_exists:
print(f"\x1b[2K\rUpdate done.")
print("\x1b[2K\rUpdate done.")
else:
print(f"\x1b[2K\rAll extensions are already up-to-date.")
print("\x1b[2K\rAll extensions are already up-to-date.")
elif do_update_check:
print(f"\x1b[2K\rUpdate check done.")
print("\x1b[2K\rUpdate check done.")


def nickname_filter(json_obj):
Expand Down Expand Up @@ -655,7 +655,7 @@ async def remove_snapshot(request):


@PromptServer.instance.routes.get("/snapshot/restore")
async def remove_snapshot(request):
async def restore_snapshot(request):
if not is_allowed_security_level('middle'):
print(SECURITY_MESSAGE_MIDDLE_OR_BELOW)
return web.Response(status=403)
Expand Down Expand Up @@ -871,7 +871,7 @@ async def install_custom_node(request):
core.clear_pip_cache()

if res:
print(f"After restarting ComfyUI, please refresh the browser.")
print("After restarting ComfyUI, please refresh the browser.")
return web.json_response({}, content_type='application/json')

return web.Response(status=400)
Expand Down Expand Up @@ -913,7 +913,7 @@ async def fix_custom_node(request):
core.try_install_script(json_data['files'][0], ".", install_cmd)

if res:
print(f"After restarting ComfyUI, please refresh the browser.")
print("After restarting ComfyUI, please refresh the browser.")
return web.json_response({}, content_type='application/json')

return web.Response(status=400)
Expand All @@ -929,14 +929,14 @@ async def install_custom_node_git_url(request):
res = core.gitclone_install([url])

if res:
print(f"After restarting ComfyUI, please refresh the browser.")
print("After restarting ComfyUI, please refresh the browser.")
return web.Response(status=200)

return web.Response(status=400)


@PromptServer.instance.routes.post("/customnode/install/pip")
async def install_custom_node_git_url(request):
async def install_custom_node_pip(request):
if not is_allowed_security_level('high'):
print(SECURITY_MESSAGE_NORMAL_MINUS)
return web.Response(status=403)
Expand Down Expand Up @@ -969,7 +969,7 @@ async def uninstall_custom_node(request):
res = core.gitclone_uninstall(json_data['files'])

if res:
print(f"After restarting ComfyUI, please refresh the browser.")
print("After restarting ComfyUI, please refresh the browser.")
return web.json_response({}, content_type='application/json')

return web.Response(status=400)
Expand All @@ -995,21 +995,21 @@ async def update_custom_node(request):
core.clear_pip_cache()

if res:
print(f"After restarting ComfyUI, please refresh the browser.")
print("After restarting ComfyUI, please refresh the browser.")
return web.json_response({}, content_type='application/json')

return web.Response(status=400)


@PromptServer.instance.routes.get("/comfyui_manager/update_comfyui")
async def update_comfyui(request):
print(f"Update ComfyUI")
print("Update ComfyUI")

try:
repo_path = os.path.dirname(folder_paths.__file__)
res = core.update_path(repo_path)
if res == "fail":
print(f"ComfyUI update fail: The installed ComfyUI does not have a Git repository.")
print("ComfyUI update fail: The installed ComfyUI does not have a Git repository.")
return web.Response(status=400)
elif res == "updated":
return web.Response(status=201)
Expand Down Expand Up @@ -1220,9 +1220,9 @@ async def get_notice(request):

try:
if core.comfy_ui_commit_datetime == datetime(1900, 1, 1, 0, 0, 0):
markdown_content = f'<P style="text-align: center; color:red; background-color:white; font-weight:bold">Your ComfyUI isn\'t git repo.</P>' + markdown_content
markdown_content = '<P style="text-align: center; color:red; background-color:white; font-weight:bold">Your ComfyUI isn\'t git repo.</P>' + markdown_content
elif core.comfy_ui_required_commit_datetime.date() > core.comfy_ui_commit_datetime.date():
markdown_content = f'<P style="text-align: center; color:red; background-color:white; font-weight:bold">Your ComfyUI is too OUTDATED!!!</P>' + markdown_content
markdown_content = '<P style="text-align: center; color:red; background-color:white; font-weight:bold">Your ComfyUI is too OUTDATED!!!</P>' + markdown_content
except:
pass

Expand All @@ -1241,17 +1241,17 @@ def restart(self):

try:
sys.stdout.close_log()
except Exception as e:
except Exception:
pass

if '__COMFY_CLI_SESSION__' in os.environ:
with open(os.path.join(os.environ['__COMFY_CLI_SESSION__'] + '.reboot'), 'w') as file:
with open(os.path.join(os.environ['__COMFY_CLI_SESSION__'] + '.reboot'), 'w'):
pass

print(f"\nRestarting...\n\n")
print("\nRestarting...\n\n")
exit(0)

print(f"\nRestarting... [Legacy Mode]\n\n")
print("\nRestarting... [Legacy Mode]\n\n")

sys_argv = sys.argv.copy()
if '--windows-standalone-build' in sys_argv:
Expand Down
Loading

0 comments on commit 7b812de

Please sign in to comment.