Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b03a75239f | ||
|
|
fdc9c1177d | ||
|
|
6c22515d55 | ||
|
|
86634380db | ||
|
|
aa58d0ff43 | ||
|
|
24b27b7ea6 | ||
|
|
e2124a8585 | ||
|
|
0f7d5f588b | ||
|
|
d972b17712 | ||
|
|
d917f19598 | ||
|
|
de0a6111aa | ||
|
|
6fe0d72dc4 | ||
|
|
9c069c13c5 |
+152
@@ -7,6 +7,158 @@ and this project adheres to [Semantic Versioning 2.0.0](https://semver.org/spec/
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
|
||||
- `dependency_management = off` turns off the changes that the Manager makes
|
||||
to Python packages on its own. On a Python that cannot be changed, such as
|
||||
one of Nix, Guix or a distribution, the Manager ran pip at every start and
|
||||
after an install. It could uninstall `comfy`, install torch again and
|
||||
install the packages of `pip_auto_fix.list`, and with
|
||||
`use_unified_resolver = True` the startup batch of the resolver installed
|
||||
packages (#2851). With `dependency_management = off` in the `[default]`
|
||||
section of `config.ini`, or `COMFYUI_MANAGER_DEPENDENCY_MANAGEMENT=off`,
|
||||
none of this runs, in the server or in `cm-cli`, and installs use pip for
|
||||
each nodepack in place of the resolver. The environment variable wins over
|
||||
`config.ini`. An install or update that is asked for, also one applied at
|
||||
the next restart, still installs its requirements, and the `install.py` of
|
||||
a nodepack still runs. The setting is on by default, and while it is unset
|
||||
nothing changes.
|
||||
|
||||
### Changed
|
||||
|
||||
- The log file has no color codes of the console. The Manager writes what
|
||||
ComfyUI prints to the console and to the log file, `comfyui.log` in the
|
||||
user directory. The color codes of the console, such as `ESC[32m`, went
|
||||
into the file as well, where an editor or `grep` shows them as text
|
||||
(#3466). They are now left out of the file, and the console keeps its
|
||||
colors. To keep them in the file as before, set
|
||||
`strip_ansi_file_logging = false` in `config.ini`.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Report the `desktop-linux` form factor to the registry for Desktop installs
|
||||
on Linux, which previously reported `other`.
|
||||
|
||||
- `--mode remote` reads the channel when the Manager is installed as a pip
|
||||
package. On such an install every mode read the cached list, or the list
|
||||
that comes with the package, so a nodepack that was added to the channel
|
||||
after the package was built did not show (#3590). Remote mode now reads the
|
||||
list from the channel and caches it, in `cm-cli` and in the server. When
|
||||
the channel cannot be read, a message says so and the list is the one from
|
||||
before: the cached list, else the list of the package. The other modes and
|
||||
`network_mode = offline` are unchanged.
|
||||
|
||||
- The legacy Model Manager finds a model in a subfolder of an extra model path.
|
||||
A model whose folder in the list has a subfolder, such as `checkpoints/SD1.5`,
|
||||
was shown as not installed when its file was in that subfolder of a folder
|
||||
that `extra_model_paths.yaml` adds (#1844). The Model Manager now also asks
|
||||
ComfyUI where the file is. ComfyUI looks in every folder it has for the first
|
||||
part of the path, the extra ones included, so the model is shown as
|
||||
installed. A model that was shown as installed before still is.
|
||||
|
||||
- A download through aria2 works again, and one that fails is reported as
|
||||
failed. With `COMFYUI_MANAGER_ARIA2_SERVER` set, the install of a registry
|
||||
nodepack or of a model failed with `No module named 'manager_core'` (#3064,
|
||||
#3246). The download goes through aria2 again. The install waits for a
|
||||
download that aria2 has queued, and fails with the error of aria2 when
|
||||
aria2 fails the download. It also fails when the file is not where ComfyUI
|
||||
reads it, as when aria2 does not see the ComfyUI folder as `/`
|
||||
(`docs/en/use_aria2.md`): the terminal names the folder that aria2 wrote
|
||||
to.
|
||||
|
||||
- A conflict in the legacy Custom Nodes Manager counts only enabled
|
||||
nodepacks. The Nodes column counted a conflict for every node name that
|
||||
another nodepack in the list also has, whether that nodepack is installed
|
||||
or not. An enabled nodepack showed `N conflicts` for nodepacks that are
|
||||
disabled or not installed, which ComfyUI does not load (#3092, #3273). A
|
||||
conflict now counts only another enabled nodepack. An enabled nodepack
|
||||
shows `N conflicts`, and its node list says `Conflict with enabled packs`.
|
||||
A disabled or not installed nodepack shows `N potential conflicts` for the
|
||||
enabled nodepacks it would conflict with, and its node list says
|
||||
`Potential conflict if installed/enabled with`. In the Nodes column
|
||||
`N potential conflicts` takes two lines. Two nodepacks that are both not
|
||||
enabled show nothing for each other. The Nodes Manager does not run this
|
||||
code.
|
||||
|
||||
- An install without a version enables a disabled registry nodepack, and
|
||||
Enable fails for one the registry data does not list. An install without a
|
||||
version did not see a registry nodepack that was disabled: with the nodepack
|
||||
disabled at 1.0.0 and the registry at 2.0.0, `cm-cli install <id>` installed
|
||||
2.0.0. It now enables 1.0.0, with no download (#3469, #3528). Where the
|
||||
folder of the newest disabled version is gone, it enables the newest version
|
||||
whose folder is there. **Enable** reported success for a disabled nodepack
|
||||
that the registry data does not list: nothing was enabled. It now reports
|
||||
`Failed to enable: '<id>'`, and the terminal says
|
||||
`Specified inactive node not exists: <id>`.
|
||||
|
||||
- A nodepack that two node mappings name shows all its nodes in the legacy
|
||||
Custom Nodes Manager, and the list is drawn. Two node mappings can name one
|
||||
nodepack, one by its id or git URL and one by its `title_aux`. The second
|
||||
mapping replaced the nodes of the first. When another nodepack had a node
|
||||
of the first mapping, the page failed with `TypeError: Cannot read
|
||||
properties of undefined (reading 'conflicts')` and drew no list (#2502). A
|
||||
node that both mappings name showed a conflict with no other nodepack, or
|
||||
each other nodepack twice. The Nodes column and the node list of such a
|
||||
nodepack now have the nodes of both mappings, and each conflict names each
|
||||
other nodepack once. A row can therefore list more nodes than before. The
|
||||
Nodes Manager does not run this code.
|
||||
|
||||
- An install from a Git URL installs the dependencies when Windows cannot
|
||||
read `requirements.txt`. An install of a nodepack from a Git URL
|
||||
(**Install via Git URL** of the legacy Custom Nodes Manager,
|
||||
`cm-cli install <url>`, `cm-cli install-deps`) read its `requirements.txt`
|
||||
in the encoding of the locale, which on Windows is the ANSI code page. A
|
||||
UTF-8 file with a Chinese or Korean comment failed with
|
||||
`UnicodeDecodeError`, and the nodepack was cloned without its dependencies
|
||||
(#3520). When the locale cannot read the file, the install now reads it in
|
||||
the encoding that `chardet` names, if every line is printable ASCII outside
|
||||
its comment. Otherwise, as for a file that is not text or a requirement
|
||||
with a non-ASCII path, it fails with the same error as before. Such a
|
||||
failure no longer installs the lines in front of the byte it fails on.
|
||||
|
||||
- A nodepack that only the registry lists shows Update in the legacy Custom
|
||||
Nodes Manager when the registry has a newer version. A nodepack that is in
|
||||
the registry and not in the node list never showed **Update** there, and
|
||||
the Update filter did not list it (#3220, #3261). The row showed
|
||||
**Try update**, which did update it, but nothing said that an update was
|
||||
there. The row of an enabled nodepack of this kind now shows **Update**,
|
||||
and the Update filter lists it. A nodepack installed as nightly gets no
|
||||
**Update** this way, as for a nodepack of the node list. When such a
|
||||
nodepack failed to import and has a newer version, its row shows
|
||||
**Update** in place of `IMPORT FAILED ↗` and **Try fix**, as the row of a
|
||||
nodepack of the node list already did. The Import Failed filter still
|
||||
lists it. The Nodes Manager already offered **Update** for such a nodepack
|
||||
and is not changed.
|
||||
|
||||
- The PyTorch restore after a nodepack installs the builds that were installed
|
||||
before. When a nodepack changed torch or torchvision and the torch from
|
||||
before had no local label, Manager installed the newest releases, and
|
||||
through uv nothing. For a torch with a label it installed the versions of a
|
||||
table that ends at 2.7.0, or the newest nightly build. A nodepack that
|
||||
removed torch, or removed torchvision and left torch as it was, ended the
|
||||
restore with `Failed to restore PyTorch`. Now Manager installs each of
|
||||
torch, torchvision and torchaudio that is not the build it was before as
|
||||
that build, such as `torch===2.14.0+cu130` from
|
||||
`https://download.pytorch.org/whl/cu130`. A torchvision or torchaudio whose
|
||||
build cannot be had is replaced by one that fits that torch. A package that
|
||||
this torch requires is installed again with it when another package wrote
|
||||
over one of its files, as a torch of another CUDA version does with the CUDA
|
||||
libraries. A last command resolves torch with torchvision and torchaudio:
|
||||
what fits that torch stays, what does not is replaced, and a dependency that
|
||||
the nodepack removed comes back. Then Manager checks in a separate process
|
||||
that torch, torchvision and torchaudio work. For a torch that does not, the
|
||||
packages it requires that lack a file are installed again. A torchvision or
|
||||
torchaudio that does not is installed again from torch's index. What still
|
||||
does not work is named in an ERROR line. When the torch from before cannot
|
||||
be had, Manager restores by its version table as before; the table now goes
|
||||
up to 2.15.0. With uv, the command that installs torch, or a changed
|
||||
torchvision or torchaudio, at its build is sent only in a form that a dry
|
||||
run resolved, and once more when it fails while it installs. For safety the
|
||||
restore does not start when the disk has less free space than it can take:
|
||||
twice the size of what it installs again with pip, one and a half times with
|
||||
uv. pip runs without its cache during the restore, so that it holds each
|
||||
wheel once.
|
||||
|
||||
## [4.5] - 2026-11-30
|
||||
|
||||
### Removed
|
||||
|
||||
@@ -209,6 +209,7 @@ The following settings are applied based on the section marked as `is_default`.
|
||||
[default]
|
||||
git_exe = <Manually specify the path to the git executable. If left empty, the default git executable path will be used.>
|
||||
use_uv = <Use uv instead of pip for dependency installation.>
|
||||
dependency_management = <on|off; defaults to on. Disable automatic startup package changes in externally-managed Python environments.>
|
||||
default_cache_as_channel_url = <Determines whether to retrieve the DB designated as channel_url at startup>
|
||||
bypass_ssl = <Set to True if SSL errors occur to disable SSL.>
|
||||
file_logging = <Configure whether to create a log file used by ComfyUI-Manager.>
|
||||
@@ -227,7 +228,11 @@ The following settings are applied based on the section marked as `is_default`.
|
||||
- public: An environment that uses a typical public network.
|
||||
- private: An environment that uses a closed network, where a private node DB is configured via `channel_url`. (Uses cache if available)
|
||||
- offline: An environment that does not use any external connections when using an offline network. (Uses cache if available)
|
||||
- personal_cloud: Applies relaxed security features in cloud environments such as Google Colab or Runpod, where strong security is not required.
|
||||
- personal_cloud: Applies relaxed security features in cloud environments such as Google Colab or Runpod, where strong security is not required.
|
||||
|
||||
* `dependency_management = off` skips PIPFixer auto-healing (in the server and in cm-cli) and the startup unified dependency resolver; with the resolver skipped, installs use per-node pip. Read-only package inventory operations remain available.
|
||||
- `COMFYUI_MANAGER_DEPENDENCY_MANAGEMENT=on|off` overrides the config setting. `false`, `0`, `no`, and `disabled` also disable it (case-insensitive).
|
||||
- Explicit install/update commands, including those applied at the next restart, and custom-node `install.py` scripts remain available and can modify the environment. This setting is not a sandbox; externally-managed installations should use `--no-deps` for explicit node operations where supported and provision dependencies separately.
|
||||
|
||||
|
||||
## Additional Feature
|
||||
|
||||
@@ -20,6 +20,29 @@ lock = asyncio.Lock()
|
||||
|
||||
is_cache_loading = False
|
||||
|
||||
def get_form_factor():
|
||||
"""Form factor reported to the registry, based on environment and platform."""
|
||||
is_desktop = bool(os.environ.get('__COMFYUI_DESKTOP_VERSION__'))
|
||||
system = platform.system().lower()
|
||||
|
||||
if is_desktop:
|
||||
if system == 'windows':
|
||||
return 'desktop-win'
|
||||
if system == 'darwin':
|
||||
return 'desktop-mac'
|
||||
if system == 'linux':
|
||||
return 'desktop-linux'
|
||||
return 'other'
|
||||
|
||||
if system == 'windows':
|
||||
return 'git-windows'
|
||||
if system == 'darwin':
|
||||
return 'git-mac'
|
||||
if system == 'linux':
|
||||
return 'git-linux'
|
||||
return 'other'
|
||||
|
||||
|
||||
async def get_cnr_data(cache_mode=True, dont_wait=True):
|
||||
try:
|
||||
return await _get_cnr_data(cache_mode, dont_wait)
|
||||
@@ -39,12 +62,7 @@ async def _get_cnr_data(cache_mode=True, dont_wait=True):
|
||||
full_nodes = {}
|
||||
|
||||
|
||||
# Determine form factor based on environment and platform
|
||||
is_desktop = bool(os.environ.get('__COMFYUI_DESKTOP_VERSION__'))
|
||||
system = platform.system().lower()
|
||||
is_windows = system == 'windows'
|
||||
is_mac = system == 'darwin'
|
||||
is_linux = system == 'linux'
|
||||
|
||||
# Get ComfyUI version tag
|
||||
if is_desktop:
|
||||
@@ -53,22 +71,7 @@ async def _get_cnr_data(cache_mode=True, dont_wait=True):
|
||||
else:
|
||||
comfyui_ver = context.get_comfyui_tag() or 'unknown'
|
||||
|
||||
if is_desktop:
|
||||
if is_windows:
|
||||
form_factor = 'desktop-win'
|
||||
elif is_mac:
|
||||
form_factor = 'desktop-mac'
|
||||
else:
|
||||
form_factor = 'other'
|
||||
else:
|
||||
if is_windows:
|
||||
form_factor = 'git-windows'
|
||||
elif is_mac:
|
||||
form_factor = 'git-mac'
|
||||
elif is_linux:
|
||||
form_factor = 'git-linux'
|
||||
else:
|
||||
form_factor = 'other'
|
||||
form_factor = get_form_factor()
|
||||
|
||||
from comfyui_manager.glob import manager_core
|
||||
verbose = manager_core.get_config().get('verbose', False)
|
||||
|
||||
@@ -76,21 +76,28 @@ def aria2_find_task(dir: str, filename: str):
|
||||
|
||||
|
||||
def aria2_download_url(model_url: str, model_dir: str, filename: str):
|
||||
import manager_core as core
|
||||
try:
|
||||
from comfyui_manager.common import context
|
||||
except ImportError:
|
||||
import manager_core as context
|
||||
import tqdm
|
||||
import time
|
||||
|
||||
if model_dir.startswith(core.comfy_path):
|
||||
model_dir = model_dir[len(core.comfy_path) :]
|
||||
local_path = os.path.join(model_dir, filename)
|
||||
|
||||
if model_dir.startswith(context.comfy_path):
|
||||
model_dir = model_dir[len(context.comfy_path) :]
|
||||
|
||||
download_dir = model_dir if model_dir.startswith('/') else os.path.join('/models', model_dir)
|
||||
|
||||
download = aria2_find_task(download_dir, filename)
|
||||
if download is None:
|
||||
if download is not None and download.is_complete and os.path.exists(local_path):
|
||||
return
|
||||
if download is None or not (download.is_active or download.is_waiting):
|
||||
options = {'dir': download_dir, 'out': filename}
|
||||
download = aria2.add(model_url, options)[0]
|
||||
|
||||
if download.is_active:
|
||||
if download.is_active or download.is_waiting:
|
||||
with tqdm.tqdm(
|
||||
total=download.total_length,
|
||||
bar_format='{l_bar}{bar}{r_bar}',
|
||||
@@ -98,13 +105,19 @@ def aria2_download_url(model_url: str, model_dir: str, filename: str):
|
||||
unit='B',
|
||||
unit_scale=True,
|
||||
) as progress_bar:
|
||||
while download.is_active:
|
||||
while download.is_active or download.is_waiting:
|
||||
if progress_bar.total == 0 and download.total_length != 0:
|
||||
progress_bar.reset(download.total_length)
|
||||
progress_bar.update(download.completed_length - progress_bar.n)
|
||||
time.sleep(1)
|
||||
download.update()
|
||||
|
||||
if download.has_failed:
|
||||
raise Exception(f"aria2 failed to download '{model_url}' into '{download_dir}': {download.error_message}")
|
||||
if not os.path.exists(local_path):
|
||||
raise Exception(f"aria2 saved '{filename}' into its '{download_dir}', but the file is not at '{local_path}'. "
|
||||
"aria2 must see the ComfyUI folder as '/' (see docs/en/use_aria2.md).")
|
||||
|
||||
|
||||
def download_url_with_agent(url, save_path):
|
||||
try:
|
||||
|
||||
@@ -2,16 +2,23 @@
|
||||
description:
|
||||
`manager_util` is the lightest module shared across the prestartup_script, main code, and cm-cli of ComfyUI-Manager.
|
||||
"""
|
||||
import csv
|
||||
import sysconfig
|
||||
import shutil
|
||||
import importlib.metadata
|
||||
import traceback
|
||||
|
||||
import aiohttp
|
||||
import json
|
||||
import math
|
||||
import threading
|
||||
import contextlib
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import re
|
||||
import codecs
|
||||
import logging
|
||||
import platform
|
||||
import shlex
|
||||
@@ -34,6 +41,50 @@ use_uv = False
|
||||
use_unified_resolver = False
|
||||
bypass_ssl = False
|
||||
|
||||
# When False, ComfyUI-Manager will not attempt to install, upgrade, or
|
||||
# uninstall Python packages on its own (prestartup auto-healing and the unified
|
||||
# dependency resolver batch). This is intended for distro-packaged or otherwise
|
||||
# externally-managed Python environments (e.g. Nix, Guix, system package
|
||||
# managers, locked-down corporate images) where the interpreter is read-only.
|
||||
#
|
||||
# Read-only pip operations (`list`, `freeze`, `show`) still run so the UI,
|
||||
# inventory, and security checks keep working.
|
||||
dependency_management_enabled = True
|
||||
|
||||
|
||||
_OFF_VALUES = frozenset({'off', 'false', '0', 'no', 'disabled'})
|
||||
|
||||
|
||||
def is_off_value(value):
|
||||
"""Return True if a config or env-var string spells "off".
|
||||
|
||||
Anything else — including the empty string and unknown words — is treated
|
||||
as "on", so a typo doesn't silently disable dependency management.
|
||||
"""
|
||||
return value.strip().lower() in _OFF_VALUES
|
||||
|
||||
|
||||
DEPENDENCY_MANAGEMENT_ENV = 'COMFYUI_MANAGER_DEPENDENCY_MANAGEMENT'
|
||||
|
||||
|
||||
def apply_dependency_management_setting(config_value=None):
|
||||
"""Set `dependency_management_enabled` from the environment, else from config.ini's value.
|
||||
|
||||
The environment wins over config.ini; with neither, the current value stays. Every process
|
||||
that loads this module (the server, cm-cli, the cm-cli that the startup runs) applies the
|
||||
environment."""
|
||||
global dependency_management_enabled
|
||||
value = os.environ.get(DEPENDENCY_MANAGEMENT_ENV)
|
||||
if value is None:
|
||||
value = config_value
|
||||
if value is not None:
|
||||
dependency_management_enabled = not is_off_value(value)
|
||||
return dependency_management_enabled
|
||||
|
||||
|
||||
apply_dependency_management_setting()
|
||||
|
||||
|
||||
def is_manager_pip_package():
|
||||
return not os.path.exists(os.path.join(comfyui_manager_path, '..', 'custom_nodes'))
|
||||
|
||||
@@ -934,9 +985,21 @@ def parse_requirement_line(line):
|
||||
|
||||
|
||||
torch_torchvision_torchaudio_version_map = {
|
||||
'2.15.0': ('0.29.2', '2.11.*'),
|
||||
'2.14.1': ('0.29.1', '2.11.*'),
|
||||
'2.14.0': ('0.29.0', '2.11.*'),
|
||||
'2.13.0': ('0.28.0', '2.11.*'),
|
||||
'2.12.1': ('0.27.1', '2.11.*'),
|
||||
'2.12.0': ('0.27.0', '2.11.*'),
|
||||
'2.11.0': ('0.26.0', '2.11.*'),
|
||||
'2.10.0': ('0.25.0', '2.10.0'),
|
||||
'2.9.1': ('0.24.1', '2.9.1'),
|
||||
'2.9.0': ('0.24.0', '2.9.0'),
|
||||
'2.8.0': ('0.23.0', '2.8.0'),
|
||||
'2.7.1': ('0.22.1', '2.7.1'),
|
||||
'2.7.0': ('0.22.0', '2.7.0'),
|
||||
'2.6.0': ('0.21.0', '2.6.0'),
|
||||
'2.5.1': ('0.20.0', '2.5.0'),
|
||||
'2.5.1': ('0.20.1', '2.5.1'),
|
||||
'2.5.0': ('0.20.0', '2.5.0'),
|
||||
'2.4.1': ('0.19.1', '2.4.1'),
|
||||
'2.4.0': ('0.19.0', '2.4.0'),
|
||||
@@ -948,19 +1011,19 @@ torch_torchvision_torchaudio_version_map = {
|
||||
'2.1.2': ('0.16.2', '2.1.2'),
|
||||
'2.1.1': ('0.16.1', '2.1.1'),
|
||||
'2.1.0': ('0.16.0', '2.1.0'),
|
||||
'2.0.1': ('0.15.2', '2.0.1'),
|
||||
'2.0.1': ('0.15.2', '2.0.2'),
|
||||
'2.0.0': ('0.15.1', '2.0.0'),
|
||||
}
|
||||
|
||||
|
||||
def torch_rollback(prev, packages):
|
||||
def torch_rollback_by_version_table(prev, packages, options=()):
|
||||
spec = prev.split('+')
|
||||
if len(spec) > 1:
|
||||
platform = spec[1]
|
||||
else:
|
||||
cmd = make_pip_cmd(['install', '--force', *packages])
|
||||
cmd = make_pip_cmd(['install', '--force', *packages, *options])
|
||||
logging.info("[ComfyUI-Manager] restore PyTorch to the newest release")
|
||||
subprocess.check_output(cmd, universal_newlines=True)
|
||||
logging.error(cmd)
|
||||
return
|
||||
|
||||
torch_ver = StrictVersion(spec[0])
|
||||
@@ -969,21 +1032,341 @@ def torch_rollback(prev, packages):
|
||||
|
||||
if torch_torchvision_torchaudio_ver is None:
|
||||
cmd = make_pip_cmd(['install', '--pre', *packages,
|
||||
'--index-url', f"https://download.pytorch.org/whl/nightly/{platform}"])
|
||||
'--index-url', f"https://download.pytorch.org/whl/nightly/{platform}", *options])
|
||||
logging.info("[ComfyUI-Manager] restore PyTorch to nightly version")
|
||||
else:
|
||||
torchvision_ver, torchaudio_ver = torch_torchvision_torchaudio_ver
|
||||
versions = {'torch': torch_ver, 'torchvision': torchvision_ver, 'torchaudio': torchaudio_ver}
|
||||
cmd = make_pip_cmd(['install', *[f'{name}=={versions[name]}' for name in packages],
|
||||
'--index-url', f"https://download.pytorch.org/whl/{platform}"])
|
||||
'--index-url', f"https://download.pytorch.org/whl/{platform}", *options])
|
||||
logging.info(f"[ComfyUI-Manager] restore PyTorch to {torch_ver}+{platform}")
|
||||
|
||||
subprocess.check_output(cmd, universal_newlines=True)
|
||||
|
||||
|
||||
def _pytorch_index(build, option):
|
||||
version = Version(build)
|
||||
if version.is_devrelease:
|
||||
return ['--pre', option, f"https://download.pytorch.org/whl/nightly/{version.local or 'cpu'}"]
|
||||
if version.local is not None:
|
||||
return [option, f"https://download.pytorch.org/whl/{version.local}"]
|
||||
return []
|
||||
|
||||
|
||||
def _installed_version(name):
|
||||
try:
|
||||
return importlib.metadata.version(name)
|
||||
except importlib.metadata.PackageNotFoundError:
|
||||
return None
|
||||
|
||||
|
||||
def _recorded_files(name):
|
||||
try:
|
||||
distribution = importlib.metadata.distribution(name)
|
||||
except importlib.metadata.PackageNotFoundError:
|
||||
return []
|
||||
# From the RECORD itself: files() leaves out the missing ones from Python 3.12 on
|
||||
return [(distribution.locate_file(row[0]), int(row[2]))
|
||||
for row in csv.reader((distribution.read_text('RECORD') or '').splitlines()) if len(row) == 3 and row[2]]
|
||||
|
||||
|
||||
def _required_here(name, extras=frozenset()):
|
||||
found = []
|
||||
for line in importlib.metadata.requires(name) or []:
|
||||
try:
|
||||
requirement = Requirement(line)
|
||||
except InvalidRequirement:
|
||||
continue
|
||||
if requirement.marker is None or any(requirement.marker.evaluate({'extra': extra}) for extra in {*extras, ''}):
|
||||
found.append((normalize_pip_name(requirement.name), set(requirement.extras)))
|
||||
return found
|
||||
|
||||
|
||||
def _size_of_pytorch():
|
||||
extras, todo = {}, [(name, set()) for name in ('torch', 'torchvision', 'torchaudio')]
|
||||
while todo:
|
||||
name, wanted = todo.pop()
|
||||
if _installed_version(name) is None or name in extras and wanted <= extras[name]:
|
||||
continue
|
||||
extras[name] = extras.get(name, set()) | wanted
|
||||
todo += _required_here(name, extras[name])
|
||||
return {name: sum(size for _, size in _recorded_files(name)) for name in extras}
|
||||
|
||||
|
||||
def _space_to_restore(installed_before, installed_after, overwritten, size_of_pytorch, times_the_size):
|
||||
return int(times_the_size * sum(size for name, size in size_of_pytorch.items()
|
||||
if installed_after.get(name) != installed_before.get(name) or name in overwritten))
|
||||
|
||||
|
||||
def _overwritten(installed_before, installed_after, required_by_torch):
|
||||
# cuDNN, cuSPARSELt, NCCL and NVSHMEM ship one distribution per CUDA version, all writing the same file paths.
|
||||
return {name: installed_after[name] for name in sorted(required_by_torch)
|
||||
if name in installed_after and installed_before.get(name) == installed_after[name]
|
||||
and any(os.path.isfile(file) and os.path.getsize(file) != size for file, size in _recorded_files(name))}
|
||||
|
||||
|
||||
def _incomplete(required_by_torch):
|
||||
return {name: _installed_version(name) for name in sorted(required_by_torch)
|
||||
if any(not os.path.isfile(file) for file, _ in _recorded_files(name))}
|
||||
|
||||
|
||||
# The metadata of a torchvision or torchaudio can fit torch while its native library does not load beside it: a build
|
||||
# for another CUDA version, or the PyPI build beside a CPU torch. torch imports beside a cuDNN older than the one it
|
||||
# was built for; cudnn.version() compares the two without a GPU, and a CPU build has none to compare.
|
||||
_PYTORCH_CHECKS = {
|
||||
'torch': 'import torch; torch.backends.cudnn.version()',
|
||||
'torchvision': 'import torch, torchvision; torchvision.ops.nms(torch.rand(3, 4) * 10, torch.rand(3), 0.5)',
|
||||
'torchaudio': 'import torch, torchaudio.functional as F; F.lowpass_biquad(torch.rand(1, 100), 16000, 300.0)',
|
||||
}
|
||||
|
||||
|
||||
_CHECK_TIME_LIMIT = 300
|
||||
|
||||
# A .pth file or a module can print to the same stdout when Python starts, and can leave its line without an end.
|
||||
_CHECK_LINE = '[ComfyUI-Manager] PyTorch check:'
|
||||
_CHECK_DID_NOT_RUN = None
|
||||
|
||||
|
||||
def _not_working(names):
|
||||
code = f"print({_CHECK_LINE!r}, flush=True)\n" + ''.join(
|
||||
f"try:\n {_PYTORCH_CHECKS[name]}\n print({f'{_CHECK_LINE} {name}'!r}, flush=True)\nexcept Exception:\n"
|
||||
f" pass\n" for name in names)
|
||||
try:
|
||||
printed = subprocess.run([sys.executable, '-c', code], capture_output=True, text=True,
|
||||
timeout=_CHECK_TIME_LIMIT).stdout.splitlines()
|
||||
except subprocess.TimeoutExpired:
|
||||
return _CHECK_DID_NOT_RUN
|
||||
def told(line):
|
||||
return any(found.endswith(line) for found in printed)
|
||||
|
||||
if not told(_CHECK_LINE):
|
||||
return _CHECK_DID_NOT_RUN
|
||||
return [name for name in names if not told(f'{_CHECK_LINE} {name}')]
|
||||
|
||||
|
||||
class _Pip:
|
||||
# Measured: pip holds a wheel in its temporary folder while it writes the files, at the peak 1.7 times the size of
|
||||
# the files. With its cache it holds the wheel there too, at the peak 2.35 times for a CUDA torch for Windows.
|
||||
times_the_size = 2
|
||||
|
||||
@contextlib.contextmanager
|
||||
def environment(self):
|
||||
before = os.environ.get('PIP_NO_CACHE_DIR')
|
||||
os.environ['PIP_NO_CACHE_DIR'] = '1'
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if before is None:
|
||||
del os.environ['PIP_NO_CACHE_DIR']
|
||||
else:
|
||||
os.environ['PIP_NO_CACHE_DIR'] = before
|
||||
|
||||
def install(self, name, build, *options):
|
||||
command = make_pip_cmd(['install', *options, f'{name}==={build}', *_pytorch_index(build, '--extra-index-url')])
|
||||
try:
|
||||
subprocess.check_output(command, universal_newlines=True)
|
||||
except subprocess.CalledProcessError:
|
||||
return False
|
||||
return True
|
||||
|
||||
@contextlib.contextmanager
|
||||
def putting_back(self, overwritten, torch):
|
||||
# pip installs no distribution of a command again without all the others.
|
||||
pins = [f'{name}=={version}' for name, version in overwritten.items()]
|
||||
with tempfile.TemporaryDirectory() as wheels:
|
||||
if pins:
|
||||
try:
|
||||
subprocess.check_output(make_pip_cmd(['download', '--no-deps', '-d', wheels, *pins,
|
||||
*_pytorch_index(torch, '--extra-index-url')]),
|
||||
universal_newlines=True)
|
||||
except subprocess.CalledProcessError:
|
||||
raise RuntimeError(f"{', '.join(pins)} cannot be had")
|
||||
yield []
|
||||
left = [f'{name}=={version}' for name, version in overwritten.items()
|
||||
if _installed_version(name) == version]
|
||||
if left:
|
||||
subprocess.check_output(make_pip_cmd(['install', '--no-deps', '--force-reinstall', '--no-index',
|
||||
'--find-links', wheels, *left]), universal_newlines=True)
|
||||
|
||||
def own_index(self, torch):
|
||||
return _pytorch_index(torch, '--index-url')
|
||||
|
||||
def install_again(self, broken, requirements, torch):
|
||||
# pip joins PIP_EXTRA_INDEX_URL to an index and takes the highest version of all, which can be a build for
|
||||
# another CUDA version.
|
||||
index = _pytorch_index(torch, '--find-links')
|
||||
if index:
|
||||
*pre, _, url = index
|
||||
index = [*pre, '--no-index', *[option for name in broken for option in ('--find-links', f'{url}/{name}/')]]
|
||||
subprocess.check_output(make_pip_cmd(['install', '--force-reinstall', '--no-deps',
|
||||
*[requirements[name] for name in broken], *index]),
|
||||
universal_newlines=True)
|
||||
|
||||
def install_files_again(self, name, version, torch):
|
||||
subprocess.check_output(make_pip_cmd(['install', '--force-reinstall', '--no-deps', f'{name}=={version}',
|
||||
*_pytorch_index(torch, '--extra-index-url')]), universal_newlines=True)
|
||||
|
||||
|
||||
class _Uv:
|
||||
# Measured: uv unpacks a wheel into its cache and links the files from there, at the peak 1.06 times the size of
|
||||
# the files. Where it copies them, it removes the old build first.
|
||||
times_the_size = 1.5
|
||||
|
||||
def __init__(self):
|
||||
# uv's version line can follow what Python prints as it starts.
|
||||
try:
|
||||
printed = subprocess.check_output([*make_pip_cmd([])[:-1], '--version'], universal_newlines=True)
|
||||
except subprocess.CalledProcessError:
|
||||
printed = ''
|
||||
version = re.search(r'^uv (\d+(\.\d+)*)', printed, re.MULTILINE)
|
||||
self.reads_index = version is not None and Version(version[1]) >= Version('0.4.23')
|
||||
|
||||
def environment(self):
|
||||
return contextlib.nullcontext()
|
||||
|
||||
def install(self, name, build, *options):
|
||||
# uv does not put back what it removed when a command fails while it installs, and an install command sent
|
||||
# after it can lay the new build over what is left and report it as installed. uv ends a command when it
|
||||
# cannot reach an index that the command names. A --extra-index-url of the command takes the place of
|
||||
# UV_EXTRA_INDEX_URL.
|
||||
index = _pytorch_index(build, '--extra-index-url')
|
||||
command = make_pip_cmd(['install', *options, f'{name}==={build}', *index])
|
||||
forms = [command, [*command, '--offline']]
|
||||
if index:
|
||||
forms.append([*make_pip_cmd(['install', *options, f'{name}==={build}', *index[:-2]]), '--offline'])
|
||||
for form in forms:
|
||||
try:
|
||||
subprocess.check_output([*form, '--dry-run'], universal_newlines=True, stderr=subprocess.PIPE)
|
||||
except subprocess.CalledProcessError as e:
|
||||
if form is command:
|
||||
reason = '\n'.join(line for line in e.stderr.strip().splitlines()
|
||||
if not line.startswith('Using Python '))
|
||||
continue
|
||||
if form is not command:
|
||||
logging.info("[ComfyUI-Manager] restore PyTorch: the command does not resolve with its indexes, "
|
||||
"installing from uv's cache alone")
|
||||
try:
|
||||
subprocess.check_output(form, universal_newlines=True)
|
||||
except subprocess.CalledProcessError:
|
||||
logging.warning(f"[ComfyUI-Manager] restore PyTorch: installing {name} {build} failed, "
|
||||
f"sending it once more")
|
||||
subprocess.check_output([*form, '--reinstall-package', name], universal_newlines=True)
|
||||
return True
|
||||
logging.warning(f"[ComfyUI-Manager] restore PyTorch: uv does not resolve the command: {reason}")
|
||||
return False
|
||||
|
||||
def putting_back(self, overwritten, torch):
|
||||
return contextlib.nullcontext([option for name in overwritten for option in ('--reinstall-package', name)])
|
||||
|
||||
def own_index(self, torch):
|
||||
# uv reads --index before UV_INDEX, UV_EXTRA_INDEX_URL and the default index, and a --index of the command
|
||||
# takes the place of UV_INDEX.
|
||||
index = _pytorch_index(torch, '--index-url')
|
||||
return [*index, '--index' if self.reads_index else '--extra-index-url', index[-1]] if index else []
|
||||
|
||||
def install_again(self, broken, requirements, torch):
|
||||
again = [option for name in broken for option in ('--reinstall-package', name)]
|
||||
subprocess.check_output(make_pip_cmd(['install', *requirements.values(), *self.own_index(torch), *again]),
|
||||
universal_newlines=True)
|
||||
|
||||
def install_files_again(self, name, version, torch):
|
||||
subprocess.check_output(make_pip_cmd(['install', '--no-deps', f'{name}=={version}',
|
||||
*_pytorch_index(torch, '--extra-index-url'),
|
||||
'--reinstall-package', name]), universal_newlines=True)
|
||||
|
||||
|
||||
def _report_not_working(names):
|
||||
if names is _CHECK_DID_NOT_RUN:
|
||||
logging.warning("[ComfyUI-Manager] restore PyTorch: the check of what works did not run")
|
||||
elif names:
|
||||
logging.error(f"[ComfyUI-Manager] restore PyTorch: does not work after the restore: "
|
||||
f"{', '.join(f'{name} {_installed_version(name)}' for name in names)}")
|
||||
|
||||
|
||||
def torch_rollback(installed_before, installed_after, required_by_torch, size_of_pytorch):
|
||||
tool = _Uv() if 'uv' in make_pip_cmd([]) else _Pip()
|
||||
torch = installed_before['torch']
|
||||
packages = [name for name in ('torch', 'torchvision', 'torchaudio')
|
||||
if name in installed_before or name in installed_after]
|
||||
changed = {name: installed_before[name] for name in ('torch', 'torchvision', 'torchaudio')
|
||||
if name in installed_before and installed_after.get(name) != installed_before[name]}
|
||||
logging.info(f"[ComfyUI-Manager] restore PyTorch: {', '.join(f'{name} {build}' for name, build in changed.items())}")
|
||||
|
||||
companions = {name: build for name, build in changed.items() if name != 'torch'}
|
||||
overwritten = _overwritten(installed_before, installed_after, required_by_torch)
|
||||
needed = _space_to_restore(installed_before, installed_after, overwritten, size_of_pytorch, tool.times_the_size)
|
||||
free = shutil.disk_usage(sysconfig.get_path('purelib')).free
|
||||
if free < needed:
|
||||
raise RuntimeError(f"for safety the restore does not start: it can take {math.ceil(needed / 10 ** 6)} MB on "
|
||||
f"the disk of the Python environment, where {free // 10 ** 6} MB are free")
|
||||
with tool.environment():
|
||||
if 'torch' in changed or overwritten:
|
||||
with tool.putting_back(overwritten, torch) as options:
|
||||
torch_installed = tool.install('torch', torch, *options)
|
||||
if not torch_installed:
|
||||
logging.warning(f"[ComfyUI-Manager] restore PyTorch: torch {torch} cannot be had, "
|
||||
f"restoring by the version table instead")
|
||||
torch_rollback_by_version_table(torch, packages, options)
|
||||
if not torch_installed:
|
||||
_report_not_working(_not_working(packages))
|
||||
return
|
||||
|
||||
for name, build in companions.items():
|
||||
if not tool.install(name, build, '--no-deps'):
|
||||
logging.warning(f"[ComfyUI-Manager] restore PyTorch: {name} {build} cannot be had, "
|
||||
f"installing a {name} that fits torch {torch} instead")
|
||||
|
||||
# torchaudio 2.11.0 declares no requirement on torch, so without a bound the resolver takes it beside an older
|
||||
# torch. The bound is the next minor version of torch, as a patch release of torchaudio can be newer than its
|
||||
# torch: 2.0.2 goes with 2.0.1.
|
||||
version = Version(torch)
|
||||
requirement = {'torch': f'torch==={torch}', 'torchvision': 'torchvision',
|
||||
'torchaudio': f'torchaudio<{version.major}.{version.minor + 1}'}
|
||||
requirements = {name: requirement[name] for name in packages}
|
||||
try:
|
||||
subprocess.check_output(make_pip_cmd(['install', *requirements.values(), *tool.own_index(torch)]),
|
||||
universal_newlines=True)
|
||||
except subprocess.CalledProcessError as e:
|
||||
logging.warning(f"[ComfyUI-Manager] restore PyTorch: the whole set failed to install, checking what "
|
||||
f"works: {e}")
|
||||
|
||||
broken = _not_working(packages)
|
||||
if broken and 'torch' in broken:
|
||||
# An uninstall takes the files that two distributions share.
|
||||
incomplete = _incomplete(required_by_torch)
|
||||
for name, version in incomplete.items():
|
||||
try:
|
||||
tool.install_files_again(name, version, torch)
|
||||
except subprocess.CalledProcessError:
|
||||
pass
|
||||
if incomplete:
|
||||
broken = _not_working(packages)
|
||||
|
||||
if broken and 'torch' not in broken:
|
||||
torchvision = _installed_version('torchvision')
|
||||
if 'torchvision' in broken and torchvision is not None:
|
||||
requirements['torchvision'] = f"torchvision=={Version(torchvision).public}"
|
||||
try:
|
||||
tool.install_again(broken, requirements, torch)
|
||||
except subprocess.CalledProcessError:
|
||||
pass
|
||||
broken = _not_working(packages)
|
||||
_report_not_working(broken)
|
||||
|
||||
|
||||
class PIPFixer:
|
||||
def __init__(self, prev_pip_versions, comfyui_path, manager_files_path):
|
||||
self.prev_pip_versions = { **prev_pip_versions }
|
||||
self.required_by_torch, self.size_of_pytorch = set(), {}
|
||||
torch = prev_pip_versions.get('torch')
|
||||
try:
|
||||
list_names_the_installed_torch = torch is not None and _installed_version('torch') == torch
|
||||
if list_names_the_installed_torch:
|
||||
self.required_by_torch, self.size_of_pytorch = ({name for name, _ in _required_here('torch')},
|
||||
_size_of_pytorch())
|
||||
except Exception as e:
|
||||
logging.warning(f"[ComfyUI-Manager] restore PyTorch: what torch requires could not be read, "
|
||||
f"a restore will put no library back: {e!r}")
|
||||
self.comfyui_path = comfyui_path
|
||||
self.manager_files_path = manager_files_path
|
||||
|
||||
@@ -997,6 +1380,10 @@ class PIPFixer:
|
||||
return {parse_pip_spec(x)[0] for x in f.readlines()}
|
||||
|
||||
def fix_broken(self):
|
||||
if not dependency_management_enabled:
|
||||
logging.info("[ComfyUI-Manager] dependency management disabled; skipping PIPFixer.fix_broken()")
|
||||
return
|
||||
|
||||
new_pip_versions = get_installed_packages(True)
|
||||
|
||||
# remove `comfy` python package
|
||||
@@ -1014,11 +1401,10 @@ class PIPFixer:
|
||||
try:
|
||||
if 'torch' not in self.prev_pip_versions or 'torchvision' not in self.prev_pip_versions:
|
||||
logging.error("[ComfyUI-Manager] PyTorch is not installed")
|
||||
elif self.prev_pip_versions['torch'] != new_pip_versions['torch'] \
|
||||
or self.prev_pip_versions['torchvision'] != new_pip_versions['torchvision']:
|
||||
packages = [name for name in ('torch', 'torchvision', 'torchaudio')
|
||||
if name in self.prev_pip_versions or name in new_pip_versions]
|
||||
torch_rollback(self.prev_pip_versions['torch'], packages)
|
||||
elif any(self.prev_pip_versions[name] != new_pip_versions.get(name) for name in ('torch', 'torchvision')):
|
||||
clear_pip_cache()
|
||||
torch_rollback(self.prev_pip_versions, new_pip_versions, self.required_by_torch,
|
||||
self.size_of_pytorch)
|
||||
except Exception as e:
|
||||
logging.error("[ComfyUI-Manager] Failed to restore PyTorch")
|
||||
logging.error(e)
|
||||
@@ -1151,6 +1537,52 @@ def robust_readlines(fullpath):
|
||||
return []
|
||||
|
||||
|
||||
_PRINTABLE_ASCII = re.compile(r'[\t-\r -~]*')
|
||||
_PRINTABLE_ASCII_BYTES = bytes(range(0x09, 0x0e)) + bytes(range(0x20, 0x7f))
|
||||
_WIDE_UNICODE_CODECS = ('utf-16', 'utf-16-le', 'utf-16-be', 'utf-32', 'utf-32-le', 'utf-32-be')
|
||||
|
||||
|
||||
def _is_ascii_compatible_or_wide_unicode(encoding):
|
||||
try:
|
||||
codec = codecs.lookup(encoding)
|
||||
if codec.name in _WIDE_UNICODE_CODECS:
|
||||
return True
|
||||
return codec.decode(_PRINTABLE_ASCII_BYTES)[0] == _PRINTABLE_ASCII_BYTES.decode('ascii')
|
||||
except (LookupError, UnicodeDecodeError):
|
||||
return False
|
||||
|
||||
|
||||
def _hands_pip_only_ascii(line):
|
||||
before_comment = _PIP_COMMENT_PATTERN.sub('', line)
|
||||
return before_comment.isspace() or _PRINTABLE_ASCII.fullmatch(before_comment) is not None
|
||||
|
||||
|
||||
def read_requirements_lines(fullpath):
|
||||
try:
|
||||
with open(fullpath, "r") as f:
|
||||
return f.readlines()
|
||||
except UnicodeDecodeError:
|
||||
import chardet
|
||||
with open(fullpath, "rb") as f:
|
||||
encoding = chardet.detect(f.read())['encoding']
|
||||
|
||||
lines = None
|
||||
if encoding is not None and _is_ascii_compatible_or_wide_unicode(encoding):
|
||||
try:
|
||||
with open(fullpath, "r", encoding=encoding) as f:
|
||||
lines = f.readlines()
|
||||
except UnicodeDecodeError:
|
||||
pass
|
||||
|
||||
if lines:
|
||||
# chardet 7.1.0 names UTF-16-LE for a UTF-16 file with a byte order mark, which then stays in the text
|
||||
lines[0] = lines[0].lstrip('\ufeff')
|
||||
|
||||
if lines is None or not all(_hands_pip_only_ascii(line) for line in lines):
|
||||
raise
|
||||
return lines
|
||||
|
||||
|
||||
def build_restart_command(argv, drop_args=()):
|
||||
"""
|
||||
Rebuild the command line used to re-exec the current ComfyUI process.
|
||||
|
||||
@@ -553,6 +553,12 @@ class UnifiedManager:
|
||||
for folder in folders:
|
||||
self.invalid_installations.pop(folder, None)
|
||||
|
||||
def forget_gone_disabled_versions_if_one_is_left(self, node_id):
|
||||
disabled = self.cnr_inactive_nodes.get(node_id, {})
|
||||
gone = [x for x in disabled.values() if not os.path.exists(x)]
|
||||
if len(gone) < len(disabled):
|
||||
self.forget_folders(gone)
|
||||
|
||||
def move_invalid_installation(self, from_path, to_path, enabled):
|
||||
x = self.invalid_installations.pop(from_path, None)
|
||||
if x is not None:
|
||||
@@ -653,7 +659,7 @@ class UnifiedManager:
|
||||
return True
|
||||
|
||||
target = self.cnr_inactive_nodes.get(node_id, None)
|
||||
if target is not None and target == version_spec:
|
||||
if target and any(ver != 'nightly' for ver in target.keys()):
|
||||
return True
|
||||
|
||||
return False
|
||||
@@ -1023,7 +1029,7 @@ class UnifiedManager:
|
||||
|
||||
if version_spec is None:
|
||||
version_spec = self.resolve_unspecified_version(node_id, guess_mode='inactive')
|
||||
if version is None:
|
||||
if version_spec is None and not self.is_enabled(node_id):
|
||||
return result.fail(f'Specified inactive node not exists: {node_id}')
|
||||
|
||||
if self.is_enabled(node_id, version_spec):
|
||||
@@ -1495,6 +1501,8 @@ class UnifiedManager:
|
||||
|
||||
repo_url = None
|
||||
if version_spec is None:
|
||||
if node_id in self.cnr_map:
|
||||
self.forget_gone_disabled_versions_if_one_is_left(node_id)
|
||||
if self.is_enabled(node_id):
|
||||
return ManagedResult('skip')
|
||||
elif self.is_disabled(node_id):
|
||||
@@ -1913,6 +1921,7 @@ def read_config():
|
||||
return default_conf[key].lower() == 'true' if key in default_conf else False
|
||||
|
||||
manager_util.use_uv = default_conf['use_uv'].lower() == 'true' if 'use_uv' in default_conf else False
|
||||
manager_util.apply_dependency_management_setting(default_conf.get('dependency_management'))
|
||||
# Don't override use_unified_resolver here: prestartup_script.py already reads config
|
||||
# and sets this flag, then may reset it to False on resolver fallback.
|
||||
# Re-reading from config would undo the fallback.
|
||||
@@ -2195,11 +2204,10 @@ def execute_install_script(url, repo_path, lazy_mode=False, instant_execution=Fa
|
||||
elif os.path.exists(requirements_path) and not no_deps:
|
||||
print("Install: pip packages")
|
||||
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), context.comfy_path, context.manager_files_path)
|
||||
with open(requirements_path, "r") as requirements_file:
|
||||
for line in requirements_file:
|
||||
install_args = manager_util.pip_install_args(line, cm_global.pip_overrides)
|
||||
if install_args:
|
||||
try_install_script(url, repo_path, manager_util.make_pip_cmd(["install", *install_args]), instant_execution=instant_execution)
|
||||
for line in manager_util.read_requirements_lines(requirements_path):
|
||||
install_args = manager_util.pip_install_args(line, cm_global.pip_overrides)
|
||||
if install_args:
|
||||
try_install_script(url, repo_path, manager_util.make_pip_cmd(["install", *install_args]), instant_execution=instant_execution)
|
||||
pip_fixer.fix_broken()
|
||||
|
||||
if os.path.exists(install_script_path):
|
||||
@@ -2513,6 +2521,14 @@ async def get_data_by_mode(mode, filename, channel_url=None):
|
||||
cache_uri = str(manager_util.simple_hash(uri))+'_'+filename
|
||||
cache_uri = os.path.join(manager_util.cache_dir, cache_uri)
|
||||
|
||||
if mode == "remote" and get_config()['network_mode'] != 'offline' and manager_util.is_manager_pip_package():
|
||||
try:
|
||||
json_obj = await manager_util.get_data(uri)
|
||||
manager_util.write_cache_file(cache_uri, json_obj)
|
||||
return json_obj
|
||||
except Exception as e:
|
||||
print(f"[ComfyUI-Manager] Due to a network error, switching to cache mode.\n=> {filename} @ {channel_url}/{mode}\n=> {e}")
|
||||
|
||||
if get_config()['network_mode'] == 'offline' or manager_util.is_manager_pip_package():
|
||||
# offline network mode
|
||||
if os.path.exists(cache_uri):
|
||||
@@ -3189,8 +3205,8 @@ async def get_unified_total_nodes(channel, mode, regsitry_cache_mode='cache'):
|
||||
if cnr_id in unified_manager.active_nodes:
|
||||
# installed
|
||||
state = 'enabled'
|
||||
updatable = unified_manager.is_updatable(cnr_id)
|
||||
active_version = unified_manager.active_nodes[cnr['id']][0]
|
||||
updatable = active_version != 'nightly' and unified_manager.is_updatable(cnr_id)
|
||||
ver = active_version
|
||||
|
||||
if cm_global.try_call(api="cm.is_import_failed_extension", name=unified_manager.active_nodes[cnr_id][1]):
|
||||
@@ -3212,6 +3228,7 @@ async def get_unified_total_nodes(channel, mode, regsitry_cache_mode='cache'):
|
||||
|
||||
item = dict(author=author, title=title, reference=reference, repository=repository, install_type=install_type,
|
||||
description=description, state=state, updatable=updatable, version=ver)
|
||||
item['update-state'] = 'true' if updatable else 'false'
|
||||
|
||||
if active_version:
|
||||
item['active_version'] = active_version
|
||||
|
||||
@@ -127,8 +127,10 @@ def check_model_installed(json_obj):
|
||||
fullpath = os.path.join(
|
||||
folder_paths.models_dir, item["save_path"], filename
|
||||
)
|
||||
subpath = os.path.join(item["save_path"].partition("/")[2], filename)
|
||||
found = os.path.exists(fullpath) or folder_paths.get_full_path(model_dir_name, subpath)
|
||||
|
||||
item["installed"] = "True" if os.path.exists(fullpath) else "False"
|
||||
item["installed"] = "True" if found else "False"
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(8) as executor:
|
||||
for item in json_obj["models"]:
|
||||
|
||||
@@ -218,6 +218,7 @@
|
||||
|
||||
.cn-manager-grid .cn-pack-conflicts {
|
||||
color: orange;
|
||||
white-space: normal;
|
||||
}
|
||||
|
||||
.cn-popover {
|
||||
|
||||
@@ -883,6 +883,9 @@ export class CustomNodesManager {
|
||||
if (rowItem.conflicts) {
|
||||
list.push(`<div class="cn-pack-conflicts">${rowItem.conflicts} conflict${(rowItem.conflicts>1?'s':'')}</div>`);
|
||||
}
|
||||
if (rowItem.potentialConflicts) {
|
||||
list.push(`<div class="cn-pack-conflicts">${rowItem.potentialConflicts} potential conflict${(rowItem.potentialConflicts>1?'s':'')}</div>`);
|
||||
}
|
||||
list.push('</div>');
|
||||
return list.join("");
|
||||
}
|
||||
@@ -1326,8 +1329,9 @@ export class CustomNodesManager {
|
||||
list.push(`<div class="cn-nodes-list">`);
|
||||
|
||||
nodesList.forEach((it, i) => {
|
||||
const conflicts = it.conflicts || it.potentialConflicts;
|
||||
let rowClass = 'cn-nodes-row'
|
||||
if (it.conflicts) {
|
||||
if (conflicts) {
|
||||
rowClass += ' cn-nodes-conflict';
|
||||
}
|
||||
|
||||
@@ -1336,8 +1340,9 @@ export class CustomNodesManager {
|
||||
// `it.name` is a raw node name from getmappings (not the pack name)
|
||||
list.push(`<div class="cn-nodes-name">${sanitizeHTML(String(it.name ?? ''))}</div>`);
|
||||
|
||||
if (it.conflicts) {
|
||||
list.push(`<div class="cn-conflicts-list"><div class="cn-nodes-conflict cn-icon">${icons.conflicts}</div><b>Conflict with</b>${it.conflicts.map(c => {
|
||||
if (conflicts) {
|
||||
const label = it.conflicts ? 'Conflict with enabled packs' : 'Potential conflict if installed/enabled with';
|
||||
list.push(`<div class="cn-conflicts-list"><div class="cn-nodes-conflict cn-icon">${icons.conflicts}</div><b>${label}</b>${conflicts.map(c => {
|
||||
return `<div class="cn-nodes-pack" hash="${c.hash}">${String(c.title ?? '')}</div>`;
|
||||
}).join("<b>,</b>")}</div>`);
|
||||
}
|
||||
@@ -1380,6 +1385,7 @@ export class CustomNodesManager {
|
||||
}
|
||||
|
||||
const conflictsMap = {};
|
||||
const nodesMapByPack = new Map();
|
||||
|
||||
// add nodes data
|
||||
Object.keys(data).forEach(k => {
|
||||
@@ -1392,9 +1398,12 @@ export class CustomNodesManager {
|
||||
// deduped
|
||||
const eList = Array.from(new Set(nodes));
|
||||
|
||||
nodeItem.nodes = eList.length;
|
||||
const nodesMap = {};
|
||||
const nodesMap = nodesMapByPack.get(nodeItem) || {};
|
||||
nodesMapByPack.set(nodeItem, nodesMap);
|
||||
eList.forEach(extName => {
|
||||
if (nodesMap[extName]) {
|
||||
return;
|
||||
}
|
||||
nodesMap[extName] = {
|
||||
name: extName
|
||||
};
|
||||
@@ -1406,6 +1415,7 @@ export class CustomNodesManager {
|
||||
cList.push(nodeItem.key);
|
||||
});
|
||||
nodeItem.nodesMap = nodesMap;
|
||||
nodeItem.nodes = Object.keys(nodesMap).length;
|
||||
} else {
|
||||
// should be removed
|
||||
// console.log("not found", k, title, nodes)
|
||||
@@ -1422,13 +1432,15 @@ export class CustomNodesManager {
|
||||
cList.forEach(key => {
|
||||
const nodeItem = node_packs[key];
|
||||
const extItem = nodeItem.nodesMap[extName];
|
||||
if(!extItem.conflicts) {
|
||||
extItem.conflicts = []
|
||||
const conflictsList = cList.filter(k => k !== key && node_packs[k].state === 'enabled');
|
||||
if (!conflictsList.length) {
|
||||
return;
|
||||
}
|
||||
const conflictsList = cList.filter(k => k !== key);
|
||||
const field = nodeItem.state === 'enabled' ? 'conflicts' : 'potentialConflicts';
|
||||
extItem[field] = [];
|
||||
conflictsList.forEach(k => {
|
||||
const nItem = node_packs[k];
|
||||
extItem.conflicts.push({
|
||||
extItem[field].push({
|
||||
key: k,
|
||||
title: nItem.title,
|
||||
hash: nItem.hash
|
||||
@@ -1442,6 +1454,7 @@ export class CustomNodesManager {
|
||||
if (nodeItem.nodesMap) {
|
||||
nodeItem.nodesList = Object.values(nodeItem.nodesMap);
|
||||
nodeItem.conflicts = nodeItem.nodesList.filter(it => it.conflicts).length;
|
||||
nodeItem.potentialConflicts = nodeItem.nodesList.filter(it => it.potentialConflicts).length;
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -543,6 +543,12 @@ class UnifiedManager:
|
||||
for folder in folders:
|
||||
self.invalid_installations.pop(folder, None)
|
||||
|
||||
def forget_gone_disabled_versions_if_one_is_left(self, node_id):
|
||||
disabled = self.cnr_inactive_nodes.get(node_id, {})
|
||||
gone = [x for x in disabled.values() if not os.path.exists(x)]
|
||||
if len(gone) < len(disabled):
|
||||
self.forget_folders(gone)
|
||||
|
||||
def move_invalid_installation(self, from_path, to_path, enabled):
|
||||
x = self.invalid_installations.pop(from_path, None)
|
||||
if x is not None:
|
||||
@@ -604,7 +610,7 @@ class UnifiedManager:
|
||||
return True
|
||||
|
||||
target = self.cnr_inactive_nodes.get(node_id, None)
|
||||
if target is not None and target == version_spec:
|
||||
if target and any(ver != 'nightly' for ver in target.keys()):
|
||||
return True
|
||||
|
||||
return False
|
||||
@@ -972,7 +978,7 @@ class UnifiedManager:
|
||||
|
||||
if version_spec is None:
|
||||
version_spec = self.resolve_unspecified_version(node_id, guess_mode='inactive')
|
||||
if version is None:
|
||||
if version_spec is None and not self.is_enabled(node_id):
|
||||
return result.fail(f'Specified inactive node not exists: {node_id}')
|
||||
|
||||
if self.is_enabled(node_id, version_spec):
|
||||
@@ -1410,6 +1416,8 @@ class UnifiedManager:
|
||||
|
||||
repo_url = None
|
||||
if version_spec is None:
|
||||
if node_id in self.cnr_map:
|
||||
self.forget_gone_disabled_versions_if_one_is_left(node_id)
|
||||
if self.is_enabled(node_id):
|
||||
return ManagedResult('skip')
|
||||
elif self.is_disabled(node_id):
|
||||
@@ -1858,6 +1866,7 @@ def read_config():
|
||||
return default_conf[key].lower() == 'true' if key in default_conf else False
|
||||
|
||||
manager_util.use_uv = default_conf['use_uv'].lower() == 'true' if 'use_uv' in default_conf else False
|
||||
manager_util.apply_dependency_management_setting(default_conf.get('dependency_management'))
|
||||
manager_util.bypass_ssl = get_bool('bypass_ssl', False)
|
||||
|
||||
return with_valid_values({
|
||||
@@ -2120,11 +2129,10 @@ def execute_install_script(url, repo_path, lazy_mode=False, instant_execution=Fa
|
||||
if os.path.exists(requirements_path) and not no_deps:
|
||||
print("Install: pip packages")
|
||||
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), context.comfy_path, context.manager_files_path)
|
||||
with open(requirements_path, "r") as requirements_file:
|
||||
for line in requirements_file:
|
||||
install_args = manager_util.pip_install_args(line, cm_global.pip_overrides)
|
||||
if install_args:
|
||||
try_install_script(url, repo_path, manager_util.make_pip_cmd(["install", *install_args]), instant_execution=instant_execution)
|
||||
for line in manager_util.read_requirements_lines(requirements_path):
|
||||
install_args = manager_util.pip_install_args(line, cm_global.pip_overrides)
|
||||
if install_args:
|
||||
try_install_script(url, repo_path, manager_util.make_pip_cmd(["install", *install_args]), instant_execution=instant_execution)
|
||||
pip_fixer.fix_broken()
|
||||
|
||||
if os.path.exists(install_script_path):
|
||||
@@ -2376,6 +2384,14 @@ async def get_data_by_mode(mode, filename, channel_url=None):
|
||||
cache_uri = str(manager_util.simple_hash(uri))+'_'+filename
|
||||
cache_uri = os.path.join(manager_util.cache_dir, cache_uri)
|
||||
|
||||
if mode == "remote" and get_config()['network_mode'] != 'offline' and manager_util.is_manager_pip_package():
|
||||
try:
|
||||
json_obj = await manager_util.get_data(uri)
|
||||
manager_util.write_cache_file(cache_uri, json_obj)
|
||||
return json_obj
|
||||
except Exception as e:
|
||||
print(f"[ComfyUI-Manager] Due to a network error, switching to cache mode.\n=> {filename} @ {channel_url}/{mode}\n=> {e}")
|
||||
|
||||
if get_config()['network_mode'] == 'offline' or manager_util.is_manager_pip_package():
|
||||
# offline network mode
|
||||
if os.path.exists(cache_uri):
|
||||
@@ -3070,8 +3086,8 @@ async def get_unified_total_nodes(channel, mode, regsitry_cache_mode='cache'):
|
||||
if cnr_id in unified_manager.active_nodes:
|
||||
# installed
|
||||
state = 'enabled'
|
||||
updatable = unified_manager.is_updatable(cnr_id)
|
||||
active_version = unified_manager.active_nodes[cnr['id']][0]
|
||||
updatable = active_version != 'nightly' and unified_manager.is_updatable(cnr_id)
|
||||
ver = active_version
|
||||
|
||||
if cm_global.try_call(api="cm.is_import_failed_extension", name=unified_manager.active_nodes[cnr_id][1]):
|
||||
@@ -3093,6 +3109,7 @@ async def get_unified_total_nodes(channel, mode, regsitry_cache_mode='cache'):
|
||||
|
||||
item = dict(author=author, title=title, reference=reference, repository=repository, install_type=install_type,
|
||||
description=description, state=state, updatable=updatable, version=ver)
|
||||
item['update-state'] = 'true' if updatable else 'false'
|
||||
|
||||
if active_version:
|
||||
item['active_version'] = active_version
|
||||
|
||||
@@ -1224,8 +1224,10 @@ def check_model_installed(json_obj):
|
||||
filename = item['filename']
|
||||
|
||||
fullpath = os.path.join(folder_paths.models_dir, item['save_path'], filename)
|
||||
subpath = os.path.join(item['save_path'].partition('/')[2], filename)
|
||||
found = os.path.exists(fullpath) or folder_paths.get_full_path(model_dir_name, subpath)
|
||||
|
||||
item['installed'] = 'True' if os.path.exists(fullpath) else 'False'
|
||||
item['installed'] = 'True' if found else 'False'
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(8) as executor:
|
||||
for item in json_obj['models']:
|
||||
|
||||
@@ -35,6 +35,11 @@ message_collapses = [skip_pip_spam]
|
||||
import_failed_extensions = set()
|
||||
cm_global.variables['cm.on_revision_detected_handler'] = []
|
||||
enable_file_logging = True
|
||||
# When file logging is on, strip ANSI color/escape codes from the bytes written to
|
||||
# the disk log so the file stays plain and readable. The console ALWAYS keeps its
|
||||
# original (colored) output -- this only ever touches the file branch of sync_write.
|
||||
# Default on; set `strip_ansi_file_logging = False` in config.ini to keep ANSI in the file.
|
||||
strip_ansi_file_logging = True
|
||||
|
||||
|
||||
def register_message_collapse(f):
|
||||
@@ -95,11 +100,30 @@ def read_unified_resolver_mode():
|
||||
if 'use_unified_resolver' in default_conf:
|
||||
manager_util.use_unified_resolver = default_conf['use_unified_resolver'].lower() == 'true'
|
||||
|
||||
|
||||
def read_dependency_management_mode():
|
||||
# Config: [default] dependency_management = on|off (default on).
|
||||
# Env override: COMFYUI_MANAGER_DEPENDENCY_MANAGEMENT=on|off wins over config.
|
||||
# `off` opts out of automatic Python-package mutation Manager performs at
|
||||
# startup (PIPFixer auto-heal, unified resolver batch).
|
||||
# Intended for distro-packaged / externally-managed Python environments
|
||||
# where the interpreter is read-only (Nix, Guix, system packages, etc.).
|
||||
manager_util.apply_dependency_management_setting(default_conf.get('dependency_management'))
|
||||
|
||||
if not manager_util.dependency_management_enabled:
|
||||
logging.info("[ComfyUI-Manager] dependency management disabled; auto-install/upgrade/uninstall paths will be skipped.")
|
||||
|
||||
|
||||
def check_file_logging():
|
||||
global enable_file_logging
|
||||
if 'file_logging' in default_conf and default_conf['file_logging'].lower() == 'false':
|
||||
enable_file_logging = False
|
||||
|
||||
def check_strip_ansi_file_logging():
|
||||
global strip_ansi_file_logging
|
||||
if 'strip_ansi_file_logging' in default_conf and default_conf['strip_ansi_file_logging'].lower() == 'false':
|
||||
strip_ansi_file_logging = False
|
||||
|
||||
|
||||
def set_git_executable():
|
||||
# read as written: a path of Windows may hold a `%`, which the parser takes as the start of a reference
|
||||
@@ -114,8 +138,10 @@ from .common import git_compat # noqa: E402
|
||||
print(git_compat.BACKEND_LINE, file=sys.stderr)
|
||||
read_uv_mode()
|
||||
read_unified_resolver_mode()
|
||||
read_dependency_management_mode()
|
||||
security_check.security_check()
|
||||
check_file_logging()
|
||||
check_strip_ansi_file_logging()
|
||||
|
||||
# Module-level flag set by startup batch resolver when it succeeds.
|
||||
# Used by execute_lazy_install_script() to skip per-node pip installs.
|
||||
@@ -262,6 +288,10 @@ try:
|
||||
|
||||
pat_tqdm = r'\d+%.*\[(.*?)\]'
|
||||
pat_import_fail = r'seconds \(IMPORT FAILED\):(.*)$'
|
||||
# CSI (ECMA-48) escape sequences: ESC [ <params: digits/;/> <?> <final letter>.
|
||||
# Covers SGR color codes (m), cursor moves, clears, and the tqdm/progress-bar
|
||||
# control codes that also land in the startup log.
|
||||
pat_ansi = r'\x1b\[[0-9;?]*[a-zA-Z]'
|
||||
|
||||
is_start_mode = True
|
||||
|
||||
@@ -369,15 +399,25 @@ try:
|
||||
except OSError:
|
||||
self.console_is_gone = True
|
||||
|
||||
def _file_message(self, message):
|
||||
# The disk log is the ONLY place file content and console content are
|
||||
# allowed to diverge: here we drop ANSI so the file stays plain text.
|
||||
# The console path below always uses the
|
||||
# original, unmodified message, so its coloring is never affected.
|
||||
if strip_ansi_file_logging:
|
||||
return re.sub(pat_ansi, '', message)
|
||||
return message
|
||||
|
||||
def sync_write(self, message, file_only=False):
|
||||
with log_lock:
|
||||
# after close_log() the output goes to the console only
|
||||
if not log_file.closed:
|
||||
file_message = self._file_message(message)
|
||||
timestamp = current_timestamp()
|
||||
if self.last_char != '\n':
|
||||
log_file.write(message)
|
||||
log_file.write(file_message)
|
||||
else:
|
||||
log_file.write(f"[{timestamp}] {message}")
|
||||
log_file.write(f"[{timestamp}] {file_message}")
|
||||
|
||||
try:
|
||||
log_file.flush()
|
||||
@@ -801,7 +841,10 @@ def execute_startup_script():
|
||||
|
||||
# --- Unified dependency resolver: batch resolution at startup ---
|
||||
# Runs unconditionally when enabled, independent of install-scripts.txt existence.
|
||||
if manager_util.use_unified_resolver:
|
||||
if manager_util.use_unified_resolver and not manager_util.dependency_management_enabled:
|
||||
logging.info("[ComfyUI-Manager] dependency management disabled; skipping unified dependency resolver, installs use per-node pip")
|
||||
manager_util.use_unified_resolver = False
|
||||
elif manager_util.use_unified_resolver:
|
||||
try:
|
||||
from .common.unified_dep_resolver import (
|
||||
UnifiedDepResolver,
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
"""
|
||||
Tests for the `dependency_management` opt-out switch without a ComfyUI runtime.
|
||||
|
||||
Load the actual utility module and startup functions with isolated collaborators;
|
||||
never execute startup's host-side registration, network, or interpreter mutations.
|
||||
"""
|
||||
|
||||
import ast
|
||||
import importlib.util
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tempfile
|
||||
import types
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
|
||||
_PACKAGE = Path(__file__).resolve().parents[2] / "comfyui_manager"
|
||||
|
||||
|
||||
def _import_manager_util():
|
||||
# Other tests replace the public module with a resolver stub. Import a fresh
|
||||
# private instance rather than depending on collection order or booting the
|
||||
# package's __init__, which imports the full ComfyUI application.
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"dependency_management_test_util", _PACKAGE / "common" / "manager_util.py"
|
||||
)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
# HTTP is unrelated to dependency policy and is never called by these tests.
|
||||
with mock.patch.dict(sys.modules, {"aiohttp": types.ModuleType("aiohttp")}):
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def _startup_namespace(manager_util):
|
||||
return {
|
||||
"manager_util": manager_util,
|
||||
"os": os,
|
||||
"logging": logging,
|
||||
"default_conf": {},
|
||||
"processed_install": set(),
|
||||
"_unified_resolver_succeeded": False,
|
||||
"comfy_path": "/externally-managed-comfy",
|
||||
"process_wrap": mock.Mock(return_value=0),
|
||||
"is_installed": mock.Mock(return_value=False),
|
||||
"cm_global": types.SimpleNamespace(pip_overrides={}),
|
||||
}
|
||||
|
||||
|
||||
def _load_startup_nodes(namespace, predicate):
|
||||
path = _PACKAGE / "prestartup_script.py"
|
||||
parsed = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
|
||||
nodes = [node for node in parsed.body if predicate(node)]
|
||||
if not nodes:
|
||||
raise AssertionError("Startup policy code was not found")
|
||||
exec(compile(ast.Module(body=nodes, type_ignores=[]), str(path), "exec"), namespace)
|
||||
|
||||
|
||||
class DependencyManagementFlagTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.manager_util = _import_manager_util()
|
||||
self._prev = self.manager_util.dependency_management_enabled
|
||||
self.addCleanup(setattr, self.manager_util, "dependency_management_enabled", self._prev)
|
||||
|
||||
def test_default_is_enabled(self):
|
||||
# Default must preserve today's behavior.
|
||||
self.assertTrue(self._prev)
|
||||
|
||||
def test_environment_is_applied_when_the_module_loads(self):
|
||||
# A cm-cli process loads manager_util without running prestartup_script.
|
||||
for environment, expected in [({"COMFYUI_MANAGER_DEPENDENCY_MANAGEMENT": "off"}, False), ({}, True)]:
|
||||
with self.subTest(environment=environment):
|
||||
with mock.patch.dict(os.environ, environment, clear=True):
|
||||
self.assertEqual(_import_manager_util().dependency_management_enabled, expected)
|
||||
|
||||
def test_pip_fixer_short_circuits_when_disabled(self):
|
||||
self.manager_util.dependency_management_enabled = False
|
||||
|
||||
class _Stub(self.manager_util.PIPFixer):
|
||||
def __init__(self): # bypass parent init
|
||||
pass
|
||||
|
||||
with mock.patch.object(self.manager_util, "get_installed_packages") as patched:
|
||||
_Stub().fix_broken()
|
||||
|
||||
patched.assert_not_called()
|
||||
|
||||
def test_pip_fixer_runs_when_enabled(self):
|
||||
# The enabled path must read the current installed package inventory.
|
||||
self.manager_util.dependency_management_enabled = True
|
||||
|
||||
class _Stub(self.manager_util.PIPFixer):
|
||||
def __init__(self):
|
||||
self.prev_pip_versions = {}
|
||||
self.comfyui_path = "/nonexistent"
|
||||
self.manager_files_path = "/nonexistent"
|
||||
|
||||
class InventoryRead(Exception):
|
||||
pass
|
||||
|
||||
with mock.patch.object(self.manager_util, "get_installed_packages", side_effect=InventoryRead) as patched:
|
||||
with self.assertRaises(InventoryRead):
|
||||
_Stub().fix_broken()
|
||||
|
||||
patched.assert_called_once_with(True)
|
||||
|
||||
def test_make_pip_cmd_not_gated(self):
|
||||
# make_pip_cmd is consulted for both read and write ops (pip list,
|
||||
# pip install, …). Gating it would break read paths the UI relies on.
|
||||
# Assert the helper still produces a runnable command when the flag
|
||||
# is off — gating happens at call sites that perform writes.
|
||||
self.manager_util.dependency_management_enabled = False
|
||||
|
||||
with mock.patch.object(self.manager_util, "get_pip_cmd", return_value=[sys.executable, "-m", "pip"]):
|
||||
cmd = self.manager_util.make_pip_cmd(["list"])
|
||||
install_cmd = self.manager_util.make_pip_cmd(["install", "some-pkg"])
|
||||
self.assertIsInstance(cmd, list)
|
||||
self.assertGreaterEqual(len(cmd), 3)
|
||||
self.assertIn("list", cmd)
|
||||
|
||||
self.assertIn("install", install_cmd)
|
||||
self.assertIn("some-pkg", install_cmd)
|
||||
|
||||
|
||||
class StartupDependencyPolicyTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.manager_util = _import_manager_util()
|
||||
self.namespace = _startup_namespace(self.manager_util)
|
||||
_load_startup_nodes(
|
||||
self.namespace,
|
||||
lambda node: isinstance(node, ast.FunctionDef)
|
||||
and node.name in {"read_dependency_management_mode", "execute_lazy_install_script"},
|
||||
)
|
||||
|
||||
def test_config_off(self):
|
||||
self.namespace["default_conf"]["dependency_management"] = "off"
|
||||
with mock.patch.dict(os.environ, {}, clear=True):
|
||||
self.namespace["read_dependency_management_mode"]()
|
||||
self.assertFalse(self.manager_util.dependency_management_enabled)
|
||||
|
||||
def test_environment_wins_in_both_directions(self):
|
||||
for config, environment, expected in [("off", "on", True), ("on", "off", False)]:
|
||||
with self.subTest(config=config, environment=environment):
|
||||
self.namespace["default_conf"]["dependency_management"] = config
|
||||
with mock.patch.dict(os.environ, {"COMFYUI_MANAGER_DEPENDENCY_MANAGEMENT": environment}, clear=True):
|
||||
self.namespace["read_dependency_management_mode"]()
|
||||
self.assertEqual(self.manager_util.dependency_management_enabled, expected)
|
||||
|
||||
def test_lazy_requirements_of_a_scheduled_install_still_install_when_disabled(self):
|
||||
# An install or update the user scheduled for the restart is explicit: its requirements are installed.
|
||||
self.manager_util.dependency_management_enabled = False
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
Path(directory, "requirements.txt").write_text("example-package==1.0\n")
|
||||
with (
|
||||
mock.patch.object(self.manager_util, "robust_readlines", return_value=["example-package==1.0\n"]),
|
||||
mock.patch.object(self.manager_util, "make_pip_cmd", return_value=["pip", "install", "example-package==1.0"]),
|
||||
):
|
||||
self.namespace["execute_lazy_install_script"](directory, sys.executable)
|
||||
self.namespace["process_wrap"].assert_called_once_with(
|
||||
["pip", "install", "example-package==1.0"], directory
|
||||
)
|
||||
|
||||
def test_lazy_requirements_are_installed_when_enabled(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
Path(directory, "requirements.txt").write_text("example-package==1.0\n")
|
||||
with (
|
||||
mock.patch.object(self.manager_util, "robust_readlines", return_value=["example-package==1.0\n"]),
|
||||
mock.patch.object(self.manager_util, "make_pip_cmd", return_value=["pip", "install", "example-package==1.0"]),
|
||||
):
|
||||
self.namespace["execute_lazy_install_script"](directory, sys.executable)
|
||||
self.namespace["process_wrap"].assert_called_once_with(
|
||||
["pip", "install", "example-package==1.0"], directory
|
||||
)
|
||||
|
||||
def test_explicit_node_install_script_is_not_gated(self):
|
||||
self.manager_util.dependency_management_enabled = False
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
Path(directory, "install.py").write_text("# Explicitly scheduled node installation\n")
|
||||
self.namespace["execute_lazy_install_script"](directory, sys.executable)
|
||||
call = self.namespace["process_wrap"].call_args
|
||||
self.assertEqual(call.args, ([sys.executable, "install.py"], directory))
|
||||
self.assertEqual(call.kwargs["env"]["COMFYUI_FOLDERS_BASE_PATH"], self.namespace["comfy_path"])
|
||||
|
||||
def test_disabled_startup_turns_the_resolver_off_so_installs_use_pip(self):
|
||||
# The resolver batch does not run, so an install must not defer its requirements to it.
|
||||
self.manager_util.dependency_management_enabled = False
|
||||
self.manager_util.use_unified_resolver = True
|
||||
_load_startup_nodes(
|
||||
self.namespace,
|
||||
lambda node: isinstance(node, ast.If)
|
||||
and any(isinstance(part, ast.Attribute) and part.attr == "use_unified_resolver" for part in ast.walk(node.test)),
|
||||
)
|
||||
self.assertFalse(self.manager_util.use_unified_resolver)
|
||||
self.assertFalse(self.namespace["_unified_resolver_succeeded"])
|
||||
|
||||
|
||||
class IsOffValueTest(unittest.TestCase):
|
||||
"""`is_off_value` is the single source of truth for the config/env vocabulary."""
|
||||
|
||||
def setUp(self):
|
||||
self.manager_util = _import_manager_util()
|
||||
|
||||
def test_off_synonyms(self):
|
||||
for value in ("off", "OFF", " false ", "0", "no", "Disabled"):
|
||||
with self.subTest(value=value):
|
||||
self.assertTrue(self.manager_util.is_off_value(value))
|
||||
|
||||
def test_on_values(self):
|
||||
# Anything not in the off vocabulary — including the empty string and
|
||||
# typos — keeps dependency management enabled. Better to be noisy than
|
||||
# to silently swallow installs.
|
||||
for value in ("on", "true", "1", "yes", "enabled", "auto", "", " ", "off-ish"):
|
||||
with self.subTest(value=value):
|
||||
self.assertFalse(self.manager_util.is_off_value(value))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,104 @@
|
||||
"""aria2_download_url keeps the contract of download_url: it returns only when the
|
||||
file is at <model_dir>/<filename> on this machine, and raises otherwise."""
|
||||
import os
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from _install_flags_testutil import import_context
|
||||
|
||||
|
||||
class FakeDownload:
|
||||
def __init__(self, statuses, local_file=None, error_message=None, target=None):
|
||||
self._statuses = list(statuses)
|
||||
self.status = self._statuses.pop(0)
|
||||
self._local_file = local_file # what aria2 writes through the mount when it completes
|
||||
self.error_message = error_message
|
||||
self.total_length = 10
|
||||
self.completed_length = 0
|
||||
self.updates = 0
|
||||
self.files = [type('F', (), {'is_metadata': False, 'path': target})()] if target else []
|
||||
self._write_if_complete()
|
||||
|
||||
def _write_if_complete(self):
|
||||
if self.status == 'complete' and self._local_file:
|
||||
os.makedirs(os.path.dirname(self._local_file), exist_ok=True)
|
||||
open(self._local_file, 'wb').close()
|
||||
|
||||
is_active = property(lambda self: self.status == 'active')
|
||||
is_waiting = property(lambda self: self.status == 'waiting')
|
||||
is_paused = property(lambda self: self.status == 'paused')
|
||||
has_failed = property(lambda self: self.status == 'error')
|
||||
is_complete = property(lambda self: self.status == 'complete')
|
||||
is_removed = property(lambda self: self.status == 'removed')
|
||||
|
||||
def update(self):
|
||||
self.updates += 1
|
||||
if self._statuses:
|
||||
self.status = self._statuses.pop(0)
|
||||
self._write_if_complete()
|
||||
|
||||
|
||||
class FakeAria2:
|
||||
def __init__(self, new, existing=()):
|
||||
self.new, self.existing, self.added = new, list(existing), []
|
||||
|
||||
def get_downloads(self):
|
||||
return self.existing
|
||||
|
||||
def add(self, url, options):
|
||||
self.added.append(dict(options))
|
||||
return [self.new]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def md(tmp_path, monkeypatch):
|
||||
import_context()
|
||||
from comfyui_manager.common import context, manager_downloader
|
||||
monkeypatch.setattr(context, 'comfy_path', str(tmp_path))
|
||||
monkeypatch.setattr(time, 'sleep', lambda s: None)
|
||||
return manager_downloader
|
||||
|
||||
|
||||
def install(md, tmp_path, monkeypatch, fake):
|
||||
monkeypatch.setattr(md, 'aria2', fake)
|
||||
return md.download_url('https://huggingface.co/x/y.safetensors', str(tmp_path / 'models' / 'checkpoints'), 'y.safetensors')
|
||||
|
||||
|
||||
def local(tmp_path):
|
||||
return str(tmp_path / 'models' / 'checkpoints' / 'y.safetensors')
|
||||
|
||||
|
||||
def test_a_download_that_aria2_fails_raises_with_its_message(md, tmp_path, monkeypatch):
|
||||
fake = FakeAria2(FakeDownload(['error'], error_message='Failed to make the directory /models/checkpoints, cause: Permission denied'))
|
||||
with pytest.raises(Exception, match='Permission denied'):
|
||||
install(md, tmp_path, monkeypatch, fake)
|
||||
|
||||
|
||||
def test_a_file_that_aria2_saved_elsewhere_raises(md, tmp_path, monkeypatch):
|
||||
fake = FakeAria2(FakeDownload(['complete'])) # complete, but not through a mount of this models folder
|
||||
with pytest.raises(Exception, match='y.safetensors'):
|
||||
install(md, tmp_path, monkeypatch, fake)
|
||||
|
||||
|
||||
def test_a_queued_download_is_waited_for(md, tmp_path, monkeypatch):
|
||||
download = FakeDownload(['waiting', 'active', 'complete'], local_file=local(tmp_path))
|
||||
fake = FakeAria2(download)
|
||||
install(md, tmp_path, monkeypatch, fake)
|
||||
assert download.is_complete and os.path.exists(local(tmp_path))
|
||||
assert fake.added == [{'dir': '/models/checkpoints', 'out': 'y.safetensors'}]
|
||||
|
||||
|
||||
def test_a_failed_earlier_download_is_not_reused(md, tmp_path, monkeypatch):
|
||||
old = FakeDownload(['error'], target='/models/checkpoints/y.safetensors')
|
||||
fake = FakeAria2(FakeDownload(['complete'], local_file=local(tmp_path)), existing=[old])
|
||||
install(md, tmp_path, monkeypatch, fake)
|
||||
assert len(fake.added) == 1
|
||||
|
||||
|
||||
def test_a_finished_earlier_download_whose_file_is_there_is_reused(md, tmp_path, monkeypatch):
|
||||
os.makedirs(os.path.dirname(local(tmp_path))); open(local(tmp_path), 'wb').close()
|
||||
old = FakeDownload(['complete'], target='/models/checkpoints/y.safetensors')
|
||||
fake = FakeAria2(FakeDownload(['complete']), existing=[old])
|
||||
install(md, tmp_path, monkeypatch, fake)
|
||||
assert fake.added == []
|
||||
@@ -3,7 +3,8 @@
|
||||
The channel is a local HTTP server. The startup cache update and `get_data_by_mode`
|
||||
are the real functions of each server, run against a temporary cache directory and a
|
||||
temporary bundled list. The Manager is laid out as an installed package, so the lists
|
||||
are read from the cache that the startup cache update writes.
|
||||
are read from the cache that the startup cache update writes. In `remote` mode the list
|
||||
is read from the channel, and the cached list is kept when the channel fails (#3590).
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
@@ -51,12 +52,12 @@ def manager_util(tmp_path, monkeypatch):
|
||||
return manager_util
|
||||
|
||||
|
||||
def load_server(server, manager_util, channel_url):
|
||||
def load_server(server, manager_util, channel_url, network_mode="public"):
|
||||
"""The startup cache update and `get_data_by_mode` of `server`, set to read `channel_url`."""
|
||||
async def loaded(*args, **kwargs):
|
||||
pass
|
||||
|
||||
config = {"channel_url": channel_url, "network_mode": "public", "default_cache_as_channel_url": True}
|
||||
config = {"channel_url": channel_url, "network_mode": network_mode, "default_cache_as_channel_url": True}
|
||||
core = SimpleNamespace(get_config=lambda: config, refresh_channel_dict=lambda: None, check_invalid_nodes=lambda: None,
|
||||
unified_manager=SimpleNamespace(reload=loaded, get_custom_nodes=loaded))
|
||||
remote = SimpleNamespace(remote=SimpleNamespace(value="remote"))
|
||||
@@ -162,6 +163,52 @@ def test_list_from_the_channel_is_read_from_the_cache(manager_util, server):
|
||||
assert run(scenario) == (SERVED, SERVED, STARTUP_FILES)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("server", SERVERS)
|
||||
def test_remote_mode_reads_the_list_from_the_channel(manager_util, server):
|
||||
async def scenario(channel, channel_url):
|
||||
_, get_data_by_mode = load_server(server, manager_util, channel_url)
|
||||
remote = await get_data_by_mode("remote", FILENAME)
|
||||
cached = await get_data_by_mode("cache", FILENAME)
|
||||
return remote, cached, channel.requests
|
||||
|
||||
assert run(scenario) == (SERVED, SERVED, 1)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("server", SERVERS)
|
||||
@pytest.mark.parametrize("status, text", NOT_JSON)
|
||||
def test_remote_mode_keeps_the_cached_list_when_the_channel_fails(manager_util, server, status, text):
|
||||
async def scenario(channel, channel_url):
|
||||
start, get_data_by_mode = load_server(server, manager_util, channel_url)
|
||||
await start()
|
||||
channel.serve(status, text)
|
||||
return await get_data_by_mode("remote", FILENAME), channel.requests
|
||||
|
||||
assert run(scenario) == (SERVED, STARTUP_FILES + 1)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("server", SERVERS)
|
||||
@pytest.mark.parametrize("status, text", NOT_JSON)
|
||||
def test_remote_mode_of_an_install_that_is_no_pip_package_asks_the_channel_once_as_before(
|
||||
manager_util, tmp_path, server, status, text):
|
||||
os.makedirs(tmp_path / "custom_nodes")
|
||||
|
||||
async def scenario(channel, channel_url):
|
||||
_, get_data_by_mode = load_server(server, manager_util, channel_url)
|
||||
channel.serve(status, text)
|
||||
return manager_util.is_manager_pip_package(), await get_data_by_mode("remote", FILENAME), channel.requests
|
||||
|
||||
assert run(scenario) == (False, BUNDLED, 1)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("server", SERVERS)
|
||||
def test_remote_mode_does_not_ask_the_channel_when_offline(manager_util, server):
|
||||
async def scenario(channel, channel_url):
|
||||
_, get_data_by_mode = load_server(server, manager_util, channel_url, network_mode="offline")
|
||||
return await get_data_by_mode("remote", FILENAME), channel.requests
|
||||
|
||||
assert run(scenario) == (BUNDLED, 0)
|
||||
|
||||
|
||||
def test_unreadable_local_file_still_reads_as_empty(manager_util):
|
||||
async def scenario(channel, channel_url):
|
||||
path = os.path.join(manager_util.comfyui_manager_path, "broken.json")
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
"""config.ini's `dependency_management` reaches manager_util through both config readers, as cm-cli reads it."""
|
||||
import pytest
|
||||
|
||||
from _install_flags_testutil import import_context, import_reader
|
||||
|
||||
|
||||
@pytest.mark.parametrize("reader", ["glob", "legacy"])
|
||||
@pytest.mark.parametrize("environment, expected", [(None, False), ("on", True)])
|
||||
def test_config_value_is_applied_unless_the_environment_says_otherwise(reader, environment, expected, monkeypatch, tmp_path):
|
||||
core = import_reader(reader)
|
||||
path = tmp_path / "config.ini"
|
||||
path.write_text("[default]\ndependency_management = off\n", encoding="utf-8")
|
||||
monkeypatch.setattr(import_context(), "manager_config_path", str(path))
|
||||
monkeypatch.setattr(core, "cached_config", None)
|
||||
monkeypatch.setattr(core.manager_util, "dependency_management_enabled", True)
|
||||
if environment is None:
|
||||
monkeypatch.delenv("COMFYUI_MANAGER_DEPENDENCY_MANAGEMENT", raising=False)
|
||||
else:
|
||||
monkeypatch.setenv("COMFYUI_MANAGER_DEPENDENCY_MANAGEMENT", environment)
|
||||
|
||||
core.get_config()
|
||||
|
||||
assert core.manager_util.dependency_management_enabled is expected
|
||||
@@ -454,6 +454,109 @@ def test_snapshot_denial_preserves_existing_pack_without_retry(core, monkeypatch
|
||||
assert get.call_count == 1
|
||||
|
||||
|
||||
def disabled_fixture(manager, tmp_path, versions, in_registry_data=True):
|
||||
if in_registry_data:
|
||||
manager.cnr_map['fixture'] = {'id': 'fixture', 'latest_version': {'version': '2.0.0'}}
|
||||
for key in versions:
|
||||
folder = tmp_path / ('.disabled/fixture@' + key.replace('.', '_'))
|
||||
folder.mkdir(parents=True)
|
||||
(folder / '__init__.py').write_text(key)
|
||||
(folder / '.tracking').write_text('__init__.py')
|
||||
manager.cnr_inactive_nodes.setdefault('fixture', {})[key] = str(folder)
|
||||
return manager
|
||||
|
||||
|
||||
def mock_registry_query_and_download(core, monkeypatch):
|
||||
get, download = Mock(return_value=api_response('NodeVersionStatusActive')), Mock()
|
||||
monkeypatch.setattr(core.cnr_utils.requests, 'get', get)
|
||||
monkeypatch.setattr(core.manager_downloader, 'download_url', download)
|
||||
monkeypatch.setattr(core.manager_downloader, 'basic_download_url', download)
|
||||
return get, download
|
||||
|
||||
|
||||
def press_enable(core, manager, node_id):
|
||||
path = Path(core.__file__).with_name('manager_server.py')
|
||||
names = {'do_enable', 'replaces_cnr_with_nightly'}
|
||||
nodes = [node for node in ast.walk(ast.parse(path.read_text(encoding='utf-8')))
|
||||
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in names]
|
||||
allowed = lambda level: True
|
||||
namespace = {'core': SimpleNamespace(unified_manager=manager), 'logging': logging, 'SECURITY_MESSAGE_MIDDLE_P': '',
|
||||
'is_allowed_security_level': allowed, 'security_utils': SimpleNamespace(is_allowed_security_level=allowed)}
|
||||
if core.__name__ == 'comfyui_manager.glob.manager_core':
|
||||
from comfyui_manager.data_models import EnablePackParams, OperationResult
|
||||
namespace.update(OperationResult=OperationResult, EnablePackParams=EnablePackParams)
|
||||
task = EnablePackParams(cnr_id=node_id)
|
||||
else:
|
||||
task = ('row', node_id)
|
||||
exec(compile(ast.Module(nodes, []), str(path), 'exec'), namespace)
|
||||
return asyncio.run(namespace['do_enable'](task))
|
||||
|
||||
|
||||
@pytest.mark.parametrize('key', ['1.0.0', '1.0.0-beta'])
|
||||
def test_install_without_version_restores_the_disabled_version(core, monkeypatch, tmp_path, key):
|
||||
get, download = mock_registry_query_and_download(core, monkeypatch)
|
||||
manager = disabled_fixture(core.UnifiedManager(), tmp_path, [key])
|
||||
|
||||
result = asyncio.run(manager.install_by_id('fixture', instant_execution=True))
|
||||
|
||||
assert (result.result, result.action, (tmp_path / 'fixture/__init__.py').read_text()) == (True, 'enable', key)
|
||||
assert manager.active_nodes['fixture'] == (key, str(tmp_path / 'fixture'))
|
||||
assert (get.call_count, download.call_count) == (0, 0)
|
||||
|
||||
|
||||
def test_enable_without_version_restores_the_disabled_version(core, tmp_path):
|
||||
manager = disabled_fixture(core.UnifiedManager(), tmp_path, ['1.0.0'])
|
||||
|
||||
assert manager.is_disabled('fixture')
|
||||
result = manager.unified_enable('fixture')
|
||||
|
||||
assert (result.result, result.action, (tmp_path / 'fixture/__init__.py').read_text()) == (True, 'enable', '1.0.0')
|
||||
assert not (tmp_path / '.disabled/fixture@1_0_0').exists()
|
||||
|
||||
|
||||
def test_enable_button_answers_success_for_an_enabled_pack_that_the_registry_data_does_not_list(core, tmp_path):
|
||||
manager = disabled_fixture(core.UnifiedManager(), tmp_path, ['0.9.0'], in_registry_data=False)
|
||||
enabled = tmp_path / 'fixture'
|
||||
enabled.mkdir()
|
||||
(enabled / '__init__.py').write_text('1.0.0')
|
||||
manager.active_nodes['fixture'] = ('1.0.0', str(enabled))
|
||||
|
||||
assert press_enable(core, manager, 'fixture') == 'success'
|
||||
assert (enabled / '__init__.py').read_text() == '1.0.0'
|
||||
assert (tmp_path / '.disabled/fixture@0_9_0/__init__.py').read_text() == '0.9.0'
|
||||
|
||||
|
||||
def test_enable_button_says_why_for_a_disabled_pack_that_the_registry_data_does_not_list(core, tmp_path, caplog):
|
||||
manager = disabled_fixture(core.UnifiedManager(), tmp_path, ['1.0.0'], in_registry_data=False)
|
||||
|
||||
assert press_enable(core, manager, 'fixture') == "Failed to enable: 'fixture'"
|
||||
assert 'Specified inactive node not exists: fixture' in caplog.text
|
||||
assert (tmp_path / '.disabled/fixture@1_0_0/__init__.py').read_text() == '1.0.0'
|
||||
assert not (tmp_path / 'fixture').exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('disabled, done, enabled', [
|
||||
(['0.9.0', '1.0.0'], (True, 'enable', None), '0.9.0'),
|
||||
(['1.0.0'], (False, 'enable', 'Specified inactive node path not exists: <folder>'), None),
|
||||
], ids=['an older version is left', 'no version is left'])
|
||||
def test_install_without_version_when_the_newest_disabled_version_was_removed_after_the_scan(
|
||||
core, monkeypatch, tmp_path, disabled, done, enabled,
|
||||
):
|
||||
_, download = mock_registry_query_and_download(core, monkeypatch)
|
||||
manager = disabled_fixture(core.UnifiedManager(), tmp_path, disabled)
|
||||
gone = tmp_path / '.disabled/fixture@1_0_0'
|
||||
for file in gone.iterdir():
|
||||
file.unlink()
|
||||
gone.rmdir()
|
||||
|
||||
result = asyncio.run(manager.install_by_id('fixture', instant_execution=True))
|
||||
|
||||
restored = tmp_path / 'fixture/__init__.py'
|
||||
assert (result.result, result.action, result.msg and result.msg.replace(str(gone), '<folder>')) == done
|
||||
assert (restored.read_text() if restored.exists() else None) == enabled
|
||||
assert download.call_count == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize('core', ['legacy'], indirect=True)
|
||||
def test_reinstall_stops_when_the_installed_folder_cannot_be_moved_aside(core, monkeypatch, tmp_path):
|
||||
get = Mock(return_value=api_response('NodeVersionStatusActive'))
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
"""Form factor the CNR client reports to the registry."""
|
||||
|
||||
import pytest
|
||||
|
||||
from _install_flags_testutil import import_context
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cnr_utils():
|
||||
import_context()
|
||||
from comfyui_manager.common import cnr_utils
|
||||
|
||||
return cnr_utils
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
('system', 'desktop', 'expected'),
|
||||
[
|
||||
('Windows', True, 'desktop-win'),
|
||||
('Darwin', True, 'desktop-mac'),
|
||||
('Linux', True, 'desktop-linux'),
|
||||
('FreeBSD', True, 'other'),
|
||||
('Windows', False, 'git-windows'),
|
||||
('Darwin', False, 'git-mac'),
|
||||
('Linux', False, 'git-linux'),
|
||||
('FreeBSD', False, 'other'),
|
||||
],
|
||||
)
|
||||
def test_form_factor(cnr_utils, monkeypatch, system, desktop, expected):
|
||||
monkeypatch.setattr(cnr_utils.platform, 'system', lambda: system)
|
||||
if desktop:
|
||||
monkeypatch.setenv('__COMFYUI_DESKTOP_VERSION__', '1.0.0')
|
||||
else:
|
||||
monkeypatch.delenv('__COMFYUI_DESKTOP_VERSION__', raising=False)
|
||||
|
||||
assert cnr_utils.get_form_factor() == expected
|
||||
@@ -249,6 +249,31 @@ def test_uninstall_by_id_after_the_registry_list_has_loaded_removes_what_the_sca
|
||||
assert listing(custom_nodes) == []
|
||||
|
||||
|
||||
BAZ_LATEST = next(item['latest_version']['version'] for item in REGISTRY if item['id'] == 'comfyui-baz')
|
||||
|
||||
|
||||
@pytest.mark.parametrize('installed, state, active_version, offered', [
|
||||
('1.0.0', 'enabled', '1.0.0', 'true'),
|
||||
(BAZ_LATEST, 'enabled', BAZ_LATEST, 'false'),
|
||||
('nightly', 'enabled', 'nightly', 'false'),
|
||||
('disabled 1.0.0', 'disabled', None, 'false'),
|
||||
(None, 'not-installed', None, 'false'),
|
||||
])
|
||||
def test_a_pack_that_only_the_registry_lists_offers_update_for_an_older_version_alone(core, custom_nodes, installed,
|
||||
state, active_version, offered):
|
||||
if installed == 'nightly':
|
||||
pack(custom_nodes / 'comfyui-baz', git_url='https://github.com/example/comfyui-baz')
|
||||
elif installed == 'disabled 1.0.0':
|
||||
pack(custom_nodes / '.disabled/comfyui-baz@1_0_0', 'comfyui-baz', version='1.0.0', tracking=True)
|
||||
elif installed is not None:
|
||||
pack(custom_nodes / 'comfyui-baz', 'comfyui-baz', version=installed, tracking=True)
|
||||
reload(core)
|
||||
|
||||
row = asyncio.run(core.get_unified_total_nodes(core.DEFAULT_CHANNEL, 'cache'))['comfyui-baz']
|
||||
|
||||
assert (row['state'], row.get('active_version'), row.get('update-state')) == (state, active_version, offered)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('valid, row, state', [
|
||||
('comfyui-foo', 'comfyui-foo', 'enabled'),
|
||||
('.disabled/comfyui-foo@1_0_1', 'comfyui-foo', 'disabled'),
|
||||
|
||||
@@ -87,10 +87,11 @@ def assigned(name):
|
||||
if isinstance(n, ast.Assign) and [t.id for t in n.targets if isinstance(t, ast.Name)] == [name])
|
||||
|
||||
|
||||
def writing_loggers(stdout, stderr, log_file):
|
||||
def writing_loggers(stdout, stderr, log_file, strip=True):
|
||||
return loggers(stdout, stderr, log_file=log_file, log_lock=threading.Lock(), std_log_lock=threading.Lock(),
|
||||
current_timestamp=lambda: "12:00:00", write_stdout=stdout.write, write_stderr=stderr.write,
|
||||
re=re, pat_tqdm=assigned("pat_tqdm"), message_collapses=[], is_start_mode=False)
|
||||
re=re, pat_tqdm=assigned("pat_tqdm"), pat_ansi=assigned("pat_ansi"),
|
||||
strip_ansi_file_logging=strip, message_collapses=[], is_start_mode=False)
|
||||
|
||||
|
||||
def recording_stream():
|
||||
@@ -98,10 +99,10 @@ def recording_stream():
|
||||
return SimpleNamespace(write=written.append, flush=lambda: None), written
|
||||
|
||||
|
||||
def writing_logger(log_file):
|
||||
def writing_logger(log_file, strip=True):
|
||||
"""The stderr logger with what its writes need, and the list of what reached the console."""
|
||||
stream, console = recording_stream()
|
||||
_, err = writing_loggers(stream, stream, log_file)
|
||||
_, err = writing_loggers(stream, stream, log_file, strip)
|
||||
return err, console
|
||||
|
||||
|
||||
@@ -270,6 +271,20 @@ def test_open_log_file_gets_what_is_written():
|
||||
assert console == ["first\n"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("strip, file_text", [
|
||||
(True, "colored\n"),
|
||||
(False, "\x1b[32mcolored\x1b[0m\n"),
|
||||
])
|
||||
def test_file_logging_strips_ansi_codes_and_the_console_keeps_them(strip, file_text):
|
||||
log_file = LogFile()
|
||||
logger, console = writing_logger(log_file, strip)
|
||||
|
||||
logger.sync_write("\x1b[32mcolored\x1b[0m\n")
|
||||
|
||||
assert log_file.written == [file_text]
|
||||
assert console == ["\x1b[32mcolored\x1b[0m\n"]
|
||||
|
||||
|
||||
def test_closed_log_file_is_left_alone():
|
||||
log_file = LogFile(closed=True)
|
||||
logger, console = writing_logger(log_file)
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import concurrent.futures
|
||||
import os
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from legacy_html_testutil import PACKAGE, load_functions
|
||||
|
||||
KEYS = ("checkpoints", "controlnet")
|
||||
CORES = {"legacy": PACKAGE / "legacy/manager_server.py", "glob": PACKAGE / "glob/utils/model_utils.py"}
|
||||
|
||||
|
||||
def installed(tmp_path, core, save_path, file):
|
||||
folders = {key: [str(tmp_path / "models" / key), str(tmp_path / "extra" / key)] for key in KEYS}
|
||||
path = tmp_path / file
|
||||
path.parent.mkdir(parents=True)
|
||||
path.write_bytes(b"")
|
||||
|
||||
def get_full_path(key, name):
|
||||
return next((os.path.join(folder, name) for folder in folders.get(key, [])
|
||||
if os.path.isfile(os.path.join(folder, name))), None)
|
||||
|
||||
def get_filename_list(key):
|
||||
return [os.path.relpath(os.path.join(root, name), folder)
|
||||
for folder in folders.get(key, []) for root, _, names in os.walk(folder) for name in names]
|
||||
|
||||
folder_paths = SimpleNamespace(models_dir=str(tmp_path / "models"),
|
||||
folder_names_and_paths={key: (paths, set()) for key, paths in folders.items()},
|
||||
get_folder_paths=lambda key: folders[key],
|
||||
get_filename_list=get_filename_list, get_full_path=get_full_path)
|
||||
namespace = load_functions(CORES[core], {"check_model_installed"},
|
||||
{"os": os, "concurrent": concurrent, "folder_paths": folder_paths,
|
||||
"model_dir_name_map": {}, "MODEL_DIR_NAMES": KEYS})
|
||||
|
||||
row = {"name": "m", "type": "checkpoint", "base": "SD1.5", "save_path": save_path,
|
||||
"filename": "model.safetensors", "url": "https://example.invalid/model.safetensors"}
|
||||
namespace["check_model_installed"]({"models": [row]})
|
||||
return row.get("installed")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("core", CORES)
|
||||
def test_model_in_a_subfolder_of_an_extra_model_path_is_installed(tmp_path, core):
|
||||
assert installed(tmp_path, core, "checkpoints/SD1.5", "extra/checkpoints/SD1.5/model.safetensors") == "True"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("core", CORES)
|
||||
@pytest.mark.parametrize("save_path, file, expected", [
|
||||
("checkpoints/SD1.5", "models/checkpoints/SD1.5/model.safetensors", "True"),
|
||||
("checkpoints/SD1.5", "extra/checkpoints/model.safetensors", "True"),
|
||||
("RGT/RGT", "models/RGT/RGT/model.safetensors", "True"),
|
||||
("checkpoints/SD1.5", "extra/checkpoints/SDXL/model.safetensors", "False"),
|
||||
("checkpoints/SD1.5", "extra/controlnet/SD1.5/model.safetensors", "False"),
|
||||
("RGT/RGT", "extra/RGT/RGT/model.safetensors", "False"),
|
||||
], ids=["install folder", "top of an extra folder", "folder of no key", "other subfolder", "folder of another key",
|
||||
"extra folder of no key"])
|
||||
def test_other_layouts_keep_their_state(tmp_path, core, save_path, file, expected):
|
||||
assert installed(tmp_path, core, save_path, file) == expected
|
||||
@@ -0,0 +1,76 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from js_lift import NODE, JsSource, run_node, slice_braced, slice_object_entry
|
||||
|
||||
JS = JsSource(Path(os.environ.get("MANAGER_JS_DIR") or (Path(__file__).resolve().parent.parent / "comfyui_manager" / "js")))
|
||||
MANAGER = "custom-nodes-manager.js"
|
||||
|
||||
|
||||
def nodes_column_and_list_text(states, mappings):
|
||||
source = JS.text(MANAGER)
|
||||
nodes_column = slice_object_entry(source, 'id: "nodes"')
|
||||
show_nodes = source[source.index("\tshowNodes(d) {"):source.index("\tasync loadNodes(node_packs) {")]
|
||||
rows = {key: {"key": key, "title": key, "hash": key, "state": state} for key, state in states.items()}
|
||||
script = "\n".join([
|
||||
JS.lift_declaration("common.js", "export function sanitizeHTML("),
|
||||
"const icons = {conflicts: '<svg></svg>'};",
|
||||
"const manager_instance = {datasrc_combo: {value: 'cache'}};",
|
||||
"const fetchData = async () => ({data: %s});" % json.dumps(mappings),
|
||||
"const text = (html) => html.replace(/<[^>]+>/g, ' ').replace(/\\s+/g, ' ').trim();",
|
||||
"const column = {%s};" % nodes_column,
|
||||
"const manager = {showStatus() {}, flyover: {show(title, body) { manager.list = body; }},",
|
||||
slice_braced(source, "\tasync loadNodes(node_packs) ") + ",",
|
||||
show_nodes + "};",
|
||||
"const rows = %s;" % json.dumps(rows),
|
||||
"await manager.loadNodes(rows);",
|
||||
"console.log(JSON.stringify(Object.fromEntries(Object.entries(rows).map(([key, row]) => {",
|
||||
" manager.list = '';",
|
||||
" manager.showNodes({rowItem: row});",
|
||||
" return [key, [text(column.formatter(row.nodes, row, column)), text(manager.list)]];",
|
||||
"}))));",
|
||||
])
|
||||
return {key: tuple(value) for key, value in run_node(script).items()}
|
||||
|
||||
|
||||
SHARED = {"A": [["X"], {}], "B": [["X"], {}]}
|
||||
CASES = {
|
||||
"an enabled pack and a pack that is not installed": (
|
||||
{"A": "enabled", "B": "not-installed"}, SHARED,
|
||||
{"A": ("1 node", "1 X"),
|
||||
"B": ("1 node 1 potential conflict", "1 X Potential conflict if installed/enabled with A")}),
|
||||
"an enabled pack and a disabled pack": (
|
||||
{"A": "enabled", "B": "disabled"}, SHARED,
|
||||
{"A": ("1 node", "1 X"),
|
||||
"B": ("1 node 1 potential conflict", "1 X Potential conflict if installed/enabled with A")}),
|
||||
"two enabled packs": (
|
||||
{"A": "enabled", "B": "enabled"}, SHARED,
|
||||
{"A": ("1 node 1 conflict", "1 X Conflict with enabled packs B"),
|
||||
"B": ("1 node 1 conflict", "1 X Conflict with enabled packs A")}),
|
||||
"a disabled pack and a pack that is not installed": (
|
||||
{"A": "disabled", "B": "not-installed"}, SHARED,
|
||||
{"A": ("1 node", "1 X"), "B": ("1 node", "1 X")}),
|
||||
"a disabled pack beside two enabled packs, one of which lists a node twice": (
|
||||
{"A": "enabled", "B": "enabled", "C": "disabled"},
|
||||
{"A": [["Shared", "Shared", "Own"], {}], "B": [["Shared"], {}], "C": [["Shared"], {}]},
|
||||
{"A": ("2 nodes 1 conflict", "1 Shared Conflict with enabled packs B 2 Own"),
|
||||
"B": ("1 node 1 conflict", "1 Shared Conflict with enabled packs A"),
|
||||
"C": ("1 node 1 potential conflict", "1 Shared Potential conflict if installed/enabled with A , B")}),
|
||||
"an enabled pack whose node only a pack without a row lists": (
|
||||
{"A": "enabled"}, SHARED,
|
||||
{"A": ("1 node", "1 X")}),
|
||||
"packs found by the end of their URL and by their title": (
|
||||
{"A": "enabled", "B": "disabled"},
|
||||
{"https://example.invalid/A": [["X"], {}], "other": [["X"], {"title_aux": "B"}]},
|
||||
{"A": ("1 node", "1 X"),
|
||||
"B": ("1 node 1 potential conflict", "1 X Potential conflict if installed/enabled with A")}),
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="node is required to execute the lifted production JS")
|
||||
@pytest.mark.parametrize("states, mappings, expected", CASES.values(), ids=CASES.keys())
|
||||
def test_only_an_enabled_pack_is_a_conflict_and_any_other_pack_sees_a_potential_one(states, mappings, expected):
|
||||
assert nodes_column_and_list_text(states, mappings) == expected
|
||||
@@ -0,0 +1,111 @@
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from html.parser import HTMLParser
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from js_lift import NODE, JsSource, run_node, slice_braced, slice_object_entry
|
||||
|
||||
JS = JsSource(Path(os.environ.get("MANAGER_JS_DIR") or (Path(__file__).resolve().parent.parent / "comfyui_manager" / "js")))
|
||||
MANAGER = "custom-nodes-manager.js"
|
||||
|
||||
pytestmark = pytest.mark.skipif(NODE is None, reason="node is required to execute the lifted production JS")
|
||||
|
||||
|
||||
class NodesFlyover(HTMLParser):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.nodes = {}
|
||||
self.open = []
|
||||
self.row = None
|
||||
|
||||
def handle_starttag(self, tag, attrs):
|
||||
if tag == "div":
|
||||
self.open.append((dict(attrs).get("class") or "").split())
|
||||
|
||||
def handle_endtag(self, tag):
|
||||
if tag == "div":
|
||||
self.open.pop()
|
||||
|
||||
def handle_data(self, data):
|
||||
if self.open and "cn-nodes-name" in self.open[-1]:
|
||||
self.row = data
|
||||
self.nodes[data] = []
|
||||
elif self.open and "cn-nodes-pack" in self.open[-1] and self.row is not None:
|
||||
self.nodes[self.row].append(data)
|
||||
|
||||
|
||||
def shown(packs, mappings):
|
||||
source = JS.text(MANAGER)
|
||||
column = slice_object_entry(source, 'id: "nodes",')
|
||||
script = """
|
||||
%s
|
||||
%s
|
||||
const formatter = %s;
|
||||
const manager_instance = {datasrc_combo: {value: 'cache'}};
|
||||
const fetchData = async () => ({data: %s});
|
||||
const manager = {
|
||||
showStatus() {},
|
||||
flyover: {show(title, body) { manager.body = body; }},
|
||||
%s,
|
||||
%s
|
||||
};
|
||||
const packs = %s;
|
||||
await manager.loadNodes(packs);
|
||||
const rows = {};
|
||||
for (const [key, rowItem] of Object.entries(packs)) {
|
||||
manager.body = '';
|
||||
manager.showNodes({rowItem});
|
||||
rows[key] = {column: String(formatter(null, rowItem, {})), flyover: manager.body};
|
||||
}
|
||||
console.log(JSON.stringify(rows));
|
||||
""" % (JS.lift_declaration("common.js", "export function sanitizeHTML("),
|
||||
JS.lift_declaration("common.js", "export const icons = "),
|
||||
column[column.index("formatter:") + len("formatter:"):].strip(),
|
||||
json.dumps(mappings),
|
||||
slice_braced(source, "\tasync loadNodes(node_packs) "),
|
||||
JS.lift_span(MANAGER, "\tshowNodes(d) {", "\t\tthis.flyover.show(titleHtml, bodyHtml);\n\t}"),
|
||||
json.dumps({key: {"key": key, "title": key, "hash": key, "state": "enabled"} for key in packs}))
|
||||
view = {}
|
||||
for key, row in run_node(script).items():
|
||||
flyover = NodesFlyover()
|
||||
flyover.feed(row["flyover"])
|
||||
view[key] = {"column": " ".join(re.sub(r"<[^>]+>", " ", row["column"]).split()), "nodes": flyover.nodes}
|
||||
return view
|
||||
|
||||
|
||||
def test_the_nodes_of_both_mappings_are_shown_and_each_conflict_names_its_peer():
|
||||
view = shown(["A", "B"], {
|
||||
"https://example.invalid/A": [["Shared"], {}],
|
||||
"other": [["Own"], {"title_aux": "A"}],
|
||||
"B": [["Shared"], {}],
|
||||
})
|
||||
|
||||
assert view == {
|
||||
"A": {"column": "2 nodes 1 conflict", "nodes": {"Shared": ["B"], "Own": []}},
|
||||
"B": {"column": "1 node 1 conflict", "nodes": {"Shared": ["A"]}},
|
||||
}
|
||||
|
||||
|
||||
def test_a_node_in_both_mappings_of_a_pack_is_no_conflict_with_itself():
|
||||
view = shown(["A"], {
|
||||
"https://example.invalid/A": [["Shared"], {}],
|
||||
"other": [["Shared"], {"title_aux": "A"}],
|
||||
})
|
||||
|
||||
assert view == {"A": {"column": "1 node", "nodes": {"Shared": []}}}
|
||||
|
||||
|
||||
def test_a_node_in_both_mappings_of_a_pack_names_another_pack_once():
|
||||
view = shown(["A", "B"], {
|
||||
"https://example.invalid/A": [["Shared"], {}],
|
||||
"other": [["Shared"], {"title_aux": "A"}],
|
||||
"B": [["Shared"], {}],
|
||||
})
|
||||
|
||||
assert view == {
|
||||
"A": {"column": "1 node 1 conflict", "nodes": {"Shared": ["B"]}},
|
||||
"B": {"column": "1 node 1 conflict", "nodes": {"Shared": ["A"]}},
|
||||
}
|
||||
@@ -387,6 +387,179 @@ def test_requirements_file_lines_are_checked_before_install(set_lists, monkeypat
|
||||
assert requirements == ['scipy --index-url https://example.invalid/simple', 'pyyaml>=6']
|
||||
|
||||
|
||||
def ansi_open(file, mode='r', *args, encoding=None, **kwargs):
|
||||
if 'b' not in mode and encoding is None:
|
||||
encoding = 'cp1252'
|
||||
return open(file, mode, *args, encoding=encoding, **kwargs)
|
||||
|
||||
|
||||
def ansi_core(monkeypatch, tree, executed):
|
||||
core = import_reader(tree)
|
||||
monkeypatch.setattr(core.manager_funcs, 'run_script', lambda cmd, cwd='.': executed.append(cmd) or 0)
|
||||
monkeypatch.setattr(core.manager_util, 'PIPFixer', lambda *args: SimpleNamespace(fix_broken=lambda: None))
|
||||
monkeypatch.setattr(core.manager_util, 'use_unified_resolver', False)
|
||||
for module in (core, core.manager_util):
|
||||
monkeypatch.setattr(module, 'open', ansi_open, raising=False)
|
||||
return core
|
||||
|
||||
|
||||
def chardet_names(monkeypatch, encoding):
|
||||
import chardet
|
||||
monkeypatch.setattr(chardet, 'detect', lambda data: {'encoding': encoding, 'confidence': 0.06, 'language': None})
|
||||
|
||||
|
||||
NOT_TEXT = bytes(range(128, 256)) * 4 + b'\nnumpy\n'
|
||||
MAC_ROMAN = '# Dependências do nó – instalação\nrich\n'.encode('mac_roman')
|
||||
SHIFT_JIS = 'numpy\nrich # 画像処理用\n'.encode('shift_jis')
|
||||
EBCDIC = 'pandas\r'.encode('cp500')
|
||||
|
||||
|
||||
@pytest.mark.parametrize('tree', ['glob', 'legacy'])
|
||||
def test_utf8_requirements_file_with_non_ascii_comments_is_installed_in_a_windows_code_page(
|
||||
set_lists, monkeypatch, tmp_path, tree):
|
||||
(tmp_path / 'requirements.txt').write_text('# Łukasz ✨ 中文\nnumpy\nrich # Łukasz\n', encoding='utf-8')
|
||||
executed = []
|
||||
core = ansi_core(monkeypatch, tree, executed)
|
||||
|
||||
assert core.execute_install_script(None, str(tmp_path), instant_execution=True) is True
|
||||
assert [cmd[cmd.index('install') + 1:] for cmd in executed] == [['numpy'], ['rich']]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('content, named, installed', [
|
||||
(MAC_ROMAN, 'ISO-8859-5', ['rich']),
|
||||
(SHIFT_JIS, 'cp1006', ['numpy', 'rich']),
|
||||
], ids=['mac-roman-chardet-7.1.0', 'shift-jis-chardet-7.1.0'])
|
||||
@pytest.mark.parametrize('tree', ['glob', 'legacy'])
|
||||
def test_requirements_file_whose_comment_chardet_misreads_is_installed(
|
||||
set_lists, monkeypatch, tmp_path, tree, content, named, installed):
|
||||
(tmp_path / 'requirements.txt').write_bytes(content)
|
||||
executed = []
|
||||
core = ansi_core(monkeypatch, tree, executed)
|
||||
chardet_names(monkeypatch, named)
|
||||
|
||||
assert core.execute_install_script(None, str(tmp_path), instant_execution=True) is True
|
||||
assert [cmd[cmd.index('install') + 1:] for cmd in executed] == [[name] for name in installed]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('text, installed', [
|
||||
('\u3000# 依存関係\nnumpy\n', ['numpy']),
|
||||
('# 依存関係\nnumpy\n\u00a0\u00a0\nrich\n', ['numpy', 'rich']),
|
||||
], ids=['comment-indented-with-an-ideographic-space', 'line-of-no-break-spaces'])
|
||||
@pytest.mark.parametrize('tree', ['glob', 'legacy'])
|
||||
def test_utf8_requirements_file_with_non_ascii_blanks_is_installed(
|
||||
set_lists, monkeypatch, tmp_path, tree, text, installed):
|
||||
(tmp_path / 'requirements.txt').write_text(text, encoding='utf-8')
|
||||
executed = []
|
||||
core = ansi_core(monkeypatch, tree, executed)
|
||||
chardet_names(monkeypatch, 'utf-8')
|
||||
|
||||
assert core.execute_install_script(None, str(tmp_path), instant_execution=True) is True
|
||||
assert [cmd[cmd.index('install') + 1:] for cmd in executed] == [[name] for name in installed]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('tree', ['glob', 'legacy'])
|
||||
def test_requirement_line_with_a_no_break_space_fails_the_install(set_lists, monkeypatch, tmp_path, tree):
|
||||
(tmp_path / 'requirements.txt').write_text('numpy\u00a0 # 依存関係\nrich\n', encoding='utf-8')
|
||||
executed = []
|
||||
core = ansi_core(monkeypatch, tree, executed)
|
||||
chardet_names(monkeypatch, 'utf-8')
|
||||
|
||||
with pytest.raises(UnicodeDecodeError) as error:
|
||||
core.execute_install_script(None, str(tmp_path), instant_execution=True)
|
||||
assert str(error.value) == "'charmap' codec can't decode byte 0x9d in position 12: character maps to <undefined>"
|
||||
assert executed == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize('tree', ['glob', 'legacy'])
|
||||
def test_requirement_with_a_non_ascii_url_fragment_fails_the_install(set_lists, monkeypatch, tmp_path, tree):
|
||||
(tmp_path / 'requirements.txt').write_text('git+https://host/repo#egg=依存\nrich\n', encoding='utf-8')
|
||||
executed = []
|
||||
core = ansi_core(monkeypatch, tree, executed)
|
||||
chardet_names(monkeypatch, 'utf-8')
|
||||
|
||||
with pytest.raises(UnicodeDecodeError):
|
||||
core.execute_install_script(None, str(tmp_path), instant_execution=True)
|
||||
assert executed == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize('tree', ['glob', 'legacy'])
|
||||
def test_utf16_requirements_file_with_byte_order_mark_installs_only_its_requirements(
|
||||
set_lists, monkeypatch, tmp_path, tree):
|
||||
(tmp_path / 'requirements.txt').write_bytes('# 依赖列表\nrich\n'.encode('utf-16'))
|
||||
executed = []
|
||||
core = ansi_core(monkeypatch, tree, executed)
|
||||
chardet_names(monkeypatch, 'utf-16-le')
|
||||
|
||||
assert core.execute_install_script(None, str(tmp_path), instant_execution=True) is True
|
||||
assert [cmd[cmd.index('install') + 1:] for cmd in executed] == [['rich']]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('named', ['ISO-8859-5', 'MacCyrillic', None],
|
||||
ids=['chardet-7.7.0', 'chardet-7.1.0', 'no-encoding'])
|
||||
@pytest.mark.parametrize('tree', ['glob', 'legacy'])
|
||||
def test_requirements_file_that_is_not_text_fails_the_install(set_lists, monkeypatch, tmp_path, tree, named):
|
||||
(tmp_path / 'requirements.txt').write_bytes(NOT_TEXT)
|
||||
executed = []
|
||||
core = ansi_core(monkeypatch, tree, executed)
|
||||
chardet_names(monkeypatch, named)
|
||||
|
||||
with pytest.raises(UnicodeDecodeError) as error:
|
||||
core.execute_install_script(None, str(tmp_path), instant_execution=True)
|
||||
assert str(error.value) == "'charmap' codec can't decode byte 0x81 in position 1: character maps to <undefined>"
|
||||
assert executed == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize('named', ['cp500', 'cp1140'])
|
||||
@pytest.mark.parametrize('tree', ['glob', 'legacy'])
|
||||
def test_requirements_file_that_an_ebcdic_guess_reads_as_ascii_fails_the_install(
|
||||
set_lists, monkeypatch, tmp_path, tree, named):
|
||||
(tmp_path / 'requirements.txt').write_bytes(EBCDIC)
|
||||
executed = []
|
||||
core = ansi_core(monkeypatch, tree, executed)
|
||||
chardet_names(monkeypatch, named)
|
||||
|
||||
with pytest.raises(UnicodeDecodeError) as error:
|
||||
core.execute_install_script(None, str(tmp_path), instant_execution=True)
|
||||
assert str(error.value) == "'charmap' codec can't decode byte 0x81 in position 1: character maps to <undefined>"
|
||||
assert executed == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize('tree', ['glob', 'legacy'])
|
||||
def test_requirements_file_with_carriage_return_line_ends_is_installed(set_lists, monkeypatch, tmp_path, tree):
|
||||
(tmp_path / 'requirements.txt').write_bytes('pandas\r# 依存関係\r'.encode('utf-8'))
|
||||
executed = []
|
||||
core = ansi_core(monkeypatch, tree, executed)
|
||||
chardet_names(monkeypatch, 'utf-8')
|
||||
|
||||
assert core.execute_install_script(None, str(tmp_path), instant_execution=True) is True
|
||||
assert [cmd[cmd.index('install') + 1:] for cmd in executed] == [['pandas']]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('entry_point', ['glob manager', 'legacy manager', 'startup', 'resolver'])
|
||||
def test_the_other_installers_take_the_requirements_chardet_reads(
|
||||
set_lists, monkeypatch, tmp_path, entry_point):
|
||||
(tmp_path / 'requirements.txt').write_bytes(MAC_ROMAN)
|
||||
executed = []
|
||||
core = ansi_core(monkeypatch, 'legacy' if entry_point == 'legacy manager' else 'glob', executed)
|
||||
chardet_names(monkeypatch, 'ISO-8859-5')
|
||||
|
||||
if entry_point == 'startup':
|
||||
startup = load_prestartup(
|
||||
process_wrap=lambda cmd, cwd=None, **kwargs: executed.append(cmd) or 0,
|
||||
processed_install=set(), _unified_resolver_succeeded=False)
|
||||
startup['execute_lazy_install_script'](str(tmp_path), 'python')
|
||||
elif entry_point == 'resolver':
|
||||
from comfyui_manager.common import unified_dep_resolver
|
||||
monkeypatch.setattr(unified_dep_resolver, 'manager_util', core.manager_util)
|
||||
collected = unified_dep_resolver.UnifiedDepResolver(node_pack_paths=[str(tmp_path)]).collect_requirements()
|
||||
executed.extend(['install', r.spec] for r in collected.requirements)
|
||||
else:
|
||||
monkeypatch.setattr(core.unified_manager, 'processed_install', set())
|
||||
core.unified_manager.execute_install_script(None, str(tmp_path), instant_execution=True)
|
||||
|
||||
assert [cmd[cmd.index('install') + 1:] for cmd in executed] == [['rich']]
|
||||
|
||||
|
||||
# Every base command make_pip_cmd() can produce.
|
||||
PIP_COMMANDS = [
|
||||
['python', '-m', 'pip'], ['python', '-s', '-m', 'pip'],
|
||||
|
||||
+1262
-40
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user