refactor: ruff

This commit is contained in:
Dr.Lt.Data 2024-12-18 12:30:47 +09:00
parent 222254896c
commit 46a6afcc19
7 changed files with 25 additions and 30 deletions

View File

@ -3,10 +3,8 @@ import sys
import traceback import traceback
import json import json
import asyncio import asyncio
import subprocess
import concurrent import concurrent
import threading import threading
import yaml
from typing import Optional from typing import Optional
import typer import typer

View File

@ -15,7 +15,7 @@ from git.remote import RemoteProgress
comfy_path = os.environ.get('COMFYUI_PATH') comfy_path = os.environ.get('COMFYUI_PATH')
if comfy_path is None: 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(os.path.dirname(__file__), '..', '..')) comfy_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))

View File

@ -1,8 +1,7 @@
from manager_util import *
import zipfile
import requests import requests
from dataclasses import dataclass from dataclasses import dataclass
from typing import List from typing import List
import manager_util
base_url = "https://api.comfy.org" base_url = "https://api.comfy.org"
@ -10,7 +9,7 @@ base_url = "https://api.comfy.org"
async def get_cnr_data(page=1, limit=1000, cache_mode=True): async def get_cnr_data(page=1, limit=1000, cache_mode=True):
try: try:
uri = f'{base_url}/nodes?page={page}&limit={limit}' uri = f'{base_url}/nodes?page={page}&limit={limit}'
json_obj = await get_data_with_cache(uri, cache_mode=cache_mode) json_obj = await manager_util.get_data_with_cache(uri, cache_mode=cache_mode)
for v in json_obj['nodes']: for v in json_obj['nodes']:
if 'latest_version' not in v: if 'latest_version' not in v:
@ -19,7 +18,7 @@ async def get_cnr_data(page=1, limit=1000, cache_mode=True):
return json_obj['nodes'] return json_obj['nodes']
except: except:
res = {} res = {}
print(f"Cannot connect to comfyregistry.") print("Cannot connect to comfyregistry.")
return res return res

View File

