Compare commits

...
Author SHA1 Message Date
Dr.Lt.Data 063e845fc8 v4: An install by a git URL takes a commit and a URL with a user
`cm-cli install <url>` and Install via Git URL of the legacy UI cloned the
whole text as the URL. `https://host/owner/repo@<commit>` failed, where
`main` installs that commit, and an SSH URL of a host other than GitHub,
`git@host:owner/repo.git`, was cloned from github.com and failed (#3627).

- `extract_url_and_commit_id` moves to `common/git_utils.py` and skips the
  host part first, so the `@` of a user is not the one that names a commit.
  The copy of the glob core split at the user
- The legacy install takes the commit off the URL and checks it out, as the
  glob install does
- `cm-cli install <url>` and `cm-cli install-deps` install through the glob
  core
- On Windows the clone is made by `git_helper.py --clone`, which now takes
  the commit as one more argument and checks it out
- A clone whose checkout fails is removed, in both cores and for the clone
  of the helper script: the install failed and left the clone at the tip of
  the default branch
- `checkout` of the pygit2 backend takes a short commit id, and a branch of
  `origin` as a local branch that tracks it, when the name is nothing else,
  as git does
- `normalize_to_github_id` does not read a text with a `:` as the short
  `owner/repo` of a GitHub repository
- `normalize_to_github_id` looks for `github` in the host of the URL, not
  in the whole text: a URL of another host with that word in its user or
  its path was cloned from github.com
- Add tests: each spelling of a URL is cloned through both cores from a
  repository of the test, and ends at its commit
- Add a CHANGELOG entry

The change of the split for main is #3628.
2026-12-05 23:23:55 +09:00
Dr.Lt.Data bca61a9d27 v4: An install by a git URL is a clone, and its failure leaves the version enabled (#3662)
`gitclone_install` of the glob core asked the registry for the latest
version of the nodepack when the URL was of a repository that the registry
lists, as `main` does since #1813. The legacy core clones its nightly, and
it is the one that `cm-cli` and the route of the legacy server call. The
glob function has no caller yet.

A nightly install over an enabled version of the registry disabled that
version before the clone, and left the nodepack with no enabled version when
the clone failed.

- The glob install asks for the nightly of such a nodepack, as the legacy
  install does
- `_install_git` of both cores enables the version again when the clone
  fails. This is the install by a URL, of `<id>@nightly`, and a switch to
  nightly
- Both cores pass `instant_execution` and `no_deps` on to the install by a
  URL, which dropped them, and the URL, which `install_by_id` now takes as
  `reinstall_by_id` does. The clone is of the URL that was given: the legacy
  install cloned the repository that the channel has under the name of the
  nodepack, which can be another repository of the same name
- Add tests for both cores: the URL of a repository that the registry lists
  is cloned from a repository of the test with the flags of the caller and
  no version is asked for, also over an enabled version, and that version
  is enabled again when the clone fails
- Add CHANGELOG entries

The change for main is #3661.
2026-12-05 21:13:49 +09:00
Dr.Lt.Data ec562aab5d v4: A folder can be a channel of a private network (#3654)
A line of `channels.list` that names a folder, such as
`private::\\NAS\comfy\channel`, was refused with
`An invalid channel was used`: `normalize_channel` took an https URL,
an http URL with `http_channel_enabled`, or the name of a channel, and
raised `InvalidChannel` for the folder that the name stood for.

- `normalize_channel` of both cores returns a UNC path or an absolute
  path as it is with `network_mode = private`. `load_nightly` still
  refuses a channel that `channels.list` does not have, so a folder
  that a request names is refused before anything is read
- With another `network_mode` the folder is refused with a reason that
  names the channel by its name of `channels.list`, and the setting.
  No reason has the URL or the folder of a channel in it
- The reason is what the list route of the legacy server answers with
  403 in place of a 500, what the legacy Custom Nodes Manager shows in
  place of `Failed to get custom node list.`, what an install reports,
  and what `cm-cli` prints in place of a traceback. The start of both
  servers logs it as a warning and completes
- Add tests and a CHANGELOG entry

The same change for main is #2669.
2026-12-05 10:34:22 +09:00
Dr.Lt.Data ce965cdbcf v4: A list request without mode is answered (#3653)
`GET /v2/customnode/getmappings` of both servers, and
`/v2/customnode/getlist` and `/v2/externalmodel/getlist` of the legacy
server, read `mode` with `request.rel_url.query["mode"]` and answered
500 with `KeyError: 'mode'` for a request without it (#2740).

- The four handlers read `mode` with `cache` as its default
- Add a test for the four handlers: a request without `mode` gets the
  answer of `mode=cache`, which is not the answer of `mode=local`
- `tests/test_legacy_secgate_other_paths.py` puts back the `get_data` that
  it replaces for its own cases. It left the replacement in place, and a
  test that ran after it read no file
- Add a CHANGELOG entry

The same change for main is #2741.
2026-12-04 01:19:38 +09:00
20 changed files with 696 additions and 78 deletions
+66
View File
@@ -9,6 +9,29 @@ and this project adheres to [Semantic Versioning 2.0.0](https://semver.org/spec/
### Added
- A folder can be a channel of a private network. With
`network_mode = private`, a line of `channels.list` can name a folder, such
as `private::\\NAS\comfy\channel` or `private::/srv/comfy/channel`. Such a
line was refused with `An invalid channel was used`: the channel was in the
Channel menu of the legacy UI, and its list did not load. The folder is now
read as a channel, so a closed network needs no web server for its own
`custom-node-list.json`. As for every channel but the default one, its
lists are read at the start with `default_cache_as_channel_url = True`, or
with the database mode `remote`. Only a folder that is written in
`channels.list` is a channel, and only on a private network. A folder that
a request names, or that only `channel_url` of `config.ini` names, is
refused as before.
With another `network_mode` the folder is refused, and the refusal names the
channel as `channels.list` names it and the setting that it needs, not the
folder. The legacy Custom Nodes Manager shows it in place of `Failed to get
custom node list.`, an install from that channel reports it, `cm-cli show`
prints it in place of a traceback, and the start logs it as a warning. A
refused channel no longer stops the tasks of the start with a traceback. For
a channel that `channels.list` does not have, the legacy Custom Nodes
Manager, `cm-cli` and an install say that a channel has to be in
`channels.list`, without its URL or folder.
- An aria2 on the same machine can be the downloader. With aria2 as the
downloader, the Manager asks aria2 to save a file into `/models/...` or
`/custom_nodes`, which is where the container of `docs/en/use_aria2.md`
@@ -44,6 +67,49 @@ and this project adheres to [Semantic Versioning 2.0.0](https://semver.org/spec/
### Fixed
- An install by a git URL takes a commit, and a URL with a user. `cm-cli
install <url>` and **Install via Git URL** of the legacy UI cloned the whole
text as the URL, so `https://host/owner/repo@<commit>` failed, where `main`
installs that commit. They now clone the repository and check out what
follows the last `@` of the path, a commit, a tag or a branch such as
`feature/x`. The `@` of a user is not that one:
`git@host:owner/repo.git`, `ssh://git@host/owner/repo.git` and
`https://user:token@host/owner/repo.git` are cloned whole, and each takes
`@<commit>` after it (#3627, as #3628 for `main`). An install whose commit
is not in the repository fails and leaves no clone. With the pygit2 backend,
a branch of the repository and a short commit id are checked out as well.
An SSH URL of a host other than GitHub, `git@host:owner/repo.git`, was
cloned from `https://github.com/git@host:owner/repo.git` and failed: a text
with one `/` was read as the short `owner/repo` of a GitHub repository. A
text with a `:` is no longer read that way. A URL is taken for a GitHub
repository by its host: a URL of another host with the word `github` in its
user or its path, such as `https://gitlab.example.com/owner/github-tools.git`,
was cloned from `https://github.com/owner/github-tools`. A URL of GitHub is
still cloned as `https://github.com/<owner>/<repo>`, without its user or its
token.
- A nightly install over an enabled version of the registry enables that
version again when the clone fails. The version was disabled first, and the
nodepack was left with no enabled version. This was so for
`cm-cli install <url>` of a repository that the registry lists, for
**Install via Git URL** of the legacy UI, and for an install of `nightly`
over a version.
- `cm-cli install <url>` and **Install via Git URL** of the legacy UI clone
the URL that was given when the registry lists the repository. They cloned
the repository that the channel has under the name of the nodepack, which is
another repository when the channel lists two of that name.
- `cm-cli install <url> --no-deps` leaves the requirements of a repository
that the registry lists. The install of such a repository by its URL dropped
`--no-deps`, and installed the requirements. `cm-cli install-deps` passes
its flags the same way, and they were dropped as well.
- A list request without `mode` is answered. `GET /v2/customnode/getmappings`
and, with the legacy UI, `/v2/customnode/getlist` and
`/v2/externalmodel/getlist` answered 500 with `KeyError: 'mode'` when the
request had no `mode` (#2740). Such a request is now answered as one with
`mode=cache`. The legacy pages always send `mode`, so nothing changes for
them.
- The Version column of the legacy Custom Nodes Manager no longer shows an
older registry version as an update. The column showed `[↑<version>]`
whenever the installed version was not the latest version of the registry,
+14 -5
View File
@@ -36,6 +36,7 @@ from comfyui_manager.common.git_compat import setup_git_environment
from comfyui_manager.common import manager_util
from comfyui_manager.common import cm_global
from comfyui_manager.legacy import manager_core as core
from comfyui_manager.glob import manager_core as glob_core
from comfyui_manager.common import context
from comfyui_manager.legacy.manager_core import unified_manager
from comfyui_manager.common import cnr_utils
@@ -193,9 +194,9 @@ class NodeInstallError(Exception):
def install_node(node_spec_str, is_all=False, cnt_msg='', **kwargs):
raise_on_fail = kwargs.get('raise_on_fail', False)
if core.is_valid_url(node_spec_str):
if glob_core.is_valid_url(node_spec_str):
# install via urls
res = asyncio.run(core.gitclone_install(node_spec_str, no_deps=cmd_ctx.no_deps))
res = asyncio.run(glob_core.gitclone_install(node_spec_str, no_deps=cmd_ctx.no_deps))
if not res.result:
print(res.msg)
print(f"ERROR: An error occurred while installing '{node_spec_str}'.", style="bold red")
@@ -446,7 +447,11 @@ def disable_node(node_spec_str: str, is_all=False, cnt_msg=''):
def show_list(kind, simple=False):
custom_nodes = asyncio.run(unified_manager.get_custom_nodes(channel=cmd_ctx.channel, mode=cmd_ctx.mode))
try:
custom_nodes = asyncio.run(unified_manager.get_custom_nodes(channel=cmd_ctx.channel, mode=cmd_ctx.mode))
except core.InvalidChannel as e:
print(f"ERROR: {e.reason}", style="bold red")
raise typer.Exit(code=1)
# collect not-installed unknown nodes
not_installed_unknown_nodes = []
@@ -1343,7 +1348,7 @@ def install_deps(
if state == 'installed':
continue
elif state == 'not-installed':
asyncio.run(core.gitclone_install(k, instant_execution=True, no_deps=bool(uv_compile)))
asyncio.run(glob_core.gitclone_install(k, instant_execution=True, no_deps=bool(uv_compile)))
else: # disabled
cnr = unified_manager.get_cnr_by_repo(k)
enable_node(cnr['id'] if cnr else core.unknown_node_id(k))
@@ -1484,7 +1489,11 @@ def export_custom_node_ids(
for x in unified_manager.cnr_map.keys():
print(x, file=output_file)
custom_nodes = asyncio.run(unified_manager.get_custom_nodes(channel=cmd_ctx.channel, mode=cmd_ctx.mode))
try:
custom_nodes = asyncio.run(unified_manager.get_custom_nodes(channel=cmd_ctx.channel, mode=cmd_ctx.mode))
except core.InvalidChannel as e:
print(f"ERROR: {e.reason}", style="bold red")
raise typer.Exit(code=1)
for x in custom_nodes.values():
if 'cnr_latest' not in x:
if len(x['files']) == 1:
+8 -7
View File
@@ -910,16 +910,17 @@ class _Pygit2Repo(GitRepo):
return
try:
oid = _pygit2.Oid(hex=ref)
obj = self._repo.get(oid)
if obj is not None:
commit = obj.peel(_pygit2.Commit)
self._repo.checkout_tree(self._repo.get(commit.id))
self._repo.set_head(commit.id)
return
commit = self._repo.revparse_single(ref).peel(_pygit2.Commit)
self._repo.checkout_tree(self._repo.get(commit.id))
self._repo.set_head(commit.id)
return
except Exception:
pass
if self._repo.references.get(f'refs/remotes/origin/{ref}') is not None:
self.checkout_new_branch(ref, f'origin/{ref}')
return
raise GitCommandError(f"Cannot resolve ref for checkout: {ref}")
def checkout_new_branch(self, branch_name, start_point):
+1 -1
View File
@@ -549,7 +549,7 @@ try:
if len(sys.argv) > 4:
repo_path = sys.argv[4]
gitclone(sys.argv[2], sys.argv[3], repo_path=repo_path)
gitclone(sys.argv[2], sys.argv[3], target_hash=sys.argv[5] if len(sys.argv) > 5 else None, repo_path=repo_path)
elif sys.argv[1] == "--check":
gitcheck(sys.argv[2], False)
elif sys.argv[1] == "--fetch":
+21 -4
View File
@@ -1,6 +1,7 @@
import os
import configparser
import logging
import re
GITHUB_ENDPOINT = os.getenv('GITHUB_ENDPOINT')
@@ -147,12 +148,15 @@ def normalize_url(url) -> str:
return url
_HOST_OF_GIT_URL = re.compile(r'^(?:[A-Za-z][A-Za-z0-9+.-]*://)?(?:[^/@]*@)?([^/:]*)')
def normalize_to_github_id(url) -> str:
if 'github' in url or (GITHUB_ENDPOINT is not None and GITHUB_ENDPOINT in url):
if 'github' in _HOST_OF_GIT_URL.match(url).group(1).lower() or (GITHUB_ENDPOINT is not None and GITHUB_ENDPOINT in url):
author = os.path.basename(os.path.dirname(url))
if author.startswith('git@github.com:'):
author = author.split(':')[1]
if ':' in author:
author = author.rsplit(':', 1)[1]
repo_name = os.path.basename(url)
if repo_name.endswith('.git'):
@@ -161,7 +165,7 @@ def normalize_to_github_id(url) -> str:
return f"{author}/{repo_name}"
# Handle short format like "author/repo" (aux_id format)
if '/' in url and not url.startswith('http'):
if '/' in url and not url.startswith('http') and ':' not in url:
parts = url.split('/')
if len(parts) == 2 and parts[0] and parts[1]:
return url
@@ -169,6 +173,19 @@ def normalize_to_github_id(url) -> str:
return None
_GIT_URL_BEFORE_PATH = re.compile(r'^(?:[A-Za-z][A-Za-z0-9+.-]*://[^/]*(?:/|$)|[^/@:]+@[^/@:]+:)')
def extract_url_and_commit_id(s):
before_path = _GIT_URL_BEFORE_PATH.match(s)
path_start = before_path.end() if before_path else 0
index = s.rfind('@', path_start)
if index == -1:
return (s, '')
else:
return (s[:index], s[index+1:])
def get_url_for_clone(url):
url = normalize_url(url)
+39 -27
View File
@@ -72,9 +72,10 @@ default_custom_nodes_path = None
class InvalidChannel(Exception):
def __init__(self, channel):
def __init__(self, channel, reason='The channel is not allowed. A channel has to be in `channels.list`.'):
self.channel = channel
super().__init__(channel)
self.reason = reason
super().__init__(reason)
def get_default_custom_nodes_path():
@@ -191,6 +192,13 @@ def normalize_channel(channel):
return normalize_channel_url(channel)
elif channel.startswith('http://') and get_config()['http_channel_enabled'] == True:
return channel
elif channel.startswith('\\\\') or os.path.isabs(channel):
network_mode = get_config()['network_mode']
if network_mode == 'private':
return channel
for name, url in get_channel_dict().items():
if url == channel:
raise InvalidChannel(channel, f"The channel '{name}' is a folder, and a folder is allowed as a channel only with `network_mode = private`. The current network_mode is `{network_mode}`.")
tmp_dict = get_channel_dict()
channel_url = tmp_dict.get(channel)
@@ -1472,9 +1480,11 @@ class UnifiedManager:
def _install_git(self, node_id, version_spec, repo_url, instant_execution=False, no_deps=False, return_postinstall=False):
to_path = self._git_install_path(node_id, version_spec, repo_url)
replaced_version = None
if version_spec == 'nightly':
# disable cnr nodes
if self.is_enabled(node_id, 'cnr'):
replaced_version = self.get_cnr_active_version(node_id)
res = self.disable_for_replacement(node_id, to_path)
if not res.result:
return res
@@ -1487,11 +1497,13 @@ class UnifiedManager:
cnr_utils.generate_cnr_id(to_path, node_id)
self.active_nodes[node_id] = 'nightly', to_path
else:
if replaced_version is not None and not os.path.lexists(to_path):
self.unified_enable(node_id, replaced_version)
return res
return res.with_target(version_spec)
async def install_by_id(self, node_id: str, version_spec=None, channel=None, mode=None, instant_execution=False, no_deps=False, return_postinstall=False):
async def install_by_id(self, node_id: str, version_spec=None, channel=None, mode=None, instant_execution=False, no_deps=False, return_postinstall=False, repo_url=None):
"""
priority if version_spec == None
1. CNR latest
@@ -1503,7 +1515,6 @@ class UnifiedManager:
if 'comfyui-manager' in node_id.lower():
return ManagedResult('skip').fail(f"ignored: installing '{node_id}'")
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)
@@ -1514,11 +1525,11 @@ class UnifiedManager:
else:
version_spec = self.resolve_unspecified_version(node_id)
if version_spec == 'unknown' or version_spec == 'nightly':
if repo_url is None and (version_spec == 'unknown' or version_spec == 'nightly'):
try:
repo_url = await self._get_git_install_url(node_id, version_spec, channel, mode)
except InvalidChannel as exc:
return ManagedResult('fail').fail(f'Invalid channel is used: {exc.channel}')
return ManagedResult('fail').fail(exc.reason)
except LookupError as exc:
return ManagedResult('install').fail(str(exc))
@@ -1585,7 +1596,7 @@ class UnifiedManager:
try:
repo_url = await self._get_git_install_url(node_id, version_spec, channel, mode)
except InvalidChannel as exc:
return ManagedResult('fail').fail(f'Invalid channel is used: {exc.channel}')
return ManagedResult('fail').fail(exc.reason)
except LookupError as exc:
return ManagedResult('install').fail(str(exc))
install_path = self._git_install_path(node_id, version_spec, repo_url)
@@ -2394,13 +2405,6 @@ def is_valid_url(url):
return False
def extract_url_and_commit_id(s):
index = s.rfind('@')
if index == -1:
return (s, '')
else:
return (s[:index], s[index+1:])
async def gitclone_install(url, instant_execution=False, msg_prefix='', no_deps=False):
await unified_manager.reload('cache')
await unified_manager.get_custom_nodes('default', 'cache')
@@ -2418,9 +2422,9 @@ async def gitclone_install(url, instant_execution=False, msg_prefix='', no_deps=
cnr = unified_manager.get_cnr_by_repo(url)
if cnr:
cnr_id = cnr['id']
return await unified_manager.install_by_id(cnr_id, version_spec=None, channel='default', mode='cache')
return await unified_manager.install_by_id(cnr_id, version_spec='nightly', channel='default', mode='cache', instant_execution=instant_execution, no_deps=no_deps, repo_url=url)
else:
new_url, commit_id = extract_url_and_commit_id(url)
new_url, commit_id = git_utils.extract_url_and_commit_id(url)
if commit_id != "":
url = new_url
repo_name = os.path.splitext(os.path.basename(url))[0]
@@ -2449,18 +2453,26 @@ async def gitclone_install(url, instant_execution=False, msg_prefix='', no_deps=
# Clone the repository from the remote URL
clone_url = git_utils.get_url_for_clone(url)
if not instant_execution and platform.system() == 'Windows':
res = manager_funcs.run_script([sys.executable, context.git_script_path, "--clone", get_default_custom_nodes_path(), clone_url, repo_path], cwd=get_default_custom_nodes_path())
if res != 0:
return result.fail(f"Failed to clone '{clone_url}' into '{repo_path}'")
else:
repo = clone_repo(clone_url, repo_path, progress=GitProgress())
if commit_id!= "":
repo.checkout(commit_id)
repo.submodule_update()
cloned = False
try:
if not instant_execution and platform.system() == 'Windows':
res = manager_funcs.run_script([sys.executable, context.git_script_path, "--clone", get_default_custom_nodes_path(), clone_url, repo_path] + ([commit_id] if commit_id else []), cwd=get_default_custom_nodes_path())
if res != 0:
return result.fail(f"Failed to clone '{clone_url}' into '{repo_path}'")
else:
repo = clone_repo(clone_url, repo_path, progress=GitProgress())
try:
if commit_id!= "":
repo.checkout(commit_id)
repo.submodule_update()
repo.clear_cache()
repo.close()
repo.clear_cache()
finally:
repo.close()
cloned = True
finally:
if not cloned and os.path.exists(repo_path):
try_rmtree(url, repo_path)
execute_install_script(url, repo_path, instant_execution=instant_execution, no_deps=no_deps)
print("Installation was successful.")
+7 -4
View File
@@ -1427,7 +1427,7 @@ async def fetch_customnode_mappings(request):
"""
provide unified (node -> node pack) mapping list
"""
mode = request.rel_url.query["mode"]
mode = request.rel_url.query.get("mode", "cache")
nickname_mode = False
if mode == "nickname":
@@ -2222,9 +2222,12 @@ async def default_cache_update():
await core.unified_manager.reload(
ManagerDatabaseSource.remote.value, dont_wait=False
)
await core.unified_manager.get_custom_nodes(
channel_url, ManagerDatabaseSource.remote.value
)
try:
await core.unified_manager.get_custom_nodes(
channel_url, ManagerDatabaseSource.remote.value
)
except core.InvalidChannel as e:
logging.warning(f"[ComfyUI-Manager] {e.reason}")
else:
await core.unified_manager.reload(
ManagerDatabaseSource.remote.value, dont_wait=False, update_cnr_map=False
+2 -1
View File
@@ -422,7 +422,8 @@ export async function fetchData(route, options) {
if (status !== 200) {
return {
status,
error: new Error(statusText || "Unknown Error")
error: new Error(statusText || "Unknown Error"),
detail: await res.text().catch(() => "")
}
}
+1 -1
View File
@@ -2175,7 +2175,7 @@ export class CustomNodesManager {
// a server that was not restarted since its update still fetches every repository without skip_update
const res = await fetchData(`/v2/customnode/getlist?mode=${mode}&skip_update=true`);
if (res.error) {
this.showError("Failed to get custom node list.");
this.showError(res.status === 403 && res.detail ? sanitizeHTML(res.detail) : "Failed to get custom node list.");
this.hideLoading();
return;
}
+42 -16
View File
@@ -70,9 +70,10 @@ default_custom_nodes_path = None
class InvalidChannel(Exception):
def __init__(self, channel):
def __init__(self, channel, reason='The channel is not allowed. A channel has to be in `channels.list`.'):
self.channel = channel
super().__init__(channel)
self.reason = reason
super().__init__(reason)
def get_default_custom_nodes_path():
@@ -192,6 +193,13 @@ def normalize_channel(channel):
return normalize_channel_url(channel)
elif channel.startswith('http://') and get_config()['http_channel_enabled'] == True:
return channel
elif channel.startswith('\\\\') or os.path.isabs(channel):
network_mode = get_config()['network_mode']
if network_mode == 'private':
return channel
for name, url in get_channel_dict().items():
if url == channel:
raise InvalidChannel(channel, f"The channel '{name}' is a folder, and a folder is allowed as a channel only with `network_mode = private`. The current network_mode is `{network_mode}`.")
tmp_dict = get_channel_dict()
channel_url = tmp_dict.get(channel)
@@ -1406,7 +1414,7 @@ class UnifiedManager:
else:
return self.cnr_switch_version(node_id, instant_execution=instant_execution, no_deps=no_deps, return_postinstall=return_postinstall).with_ver('cnr')
async def install_by_id(self, node_id: str, version_spec=None, channel=None, mode=None, instant_execution=False, no_deps=False, return_postinstall=False):
async def install_by_id(self, node_id: str, version_spec=None, channel=None, mode=None, instant_execution=False, no_deps=False, return_postinstall=False, repo_url=None):
"""
priority if version_spec == None
1. CNR latest
@@ -1418,7 +1426,6 @@ class UnifiedManager:
if 'comfyui-manager' in node_id.lower():
return ManagedResult('skip').fail(f"ignored: installing '{node_id}'")
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)
@@ -1430,11 +1437,11 @@ class UnifiedManager:
else:
version_spec = self.resolve_unspecified_version(node_id)
if version_spec in ('unknown', 'nightly'):
if repo_url is None and version_spec in ('unknown', 'nightly'):
try:
repo_url = await self.get_git_install_url(node_id, version_spec, channel, mode)
except InvalidChannel as exc:
return ManagedResult('fail').fail(f'Invalid channel is used: {exc.channel}')
return ManagedResult('fail').fail(exc.reason)
except LookupError as exc:
return ManagedResult('install').fail(str(exc))
@@ -1508,9 +1515,11 @@ class UnifiedManager:
def _install_git(self, node_id, version_spec, repo_url, instant_execution=False, no_deps=False, return_postinstall=False):
to_path = self._git_install_path(node_id, version_spec, repo_url)
replaced_version = None
if version_spec == 'nightly':
# disable cnr nodes
if self.is_enabled(node_id, 'cnr'):
replaced_version = self.get_cnr_active_version(node_id)
res = self.disable_for_replacement(node_id, to_path)
if not res.result:
return res
@@ -1523,6 +1532,8 @@ class UnifiedManager:
cnr_utils.generate_cnr_id(to_path, node_id)
self.active_nodes[node_id] = 'nightly', to_path
else:
if replaced_version is not None and not os.path.lexists(to_path):
self.unified_enable(node_id, replaced_version)
return res
return res.with_target(version_spec)
@@ -1536,7 +1547,7 @@ class UnifiedManager:
try:
repo_url = await self.get_git_install_url(node_id, version_spec, channel, mode)
except InvalidChannel as exc:
return ManagedResult('fail').fail(f'Invalid channel is used: {exc.channel}')
return ManagedResult('fail').fail(exc.reason)
except LookupError as exc:
return ManagedResult('install').fail(str(exc))
install_path = self._git_install_path(node_id, version_spec, repo_url)
@@ -2276,8 +2287,11 @@ async def gitclone_install(url, instant_execution=False, msg_prefix='', no_deps=
cnr = unified_manager.get_cnr_by_repo(url)
if cnr:
cnr_id = cnr['id']
return await unified_manager.install_by_id(cnr_id, version_spec='nightly', channel='default', mode='cache')
return await unified_manager.install_by_id(cnr_id, version_spec='nightly', channel='default', mode='cache', instant_execution=instant_execution, no_deps=no_deps, repo_url=url)
else:
new_url, commit_id = git_utils.extract_url_and_commit_id(url)
if commit_id != "":
url = new_url
repo_name = os.path.splitext(os.path.basename(url))[0]
# NOTE: Keep original name as possible if unknown node
@@ -2304,14 +2318,26 @@ async def gitclone_install(url, instant_execution=False, msg_prefix='', no_deps=
# Clone the repository from the remote URL
clone_url = git_utils.get_url_for_clone(url)
if not instant_execution and platform.system() == 'Windows':
res = manager_funcs.run_script([sys.executable, context.git_script_path, "--clone", get_default_custom_nodes_path(), clone_url, repo_path], cwd=get_default_custom_nodes_path())
if res != 0:
return result.fail(f"Failed to clone '{clone_url}' into '{repo_path}'")
else:
repo = git.Repo.clone_from(clone_url, repo_path, recursive=True, progress=GitProgress())
repo.git.clear_cache()
repo.close()
cloned = False
try:
if not instant_execution and platform.system() == 'Windows':
res = manager_funcs.run_script([sys.executable, context.git_script_path, "--clone", get_default_custom_nodes_path(), clone_url, repo_path] + ([commit_id] if commit_id else []), cwd=get_default_custom_nodes_path())
if res != 0:
return result.fail(f"Failed to clone '{clone_url}' into '{repo_path}'")
else:
repo = git.Repo.clone_from(clone_url, repo_path, recursive=True, progress=GitProgress())
try:
if commit_id != "":
repo.git.checkout(commit_id)
repo.git.submodule('update', '--init', '--recursive')
repo.git.clear_cache()
finally:
repo.close()
cloned = True
finally:
if not cloned and os.path.exists(repo_path):
try_rmtree(url, repo_path)
execute_install_script(url, repo_path, instant_execution=instant_execution, no_deps=no_deps)
print("Installation was successful.")
+16 -7
View File
@@ -875,7 +875,7 @@ async def fetch_customnode_mappings(request):
"""
provide unified (node -> node pack) mapping list
"""
mode = request.rel_url.query["mode"]
mode = request.rel_url.query.get("mode", "cache")
nickname_mode = False
if mode == "nickname":
@@ -1134,14 +1134,20 @@ async def fetch_customnode_list(request):
"""
provide unified custom node list
"""
if request.rel_url.query["mode"] == "local":
mode = request.rel_url.query.get("mode", "cache")
if mode == "local":
channel = 'local'
else:
channel = core.get_config()['channel_url']
node_packs = await core.get_unified_total_nodes(channel, request.rel_url.query["mode"], 'cache')
json_obj_github = core.get_data_by_mode(request.rel_url.query["mode"], 'github-stats.json', 'default')
json_obj_extras = core.get_data_by_mode(request.rel_url.query["mode"], 'extras.json', 'default')
try:
node_packs = await core.get_unified_total_nodes(channel, mode, 'cache')
except core.InvalidChannel as e:
logging.warning(f"[ComfyUI-Manager] {e.reason}")
return web.Response(status=403, text=e.reason)
json_obj_github = core.get_data_by_mode(mode, 'github-stats.json', 'default')
json_obj_extras = core.get_data_by_mode(mode, 'extras.json', 'default')
core.populate_github_stats(node_packs, await json_obj_github)
core.populate_favorites(node_packs, await json_obj_extras)
@@ -1237,7 +1243,7 @@ def check_model_installed(json_obj):
@routes.get("/v2/externalmodel/getlist")
async def fetch_externalmodel_list(request):
# The model list is only allowed in the default channel, yet.
json_obj = await core.get_data_by_mode(request.rel_url.query["mode"], 'model-list.json')
json_obj = await core.get_data_by_mode(request.rel_url.query.get("mode", "cache"), 'model-list.json')
check_model_installed(json_obj)
@@ -2080,7 +2086,10 @@ async def default_cache_update():
else:
# load at least once
await core.unified_manager.reload('remote', dont_wait=False)
await core.unified_manager.get_custom_nodes(channel_url, 'remote')
try:
await core.unified_manager.get_custom_nodes(channel_url, 'remote')
except core.InvalidChannel as e:
logging.warning(f"[ComfyUI-Manager] {e.reason}")
else:
await core.unified_manager.reload('remote', dont_wait=False, update_cnr_map=False)
+13 -1
View File
@@ -44,7 +44,7 @@ def cm_cli(manager, core, monkeypatch): # noqa: F811
'app': SimpleNamespace(command=lambda *args, **kwargs: lambda function: function),
'typer': typer, 'Annotated': Annotated, 'List': List, 'Optional': Optional, 'asyncio': asyncio, 'os': os, 'sys': sys,
'json': json, 'threading': threading, 'concurrent': concurrent,
'traceback': traceback, 'core': core,
'traceback': traceback, 'core': core, 'glob_core': core,
'NodeInstallError': type('NodeInstallError', (Exception,), {}),
'cmd_ctx': Mock(no_deps=False, channel='default', mode='cache'), 'unified_manager': manager, 'auto_save_snapshot': AsyncMock(),
'manager_util': Mock(), 'context': Mock(), 'comfy_path': '', '_finalize_resolve': Mock(), **more,
@@ -348,3 +348,15 @@ def test_restore_dependencies_runs_for_the_nodepacks_only(cm_cli, manager, folde
assert [line for line in cm_cli.said() if line.startswith('Restoring')] == [f'Restoring [1/1]: {folder}{os.sep}a-pack']
assert [call.args[1] for call in manager.execute_install_script.call_args_list] == [os.path.join(folder, 'a-pack')]
def test_a_list_of_a_refused_channel_says_why_and_fails(cm_cli, manager, core, monkeypatch): # noqa: F811
async def refused(channel, mode):
raise core.InvalidChannel('/srv/channel', 'the reason [of it]')
monkeypatch.setattr(manager, 'get_custom_nodes', refused)
with pytest.raises(typer.Exit) as stop:
cm_cli('show_list')['show_list']('all')
assert (cm_cli.said(), stop.value.exit_code) == (['ERROR: the reason [of it]'], 1)
+59
View File
@@ -846,6 +846,65 @@ finally:
self.assertEqual(p2['sha'], self.first_sha)
self.assertTrue(p2['detached'])
def test_checkout_branch_of_the_remote_after_a_clone(self):
snippet = """
import tempfile, shutil
dest = tempfile.mkdtemp()
try:
repo = clone_repo(REPO_PATH, os.path.join(dest, 'cloned'))
repo.checkout('feature-branch')
print(json.dumps({"sha": repo.head_commit_hexsha, "detached": repo.head_is_detached, "branch": repo.active_branch_name}))
repo.close()
finally:
shutil.rmtree(dest, ignore_errors=True)
"""
branch_sha = subprocess.run(['git', 'rev-parse', 'feature-branch'], cwd=self.repo_path, capture_output=True, text=True, check=True).stdout.strip()
for result in _run_both(snippet, self.repo_path):
self.assertEqual(result, {'sha': branch_sha, 'detached': False, 'branch': 'feature-branch'})
def test_checkout_of_a_name_that_is_a_tag_and_a_branch_of_the_remote_takes_the_tag(self):
origin = os.path.join(self._tmpdir, 'tag_and_branch')
os.makedirs(origin)
def git(*args):
return subprocess.run(['git', '-c', 'user.name=Test', '-c', 'user.email=test@test.com', *args], cwd=origin, capture_output=True, text=True, check=True).stdout.strip()
git('init', '-b', 'master')
git('commit', '--allow-empty', '-m', 'tagged')
git('tag', 'both')
tagged = git('rev-parse', 'HEAD')
git('checkout', '-b', 'both')
git('commit', '--allow-empty', '-m', 'on the branch')
git('checkout', 'master')
snippet = """
import tempfile, shutil
dest = tempfile.mkdtemp()
try:
repo = clone_repo(REPO_PATH, os.path.join(dest, 'cloned'))
repo.checkout('both')
print(json.dumps({"sha": repo.head_commit_hexsha, "detached": repo.head_is_detached}))
repo.close()
finally:
shutil.rmtree(dest, ignore_errors=True)
"""
for result in _run_both(snippet, origin):
self.assertEqual(result, {'sha': tagged, 'detached': True})
def test_checkout_by_short_sha(self):
snippet = f"""
import tempfile, shutil
dest = tempfile.mkdtemp()
try:
repo = clone_repo(REPO_PATH, os.path.join(dest, 'cloned'))
repo.checkout({self.first_sha[:8]!r})
print(json.dumps({{"sha": repo.head_commit_hexsha, "detached": repo.head_is_detached}}))
repo.close()
finally:
shutil.rmtree(dest, ignore_errors=True)
"""
for result in _run_both(snippet, self.repo_path):
self.assertEqual(result, {'sha': self.first_sha, 'detached': True})
# === list_remotes fetch routing (pygit2) ===
def test_list_remotes_fetch_routing_pygit2(self):
+118
View File
@@ -0,0 +1,118 @@
import asyncio
import subprocess
from unittest.mock import AsyncMock, Mock
import pytest
from _install_flags_testutil import GIT_LOCATION, import_reader
HOST = 'git.example.invalid'
PREFIXES = [f'https://{HOST}/grp/', f'https://user:token@{HOST}/grp/', f'git@{HOST}:grp/', f'ssh://git@{HOST}/grp/']
REFS = [('zz-pack.git', 'tip'), ('zz-pack.git@{first}', 'first'), ('zz-pack.git@feature/x', 'branch')]
def git(path, *args):
return subprocess.run(['git', '-c', 'user.name=test', '-c', 'user.email=test@example.invalid', *args],
cwd=path, check=True, capture_output=True, text=True).stdout.strip()
@pytest.fixture(params=['glob', 'legacy'])
def core(request):
return import_reader(request.param)
@pytest.fixture
def git_reads_the_folder_of_the_test_for_each_prefix(tmp_path, monkeypatch):
for name in GIT_LOCATION:
monkeypatch.delenv(name, raising=False)
monkeypatch.setenv('GIT_CONFIG_COUNT', str(len(PREFIXES)))
for index, prefix in enumerate(PREFIXES):
monkeypatch.setenv(f'GIT_CONFIG_KEY_{index}', f'url.{tmp_path}/grp/.insteadOf')
monkeypatch.setenv(f'GIT_CONFIG_VALUE_{index}', prefix)
@pytest.fixture
def commits(tmp_path, git_reads_the_folder_of_the_test_for_each_prefix):
origin = tmp_path / 'grp' / 'zz-pack.git'
origin.mkdir(parents=True)
git(origin, 'init', '-q', '-b', 'main')
commits = {}
for name, branch in (('first', None), ('tip', None), ('branch', 'feature/x')):
if branch:
git(origin, 'checkout', '-q', '-b', branch)
(origin / '__init__.py').write_text(f'# {name}')
git(origin, 'add', '.')
git(origin, 'commit', '-q', '-m', name)
commits[name] = git(origin, 'rev-parse', 'HEAD')
git(origin, 'checkout', '-q', 'main')
return commits
@pytest.fixture
def install(core, monkeypatch, tmp_path):
nodes = tmp_path / 'custom_nodes'
nodes.mkdir()
monkeypatch.setattr(core, 'get_default_custom_nodes_path', lambda: str(nodes))
monkeypatch.setattr(core, 'get_custom_nodes_paths', lambda: [str(nodes)])
monkeypatch.setattr(core, 'execute_install_script', Mock(return_value=True))
monkeypatch.setattr(core.unified_manager, 'reload', AsyncMock())
monkeypatch.setattr(core.unified_manager, 'get_custom_nodes', AsyncMock(return_value={}))
monkeypatch.setattr(core.unified_manager, 'get_cnr_by_repo', lambda url: None)
def run(url, instant_execution=True):
result = asyncio.run(core.gitclone_install(url, instant_execution=instant_execution, no_deps=True))
return result.result, {path.name: git(path, 'rev-parse', 'HEAD') for path in nodes.iterdir()}
return run
@pytest.mark.parametrize('prefix', PREFIXES)
@pytest.mark.parametrize('rest, wanted', REFS, ids=[wanted for _, wanted in REFS])
def test_git_url_is_installed_at_its_commit(install, commits, prefix, rest, wanted):
assert install(prefix + rest.format(**commits)) == (True, {'zz-pack': commits[wanted]})
def test_clone_that_the_helper_script_makes_on_windows_is_at_the_commit(install, commits, core, monkeypatch, tmp_path):
monkeypatch.setattr(core.platform, 'system', lambda: 'Windows')
(tmp_path / 'folder_paths.py').write_text('')
monkeypatch.setenv('COMFYUI_PATH', str(tmp_path))
assert install(f'https://{HOST}/grp/zz-pack.git@{commits["first"]}', instant_execution=False) == (True, {'zz-pack': commits['first']})
def test_git_url_whose_commit_is_not_there_fails_and_leaves_no_clone(install, commits):
assert install(f'https://{HOST}/grp/zz-pack.git@no-such-commit') == (False, {})
def test_clone_that_the_helper_script_makes_on_windows_is_removed_when_the_commit_is_not_there(install, commits, core, monkeypatch, tmp_path):
monkeypatch.setattr(core.platform, 'system', lambda: 'Windows')
(tmp_path / 'folder_paths.py').write_text('')
monkeypatch.setenv('COMFYUI_PATH', str(tmp_path))
assert install(f'https://{HOST}/grp/zz-pack.git@no-such-commit', instant_execution=False) == (False, {})
def test_user_of_a_git_url_with_no_path_is_not_a_commit(core):
assert core.git_utils.extract_url_and_commit_id(f'https://user:token@{HOST}') == (f'https://user:token@{HOST}', '')
GITHUB = 'https://github.com/owner/repo'
@pytest.mark.parametrize('url, clone_url, repository', [
('git@gitlab.example.invalid:owner/repo.git', 'git@gitlab.example.invalid:owner/repo.git', 'git@gitlab.example.invalid:owner/repo.git'),
('git@gitlab.example.invalid:github/repo.git', 'git@gitlab.example.invalid:github/repo.git', 'git@gitlab.example.invalid:github/repo.git'),
('https://gitlab.example.invalid/owner/github-tools.git', 'https://gitlab.example.invalid/owner/github-tools.git', 'https://gitlab.example.invalid/owner/github-tools.git'),
('https://github-bot:token@gitlab.example.invalid/owner/repo.git', 'https://github-bot:token@gitlab.example.invalid/owner/repo.git', 'https://github-bot:token@gitlab.example.invalid/owner/repo.git'),
('https://user:token@github.com/owner/repo.git', GITHUB, GITHUB),
('https://github.com/owner/repo.git', GITHUB, GITHUB),
('https://GitHub.com/owner/repo.git', GITHUB, GITHUB),
('git@github.com:owner/repo.git', GITHUB, GITHUB),
('git@GitHub.com:owner/repo.git', GITHUB, GITHUB),
('ssh://git@github.com/owner/repo.git', GITHUB, GITHUB),
('owner/repo', GITHUB, GITHUB),
])
def test_only_a_url_of_a_github_host_is_a_github_repository(core, monkeypatch, url, clone_url, repository):
monkeypatch.setattr(core.git_utils, 'GITHUB_ENDPOINT', None)
assert (core.git_utils.get_url_for_clone(url), core.git_utils.normalize_url(url)) == (clone_url, repository)
+106
View File
@@ -0,0 +1,106 @@
import asyncio
import subprocess
from unittest.mock import AsyncMock, Mock
import pytest
from _install_flags_testutil import GIT_LOCATION, import_reader
URL = 'https://git.example.invalid/grp/zz-pack'
ANOTHER_URL = 'https://git.example.invalid/other/zz-pack'
def git(path, *args):
return subprocess.run(['git', '-c', 'user.name=test', '-c', 'user.email=test@example.invalid', *args],
cwd=path, check=True, capture_output=True, text=True).stdout.strip()
@pytest.fixture(params=['glob', 'legacy'])
def core(request):
return import_reader(request.param)
@pytest.fixture
def origin(tmp_path, monkeypatch):
for name in GIT_LOCATION:
monkeypatch.delenv(name, raising=False)
origin = tmp_path / 'grp' / 'zz-pack'
origin.mkdir(parents=True)
git(origin, 'init', '-q')
for version in (1, 2):
(origin / '__init__.py').write_text(f'VERSION = {version}')
git(origin, 'add', '.')
git(origin, 'commit', '-q', '-m', f'version {version}')
another = tmp_path / 'other' / 'zz-pack'
another.mkdir(parents=True)
git(another, 'init', '-q')
(another / '__init__.py').write_text('ANOTHER = 1')
git(another, 'add', '.')
git(another, 'commit', '-q', '-m', 'another repository of the same name')
monkeypatch.setenv('GIT_CONFIG_COUNT', '2')
monkeypatch.setenv('GIT_CONFIG_KEY_0', f'url.{tmp_path}/gone/.insteadOf')
monkeypatch.setenv('GIT_CONFIG_VALUE_0', 'https://git.example.invalid/grp/')
monkeypatch.setenv('GIT_CONFIG_KEY_1', f'url.{tmp_path}/other/.insteadOf')
monkeypatch.setenv('GIT_CONFIG_VALUE_1', 'https://git.example.invalid/other/')
return origin
@pytest.fixture
def git_reads_the_origin_for_the_url(origin, monkeypatch):
monkeypatch.setenv('GIT_CONFIG_KEY_0', f'url.{origin.parent}/.insteadOf')
@pytest.fixture
def install_by_url(core, origin, monkeypatch, tmp_path):
nodes = tmp_path / 'custom_nodes'
nodes.mkdir()
listed = {'id': 'zz-pack', 'repository': URL, 'latest_version': {'version': '1.0.0'}}
asked_for_a_version = Mock(return_value=None)
scripts_of_the_clone = Mock(return_value=True)
monkeypatch.setattr(core, 'get_default_custom_nodes_path', lambda: str(nodes))
monkeypatch.setattr(core, 'get_custom_nodes_paths', lambda: [str(nodes)])
monkeypatch.setattr(core.unified_manager, 'reload', AsyncMock())
for installed in ('active_nodes', 'cnr_inactive_nodes', 'nightly_inactive_nodes'):
monkeypatch.setattr(core.unified_manager, installed, type(getattr(core.unified_manager, installed))())
channel = {}
monkeypatch.setattr(core.unified_manager, 'get_custom_nodes', AsyncMock(return_value=channel))
monkeypatch.setattr(core.unified_manager, 'get_cnr_by_repo', lambda repo: listed)
monkeypatch.setitem(core.unified_manager.cnr_map, 'zz-pack', listed)
monkeypatch.setattr(core.unified_manager, 'execute_install_script', scripts_of_the_clone)
monkeypatch.setattr(core.cnr_utils, 'install_node', asked_for_a_version)
tip = git(origin, 'rev-parse', 'HEAD')
def run(version_is_enabled=False, channel_lists_another_repository_of_that_name=False):
if channel_lists_another_repository_of_that_name:
channel['zz-pack'] = {'repository': ANOTHER_URL, 'files': [ANOTHER_URL]}
if version_is_enabled:
(nodes / 'zz-pack').mkdir()
(nodes / 'zz-pack' / 'pyproject.toml').write_text('[project]\nname = "zz-pack"\nversion = "1.0.0"\n')
(nodes / 'zz-pack' / '.tracking').write_text('pyproject.toml')
monkeypatch.setitem(core.unified_manager.active_nodes, 'zz-pack', ('1.0.0', str(nodes / 'zz-pack')))
result = asyncio.run(core.gitclone_install(URL, instant_execution=True, no_deps=True))
left = {str(path.relative_to(nodes)): 'the tip' if git(path, 'rev-parse', 'HEAD') == tip else 'a clone' for path in nodes.rglob('*') if (path / '.git').is_dir()}
left.update({str(path.relative_to(nodes)): 'version 1.0.0' for path in nodes.rglob('*') if (path / '.tracking').is_file()})
asked_for_a_version.assert_not_called()
return result.result, left, [call.kwargs for call in scripts_of_the_clone.call_args_list]
return run
FLAGS = [{'instant_execution': True, 'no_deps': True}]
def test_url_of_a_repository_that_the_registry_lists_is_cloned(install_by_url, git_reads_the_origin_for_the_url):
assert install_by_url() == (True, {'zz-pack': 'the tip'}, FLAGS)
def test_url_is_what_is_cloned_when_the_channel_lists_another_repository_of_that_name(install_by_url, git_reads_the_origin_for_the_url):
assert install_by_url(channel_lists_another_repository_of_that_name=True) == (True, {'zz-pack': 'the tip'}, FLAGS)
def test_url_of_a_nodepack_whose_version_is_enabled_is_cloned_and_the_version_is_disabled(install_by_url, git_reads_the_origin_for_the_url):
assert install_by_url(version_is_enabled=True) == (True, {'zz-pack': 'the tip', '.disabled/zz-pack@1_0_0': 'version 1.0.0'}, FLAGS)
def test_enabled_version_is_enabled_again_when_the_clone_in_its_place_fails(install_by_url):
assert install_by_url(version_is_enabled=True) == (False, {'zz-pack': 'version 1.0.0'}, [])
+1 -1
View File
@@ -26,7 +26,7 @@ def install(node, exit_on_fail):
'typer': typer, 'Annotated': Annotated, 'List': List, 'Optional': Optional,
'asyncio': asyncio, 'sys': sys, 'traceback': traceback, 'print': lambda *objects, style=None: print(*objects), 'NodeInstallError': NodeInstallError,
'cmd_ctx': Mock(no_deps=False), 'comfy_path': '', 'context': Mock(), 'manager_util': Mock(),
'core': SimpleNamespace(is_valid_url=lambda spec: False), 'unified_manager': unified_manager,
'glob_core': SimpleNamespace(is_valid_url=lambda spec: False), 'unified_manager': unified_manager,
})['install']([node], None, None, False, False, None, exit_on_fail)
+5 -2
View File
@@ -52,6 +52,7 @@ from _install_flags_testutil import ( # noqa: E402
)
_LEGACY_SERVER = None
_GET_DATA = None
def _import_legacy_server():
@@ -59,7 +60,7 @@ def _import_legacy_server():
(idempotent; memoized). Returns the real module object so the tests drive
the REAL gate function and REAL handlers — only the runtime *environment*
is stubbed, never the gate logic."""
global _LEGACY_SERVER
global _LEGACY_SERVER, _GET_DATA
if _LEGACY_SERVER is not None:
return _LEGACY_SERVER
@@ -108,6 +109,7 @@ def _import_legacy_server():
async def _inert_get_data(uri, *a, **k):
return {"custom_nodes": [], "models": [], "node_map": {}}
_GET_DATA = mu.get_data
mu.get_data = _inert_get_data
_LEGACY_SERVER = importlib.import_module("comfyui_manager.legacy.manager_server")
@@ -116,7 +118,8 @@ def _import_legacy_server():
@pytest.fixture(scope="module")
def ms():
return _import_legacy_server()
yield _import_legacy_server()
sys.modules["comfyui_manager.common.manager_util"].get_data = _GET_DATA
@pytest.fixture
+28
View File
@@ -0,0 +1,28 @@
import asyncio
import json
import re
from types import SimpleNamespace
import pytest
from aiohttp import web
from legacy_html_testutil import PACKAGE, load_functions
from test_default_channel import COMFY_ORG, configure, registry, route, user, write # noqa: F401
ROUTES = [('glob', 'fetch_customnode_mappings'), ('legacy', 'fetch_customnode_mappings'),
('legacy', 'fetch_customnode_list'), ('legacy', 'fetch_externalmodel_list')]
@pytest.mark.parametrize('server,name', ROUTES)
def test_a_request_without_mode_is_answered_as_mode_cache(user, registry, server, name): # noqa: F811
configure(user, None, COMFY_ORG)
write(user, f'{server} start')
handler = load_functions(PACKAGE / server / 'manager_server.py', {name}, {
'core': user.cores[server], 'web': web, 'routes': SimpleNamespace(get=route, post=route), 're': re,
'nodes': SimpleNamespace(NODE_CLASS_MAPPINGS={}), 'populate_markdown': lambda row: None,
'check_model_installed': lambda listed: None})[name]
def ask(**query):
return json.loads(asyncio.run(handler(SimpleNamespace(rel_url=SimpleNamespace(query=query)))).text)
assert ask() == ask(mode='cache') != ask(mode='local')
+1 -1
View File
@@ -255,7 +255,7 @@ def test_cm_cli_install_reports_an_enable_that_failed(core, custom_nodes): # no
(custom_nodes / 'ComfyUI-Bar').mkdir()
out = io.StringIO()
install_node = cm_cli_function('install_node', {
'asyncio': asyncio, 'core': core, 'unified_manager': manager, 'print': lambda *objects, **kwargs: print(*objects, file=out),
'asyncio': asyncio, 'core': core, 'glob_core': core, 'unified_manager': manager, 'print': lambda *objects, **kwargs: print(*objects, file=out),
'cmd_ctx': SimpleNamespace(channel=core.DEFAULT_CHANNEL, mode='cache', no_deps=False), 'NodeInstallError': NodeInstallError})
with pytest.raises(NodeInstallError):
+148
View File
@@ -0,0 +1,148 @@
import asyncio
import json
import logging
import os
import sys
import traceback
from types import SimpleNamespace
import pytest
from aiohttp import web
from legacy_html_testutil import PACKAGE, load_functions
from test_default_channel import COMFY_ORG, answer, configure, handlers, idle, route, user, write # noqa: F401
SHARED_URL = 'https://github.com/example/ComfyUI-Shared'
SERVERS = ['glob', 'legacy']
NETWORKS = [((), 'public'), (('network_mode = offline',), 'offline')]
UNLISTED = 'The channel is not allowed. A channel has to be in `channels.list`.'
@pytest.fixture
def share(user): # noqa: F811
folder = user.path / 'share'
folder.mkdir()
(folder / 'custom-node-list.json').write_text(json.dumps({'custom_nodes': [
{'author': 'example', 'title': 'ComfyUI-Shared', 'reference': SHARED_URL, 'files': [SHARED_URL],
'install_type': 'git-clone', 'description': ''}]}))
read, cloned = [], []
read_data = user.util.get_data
async def recording(uri, silent=False):
read.append(uri)
return await read_data(uri, silent)
user.monkeypatch.setattr(user.util, 'get_data', recording)
custom_nodes = user.path / 'comfyui' / 'custom_nodes'
custom_nodes.mkdir(parents=True)
user.monkeypatch.setattr(sys.modules['folder_paths'], 'get_folder_paths', lambda name: [str(custom_nodes)], raising=False)
def start(server):
write(user, f'{server} start')
core = user.cores[server]
manager = core.UnifiedManager()
def repo_install(url, to_path, **kwargs):
cloned.append(url)
return core.ManagedResult('install')
user.monkeypatch.setattr(manager, 'repo_install', repo_install)
user.monkeypatch.setattr(core, 'unified_manager', manager)
read.clear()
return core
return SimpleNamespace(folder=str(folder), start=start, read=read, cloned=cloned)
def install(core, channel):
result = asyncio.run(core.unified_manager.install_by_id('ComfyUI-Shared', 'unknown', channel, 'cache'))
return result.result, result.msg
@pytest.mark.parametrize('server', SERVERS)
def test_a_folder_that_channels_list_names_is_a_channel_of_a_private_network(user, share, server): # noqa: F811
configure(user, share.folder, COMFY_ORG, 'network_mode = private', 'default_cache_as_channel_url = True')
with open(user.path / 'channels.list', 'a') as f:
f.write(f'private::{share.folder}\n')
core = share.start(server)
assert list(asyncio.run(core.unified_manager.get_custom_nodes(core.get_config()['channel_url'], 'cache'))) == ['ComfyUI-Shared']
assert answer(handlers(user, server, {'channel_url_list'})['channel_url_list'])['selected'] == 'private'
assert install(core, 'private') == (True, None)
assert share.cloned == [SHARED_URL]
@pytest.mark.parametrize('unc', [False, True], ids=['folder', 'UNC'])
@pytest.mark.parametrize('server', SERVERS)
def test_a_request_cannot_name_a_folder_that_channels_list_does_not_have(user, share, server, unc): # noqa: F811
configure(user, None, COMFY_ORG, 'network_mode = private')
core = share.start(server)
channel = '\\\\attacker\\share' if unc else share.folder
assert install(core, channel) == (False, UNLISTED)
assert (share.cloned, share.read) == ([], [])
def needs(mode):
return ("The channel 'private' is a folder, and a folder is allowed as a channel only with `network_mode = private`. "
f'The current network_mode is `{mode}`.')
def register(user, share, *lines): # noqa: F811
configure(user, share.folder, COMFY_ORG, *lines)
with open(user.path / 'channels.list', 'a') as f:
f.write(f'private::{share.folder}\n')
@pytest.mark.parametrize('lines', [('network_mode = private',), ()], ids=['private', 'public'])
@pytest.mark.parametrize('server', SERVERS)
def test_a_folder_that_only_config_ini_names_is_refused(user, share, server, lines): # noqa: F811
configure(user, share.folder, COMFY_ORG, *lines)
core = share.start(server)
with pytest.raises(core.InvalidChannel) as refused:
asyncio.run(core.unified_manager.get_custom_nodes(core.get_config()['channel_url'], 'cache'))
assert refused.value.reason == UNLISTED
assert share.read == []
@pytest.mark.parametrize('lines,mode', NETWORKS, ids=['public', 'offline'])
@pytest.mark.parametrize('server', SERVERS)
def test_a_folder_on_another_network_is_refused_with_the_setting_it_needs(user, share, server, lines, mode): # noqa: F811
register(user, share, *lines)
core = share.start(server)
with pytest.raises(core.InvalidChannel) as refused:
asyncio.run(core.unified_manager.get_custom_nodes(core.get_config()['channel_url'], 'cache'))
assert refused.value.reason == needs(mode)
assert install(core, 'private') == (False, needs(mode))
assert (share.cloned, share.read) == ([], [])
def test_the_legacy_list_answers_why_a_folder_is_refused(user, share): # noqa: F811
register(user, share)
core = share.start('legacy')
handler = load_functions(PACKAGE / 'legacy/manager_server.py', {'fetch_customnode_list'}, {
'core': core, 'web': web, 'logging': logging, 'routes': SimpleNamespace(get=route, post=route)})['fetch_customnode_list']
response = asyncio.run(handler(SimpleNamespace(rel_url=SimpleNamespace(query={'mode': 'cache'}))))
assert (response.status, response.text) == (403, needs('public'))
@pytest.mark.parametrize('server', SERVERS)
def test_the_start_warns_of_a_folder_on_a_public_network_and_completes(user, share, server, caplog): # noqa: F811
register(user, share)
core = share.start(server)
user.monkeypatch.setattr(core.unified_manager, 'reload', idle)
user.monkeypatch.setattr(core, 'check_invalid_nodes', lambda: None)
start = load_functions(PACKAGE / server / 'manager_server.py', {'default_cache_update'}, {
'os': os, 'logging': logging, 'traceback': traceback, 'asyncio': asyncio, 'manager_util': user.util, 'core': core,
'ManagerDatabaseSource': SimpleNamespace(remote=SimpleNamespace(value='remote'))})['default_cache_update']
with caplog.at_level(logging.WARNING):
asyncio.run(start())
assert [record.getMessage() for record in caplog.records if 'network_mode' in record.getMessage()] == [
f'[ComfyUI-Manager] {needs("public")}']
assert [uri for uri in share.read if uri.startswith(share.folder)] == []