@ -112,8 +112,8 @@ def check_invalid_nodes():
check(disabled_dir) check(disabled_dir)
if len(invalid_nodes): if len(invalid_nodes):
print(f"\n-------------------- ComfyUI-Manager invalid nodes notice ----------------") print("\n-------------------- ComfyUI-Manager invalid nodes notice ----------------")
print(f"\nNodes requiring reinstallation have been detected:\n(Directly delete the corresponding path and reinstall.)\n") print("\nNodes requiring reinstallation have been detected:\n(Directly delete the corresponding path and reinstall.)\n")
for x in invalid_nodes.values(): for x in invalid_nodes.values():
print(x) print(x)
@ -780,7 +780,7 @@ class UnifiedManager:
if os.path.exists(install_script_path) and install_script_path not in self.processed_install: if os.path.exists(install_script_path) and install_script_path not in self.processed_install:
self.processed_install.add(install_script_path) self.processed_install.add(install_script_path)
print(f"Install: install script") print("Install: install script")
install_cmd = [sys.executable, "install.py"] install_cmd = [sys.executable, "install.py"]
return try_install_script(url, repo_path, install_cmd, instant_execution=instant_execution) return try_install_script(url, repo_path, install_cmd, instant_execution=instant_execution)
@ -1230,16 +1230,16 @@ class UnifiedManager:
remote.fetch() remote.fetch()
except Exception as e: except Exception as e:
if 'detected dubious' in str(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('\\', '/') safedir_path = comfy_path.replace('\\', '/')
subprocess.run(['git', 'config', '--global', '--add', 'safe.directory', safedir_path]) subprocess.run(['git', 'config', '--global', '--add', 'safe.directory', safedir_path])
try: try:
remote.fetch() remote.fetch()
except Exception: except Exception:
print(f"\n[ComfyUI-Manager] Failed to fixing repository setup. Please execute this command on cmd: \n" print("\n[ComfyUI-Manager] Failed to fixing repository setup. Please execute this command on cmd: \n"
f"-----------------------------------------------------------------------------------------\n" "-----------------------------------------------------------------------------------------\n"
f'git config --global --add safe.directory "{safedir_path}"\n' f'git config --global --add safe.directory "{safedir_path}"\n'
f"-----------------------------------------------------------------------------------------\n") "-----------------------------------------------------------------------------------------\n")
commit_hash = repo.head.commit.hexsha commit_hash = repo.head.commit.hexsha
remote_commit_hash = repo.refs[f'{remote_name}/{branch_name}'].object.hexsha remote_commit_hash = repo.refs[f'{remote_name}/{branch_name}'].object.hexsha
@ -1360,7 +1360,7 @@ class UnifiedManager:
await self.reload('cache') await self.reload('cache')
await self.get_custom_nodes('default', 'cache') await self.get_custom_nodes('default', 'cache')
print(f"Migration: STAGE 1") print("Migration: STAGE 1")
moves = [] moves = []
# migrate nightly inactive # migrate nightly inactive
@ -1371,7 +1371,7 @@ class UnifiedManager:
new_path = os.path.join(custom_nodes_path, '.disabled', f"{x}@nightly") new_path = os.path.join(custom_nodes_path, '.disabled', f"{x}@nightly")
moves.append((v, new_path)) moves.append((v, new_path))
print(f"Migration: STAGE 2") print("Migration: STAGE 2")
# migrate active nodes # migrate active nodes
for x, v in self.active_nodes.items(): for x, v in self.active_nodes.items():
if v[0] not in ['nightly']: if v[0] not in ['nightly']:
@ -1385,7 +1385,7 @@ class UnifiedManager:
self.reserve_migration(moves) self.reserve_migration(moves)
print(f"DONE (Migration reserved)") print("DONE (Migration reserved)")
unified_manager = UnifiedManager() unified_manager = UnifiedManager()
@ -2678,7 +2678,7 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
for k, v in unified_manager.repo_cnr_map.items(): for k, v in unified_manager.repo_cnr_map.items():
cnr_repo_map[v['id']] = k cnr_repo_map[v['id']] = k
print(f"Restore snapshot.") print("Restore snapshot.")
postinstalls = [] postinstalls = []
@ -2729,7 +2729,7 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
if hasattr(ps, 'postinstall'): if hasattr(ps, 'postinstall'):
postinstalls.append(ps.postinstall) postinstalls.append(ps.postinstall)
else: else:
print(f"cm-cli: unexpected [0001]") print("cm-cli: unexpected [0001]")
# for nightly restore # for nightly restore
git_info = info.get('git_custom_nodes') git_info = info.get('git_custom_nodes')

View File

@ -17,7 +17,7 @@ from server import PromptServer
import manager_core as core import manager_core as core
import manager_util import manager_util
import cm_global import cm_global
from datetime import datetime
print(f"### Loading: ComfyUI-Manager ({core.version_str})") print(f"### Loading: ComfyUI-Manager ({core.version_str})")
@ -482,7 +482,7 @@ async def update_all(request):
else: else:
status = 201 status = 201
print(f"\nDone.") print("\nDone.")
return web.json_response(res, status=status, content_type='application/json') return web.json_response(res, status=status, content_type='application/json')
except: except:
traceback.print_exc() traceback.print_exc()
@ -920,7 +920,7 @@ async def fix_custom_node(request):
res = core.unified_manager.unified_fix(node_name, node_ver) res = core.unified_manager.unified_fix(node_name, node_ver)
if res.result: if res.result:
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.json_response({}, content_type='application/json')
print(f"ERROR: An error occurred while fixing '{node_name}@{node_ver}'.") print(f"ERROR: An error occurred while fixing '{node_name}@{node_ver}'.")
@ -940,7 +940,7 @@ async def install_custom_node_git_url(request):
print(f"Already installed: '{res.target}'") print(f"Already installed: '{res.target}'")
return web.Response(status=200) return web.Response(status=200)
elif res.result: elif res.result:
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=200)
print(res.msg) print(res.msg)
@ -979,7 +979,7 @@ async def uninstall_custom_node(request):
res = core.unified_manager.unified_uninstall(node_name, is_unknown) res = core.unified_manager.unified_uninstall(node_name, is_unknown)
if res.result: if res.result:
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.json_response({}, content_type='application/json')
print(f"ERROR: An error occurred while uninstalling '{node_name}'.") print(f"ERROR: An error occurred while uninstalling '{node_name}'.")
@ -1006,7 +1006,7 @@ async def update_custom_node(request):
core.clear_pip_cache() core.clear_pip_cache()
if res.result: if res.result:
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.json_response({}, content_type='application/json')
print(f"ERROR: An error occurred while updating '{node_name}'.") print(f"ERROR: An error occurred while updating '{node_name}'.")
@ -1080,7 +1080,7 @@ async def disable_node(request):
@routes.get("/manager/migrate_unmanaged_nodes") @routes.get("/manager/migrate_unmanaged_nodes")
async def migrate_unmanaged_nodes(request): async def migrate_unmanaged_nodes(request):
print(f"[ComfyUI-Manager] Migrating unmanaged nodes...") print("[ComfyUI-Manager] Migrating unmanaged nodes...")
await core.unified_manager.migrate_unmanaged_nodes() await core.unified_manager.migrate_unmanaged_nodes()
print("Done.") print("Done.")
return web.Response(status=200) return web.Response(status=200)

View File

@ -1,5 +1,3 @@
import traceback
import aiohttp import aiohttp
import json import json
import threading import threading
@ -115,7 +113,7 @@ async def get_data(uri, silent=False):
json_obj = json.loads(json_text) json_obj = json.loads(json_text)
if not silent: if not silent:
print(f" [DONE]") print(" [DONE]")
return json_obj return json_obj

View File

@ -457,7 +457,7 @@ if os.path.exists(restore_snapshot_path):
else: else:
print(prefix, msg, end="") print(prefix, msg, end="")
print(f"[ComfyUI-Manager] Restore snapshot.") print("[ComfyUI-Manager] Restore snapshot.")
new_env = os.environ.copy() new_env = os.environ.copy()
new_env["COMFYUI_PATH"] = comfy_path new_env["COMFYUI_PATH"] = comfy_path