Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3a72e71f91 | ||
|
|
13a10217e7 | ||
|
|
9f967363e2 | ||
|
|
d157bb9b32 | ||
|
|
1c9e57f72a | ||
|
|
3badbaaebc | ||
|
|
685618664d | ||
|
|
a48433cc9a | ||
|
|
14626f8602 |
+327
@@ -7,6 +7,331 @@ and this project adheres to [Semantic Versioning 2.0.0](https://semver.org/spec/
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [4.4.2] - 2026-11-19
|
||||
|
||||
### Security
|
||||
|
||||
- Keep the saved Matrix password on the server.
|
||||
`GET /v2/manager/get_matrix_auth` answered with the saved homeserver, username
|
||||
and password, to any client that could reach the server. It now answers
|
||||
without the password. With the legacy UI, the share dialog leaves the password
|
||||
field empty for the saved account, and the server uses the saved password for
|
||||
the username it was saved with; for another account a password has to be
|
||||
typed. An account is saved once it has logged in; a share request no longer
|
||||
replaces the saved account before that. If others could reach the server while
|
||||
a Matrix password was saved, change that password.
|
||||
- Share to Matrix through matrix.org only, where the share room is. The server
|
||||
logged in to any homeserver that a share request named, with the password of
|
||||
the request. The homeserver of the legacy UI's share dialog can no longer be
|
||||
changed, a share request that names another homeserver is refused, and an
|
||||
account that was saved for another homeserver is not used: an account of
|
||||
matrix.org has to be entered.
|
||||
- Keep the YouML API token in the browser that shares, which is what sends it to
|
||||
YouML. The server stored it, and `GET /v2/manager/youml/settings` answered
|
||||
with it to any client that could reach the server. Both
|
||||
`/v2/manager/youml/settings` routes are removed. With the legacy UI, the token
|
||||
has to be entered once more in the YouML share dialog. Delete `.youml` in
|
||||
`<USER_DIRECTORY>/__manager/`, and if others could reach the server while a
|
||||
token was saved, issue a new token.
|
||||
- Hold a switch of ComfyUI to an older version to the security level when it is
|
||||
asked for through `POST /v2/manager/queue/task`. The switch route has needed
|
||||
`normal-` or lower on a loopback listener, or `weak` in `personal_cloud` mode,
|
||||
since 4.2.1; an `update-comfyui` task with a version was not checked. Such a
|
||||
task now needs the same when the version is an older release or is not a
|
||||
release tag. A task for `nightly` or for a newer release is an update and runs
|
||||
at every level, as before. A ComfyUI with commits after its release, as on
|
||||
`nightly`, would go back by a switch to that release, so that counts as older;
|
||||
in a repository without release tags, such as a clone without tags, every
|
||||
version but `nightly` does. `Switch ComfyUI` in the legacy UI's menu changed
|
||||
the update policy before it asked for the switch, so a switch that was refused
|
||||
still changed it; it now changes it after the switch is accepted, and says so
|
||||
when the security level does not allow the switch.
|
||||
- Hold an enable that puts a nightly in the place of a registry version to the
|
||||
security level of a nightly install (`middle+`). An `enable` names a node pack
|
||||
and no version; with a registry version of the pack enabled and its nightly
|
||||
disabled, it enabled the nightly instead, at any security level through
|
||||
`queue/task` and at `middle` through the legacy UI's install route.
|
||||
- Hold a snapshot restore to the security level of the switch route (`high+`).
|
||||
A restore takes the node packs back to the versions that the
|
||||
snapshot recorded. `POST /v2/snapshot/restore` needed `middle+`, which the
|
||||
default `security_level = normal` gives on a loopback listener. It now needs
|
||||
`normal-` or lower on a loopback listener, or `weak` in `personal_cloud`
|
||||
mode, and is refused otherwise. `cm-cli restore-snapshot` is not changed.
|
||||
- Read a value of `config.ini` as plain text, and use the default of a setting
|
||||
for a value that it cannot have. Manager read `%(name)s` in a value as a
|
||||
reference to another setting, and a `%` that is not of that form made the
|
||||
whole file unreadable: every setting was then at its default,
|
||||
`security_level` too, and nothing said so. A value is now read as it is
|
||||
written; `%%`, which was read as one `%`, is now two. `security_level`,
|
||||
`network_mode`, `db_mode` and `update_policy` have their default when
|
||||
`config.ini` gives a value that they cannot have, and Manager logs a warning
|
||||
that names it; the other settings are read as before, and `config.ini` keeps
|
||||
the value. Before, a `security_level` that is not a level refused every
|
||||
action that needs one; now it is `normal`. A `config.ini` that cannot be read
|
||||
at all still gives the default settings, and is still written anew from them
|
||||
when a setting is saved; Manager now logs a warning when it reads one.
|
||||
- Take a JSON body only as `application/json`. A POST route that reads a JSON
|
||||
body parsed it whatever the Content-Type of the request. These routes, among
|
||||
them `POST /v2/manager/queue/task` and `POST /v2/manager/queue/batch`, now
|
||||
answer 400 unless the Content-Type is `application/json`. The legacy routes
|
||||
`POST /v2/customnode/install/git_url` and `POST /v2/customnode/install/pip`
|
||||
now take `{"url": ...}` and `{"packages": ...}` as JSON in place of plain
|
||||
text. A script or tool that posts to these routes without
|
||||
`Content-Type: application/json` has to add it.
|
||||
- Save only a choice of the share menu as the share option.
|
||||
`/v2/manager/share_option` saved any text as the share option. It now saves
|
||||
`all`, `none`, `youml` or `matrix`, the choices of the menu, and answers 400
|
||||
for another value.
|
||||
- Write the saved Matrix account as a file of its user only. The share dialog
|
||||
saves the account, with its password, in `matrix_auth` in Manager's data
|
||||
directory. The file was written with the default mode of new files, which
|
||||
other users of the machine can usually read. It is now written with mode
|
||||
`0600`, and a file that is already there gets that mode the next time an
|
||||
account is saved.
|
||||
- Take every POST that changes something only as `application/json`, and save
|
||||
the share option by POST. A page of another site can make the browser send a
|
||||
GET, and a POST without a body and without a Content-Type, for which no
|
||||
preflight is made. The routes that take no body
|
||||
(`/v2/manager/queue/start`, `/v2/manager/queue/reset`,
|
||||
`/v2/manager/queue/update_all`, `/v2/manager/queue/update_comfyui`,
|
||||
`/v2/snapshot/save`, `/v2/snapshot/remove`, `/v2/snapshot/restore`,
|
||||
`/v2/manager/reboot`) now answer 400 unless the request has
|
||||
`Content-Type: application/json`, as the routes that read a JSON body do: a
|
||||
browser does not send that header to another site without a preflight. The
|
||||
share option is saved with `POST /v2/manager/share_option` and a JSON body
|
||||
`{"value": ...}`; `GET /v2/manager/share_option` only answers with the saved
|
||||
option, and a `value` given to it is ignored. The legacy UI sends the header.
|
||||
A script that calls one of these routes has to send it too, and one that
|
||||
saved the share option with `?value=` has to POST.
|
||||
|
||||
## [4.4.1] - 2026-11-19
|
||||
|
||||
### Fixed
|
||||
|
||||
- Restarting ComfyUI from the Manager under comfy-cli no longer prints
|
||||
`ValueError: I/O operation on closed file` on the console. The log file is
|
||||
closed before the process exits, and what was logged after that was still
|
||||
written to it.
|
||||
- In the legacy UI, Update ComfyUI and Update All with ComfyUI no longer end
|
||||
with status 500 and nothing queued. The batch route called the handler of
|
||||
the update route without a request.
|
||||
- With `update_policy = nightly`, the legacy server updates ComfyUI to the
|
||||
nightly version. Only `nightly-comfyui` was taken as nightly, and `nightly`
|
||||
as stable.
|
||||
- The legacy server answers 400 again when the list of ComfyUI versions cannot
|
||||
be read or a switch to another version fails. The call that logs the cause
|
||||
was given an argument it does not take, so the answer was 500 with a
|
||||
`TypeError` in the log.
|
||||
|
||||
- Update ComfyUI to the latest stable version again when Manager runs git
|
||||
through GitPython, which it does whenever the `git` command is available.
|
||||
The update ended with `Failed to checkout 'master' branch` and ComfyUI
|
||||
stayed at its version: the branch to check out was passed to git as an
|
||||
object instead of by its name. An update to the nightly version failed the
|
||||
same way when the checkout was detached and the remote's default branch was
|
||||
not known locally.
|
||||
|
||||
- On the default server, `POST /v2/manager/queue/update_comfyui` follows
|
||||
`update_policy` when the request names no version line. Its `stable`
|
||||
parameter defaulted to true, so the policy was never read and such a request
|
||||
updated ComfyUI to the stable version also under `nightly-comfyui`.
|
||||
`nightly` is taken as nightly too.
|
||||
- On the default server, the same route reads `is_stable`, the name the
|
||||
ComfyUI frontend sends, when `stable` is not given. It was ignored.
|
||||
- `openapi.yaml` lists the values the two setting routes accept: `cache` for
|
||||
`db_mode` and `stable-comfyui` for the update policy were missing.
|
||||
|
||||
- Print console messages with paths, URLs and package names as they are.
|
||||
Manager printed many of its messages through rich, which reads square
|
||||
brackets as markup: a package name such as `diffusers[torch]` was shown as
|
||||
`diffusers`, a text such as `:100:` as an emoji, and a line longer than the
|
||||
console was broken in the middle of a path or a URL. A text with a closing
|
||||
tag such as `[/b]` raised `MarkupError` instead of being printed, in the
|
||||
middle of the operation that reported it. Numbers and quoted strings keep
|
||||
their colors.
|
||||
|
||||
- Start with a node pack whose `.git/config` Manager could not read. A url
|
||||
with a `%`, such as one with `%20`, a key without a value, such as `bare`
|
||||
alone, a key on a line that is indented more than the one before it, a byte
|
||||
order mark at the start of the file, or on Windows text that
|
||||
the code page of the system cannot decode, such as a Korean user name
|
||||
written in UTF-8, raised an error while Manager was loading: ComfyUI did not
|
||||
start, or with `--enable-manager-legacy-ui` started without Manager. These
|
||||
files are read now, and for a file that cannot be read the url of that pack
|
||||
is unknown and a warning names the file once.
|
||||
|
||||
- Run the git executable set as `git_exe` in `config.ini`. The path was read
|
||||
but not used: with the GitPython backend, git commands kept running the
|
||||
`git` found on `PATH`, and without a `git` on `PATH` the pygit2 backend was
|
||||
selected, or with the legacy UI Manager did not load. Both servers, the git
|
||||
helper and `cm-cli` now run the configured executable. For the servers and
|
||||
what they start it no longer has to be on `PATH`; `cm-cli` run by hand still
|
||||
needs a git on `PATH`. A value that is not a working git is reported, and
|
||||
the default git is used. The value is read as it is written: with a `%` in
|
||||
it, as in a path of Windows, Manager read every setting of `config.ini` as
|
||||
its default. The configured executable is also run when pygit2
|
||||
is asked for with `CM_USE_PYGIT2=1` but is not installed.
|
||||
- Start without a git. With neither a `git` on `PATH` nor pygit2, ComfyUI did
|
||||
not start, or with the legacy UI started without Manager; Manager now loads
|
||||
and reports that git is missing, and what needs git fails when it is used.
|
||||
With pygit2 and no `git`, the legacy UI started without Manager; it now
|
||||
loads on the pygit2 backend, but what the legacy server does with GitPython
|
||||
itself still needs a git.
|
||||
|
||||
- Update the submodules of a submodule with the pygit2 backend, and fail when
|
||||
the submodules could not be updated. pygit2 updated the submodules of the
|
||||
nodepack and not those below them, which git does. When it could not update
|
||||
them and there was no `git` to do it in its place, or that `git` did not
|
||||
answer in time, a message was printed and the install or the update went on
|
||||
as if they were updated.
|
||||
- Fetch the submodules of a nodepack through the proxy with the pygit2
|
||||
backend. The nodepack was cloned through the `http.proxy` of the global git
|
||||
configuration and its submodules were not, so behind a proxy they could not
|
||||
be fetched. As for the nodepack, the proxy is used for an `https` url.
|
||||
- Fetch a submodule with an ssh url over https with the pygit2 backend, as the
|
||||
nodepack itself is. It was asked for credentials, which pygit2 does not
|
||||
have, and with a public repository does not need.
|
||||
- Fetch a submodule again with the pygit2 backend after its clone failed, and
|
||||
check one out again after its checkout was removed, as by an update that
|
||||
was undone. What was left of it in `.git/modules` kept every later update
|
||||
from it.
|
||||
- Update a nodepack whose submodule is at another commit than the nodepack
|
||||
names, with the pygit2 backend. The update ended before the pull, at a
|
||||
stash with nothing to stash, as it did after a submodule could not be
|
||||
fetched once.
|
||||
- Do not end a clone or a fetch of the pygit2 backend at a progress message
|
||||
of the server. pygit2 decodes each piece of such a message as UTF-8, and a
|
||||
piece can end in the middle of a character: with a server that writes its
|
||||
messages in a language other than English, a clone, a fetch or the update
|
||||
of a submodule failed now and then with `UnicodeDecodeError`.
|
||||
- Bring the submodules of a git nodepack to the commits that its commit names
|
||||
when a snapshot restore checks it out, and also when it is at the commit of
|
||||
the snapshot already. A submodule that was never fetched is then fetched
|
||||
too in a nodepack that Manager installed, as Manager clones a nodepack with
|
||||
its submodules; with the pygit2 backend, or in a nodepack cloned without
|
||||
them, it is fetched only when the nodepack itself is checked out.
|
||||
- Record the commit of a git nodepack whose refs are packed, as after
|
||||
`git gc`, in a snapshot. It was recorded as `unknown`. A `HEAD` that is not
|
||||
UTF-8, as one that names a branch in another encoding, raised an error where
|
||||
the commit of a nodepack is read. It is read as bytes now. On Windows the
|
||||
commit of a branch whose name is not ASCII, as a Korean one, could be
|
||||
unknown as well: the file of the branch is looked for under the name that
|
||||
Git for Windows gives it.
|
||||
- Start with a git nodepack whose commit cannot be read. The commit is read
|
||||
while Manager is loading, and an error there kept ComfyUI from starting, or
|
||||
with `--enable-manager-legacy-ui` Manager from loading: for a `.git` with a
|
||||
folder where the file of the branch would be, as after
|
||||
`git checkout --orphan feature` beside a branch `feature/x`, or with a file
|
||||
that cannot be read. The commit of such a nodepack is unknown now.
|
||||
- Fail an update whose pull failed in the git helper. On Windows the pull runs
|
||||
in a helper process, which ended with 0 when the pull failed, and its result
|
||||
was not read: the update went on to the install script and ended as done.
|
||||
The helper ends with 1 now.
|
||||
- Undo the pull of an update when the update of its submodules fails. The
|
||||
nodepack stayed at the new commit: the next update found nothing to do, and
|
||||
the install script of the update never ran. The submodules that were updated
|
||||
before the one that failed go back with it. A nodepack with a submodule
|
||||
that cannot be fetched at all is not updated until it can.
|
||||
|
||||
- Carry out a scheduled snapshot restore in the directories of the server.
|
||||
With `--base-directory`, the restore that runs at the next start worked on
|
||||
the Manager's files and the `custom_nodes` directory inside the ComfyUI
|
||||
directory instead of those of the base directory: it did not see the node
|
||||
packs of the server.
|
||||
|
||||
- Report the steps of a snapshot restore that failed. The summary listed a
|
||||
nodepack as `INSTALLED`, `DISABLED` or `ENABLED` without looking at the
|
||||
result of the step: a clone that failed, for example because the directory
|
||||
already existed or the url could not be reached, was `INSTALLED`. A step that
|
||||
fails is listed as `FAILED`, and Manager itself is no longer listed as
|
||||
`DISABLED`. A Registry that cannot be reached ended the restore at the first
|
||||
nodepack to install from it, and so did a nodepack whose directory could not
|
||||
be moved to disable or enable it; such a nodepack is listed as `FAILED`, and
|
||||
the restore goes on. `cm-cli restore-snapshot` ends with 1 when a step failed
|
||||
or a pip package that a `--pip-*` option selects was not installed, and a
|
||||
scheduled restore then says `Restore snapshot failed.`: it ended with 0. A
|
||||
url of the snapshot that cannot be parsed ended the restore as well; the
|
||||
nodepack is listed as `FAILED`. A git nodepack of the Registry that was
|
||||
already installed, or that the restore enabled, was listed a second time as
|
||||
`SKIPPED`; it is listed once. An installed one that is checked out is listed
|
||||
by its name, as the others are: it was listed by its path.
|
||||
- Restore the commit of the snapshot for every git nodepack. A git nodepack
|
||||
that the restore had to clone stayed at the newest commit; it is checked out
|
||||
at the commit of the snapshot, and its install script runs after that. When
|
||||
the commit cannot be checked out, the install script still runs, at the
|
||||
commit the clone is at, and the nodepack is listed as `FAILED`. An installed
|
||||
git nodepack that the Registry does not know was checked out only when
|
||||
`cm-cli` was run from `custom_nodes`, as a scheduled restore does; it is
|
||||
checked out from any directory.
|
||||
- Install the requirements and run the install script of a Registry nodepack
|
||||
that a snapshot restore installs. The nodepack was unpacked and nothing
|
||||
more. It is listed as `FAILED` when they fail.
|
||||
- Try a requirement or an install script that failed again. It was taken as
|
||||
done until the next start: the next nodepack that names the requirement
|
||||
skipped it, and installing or fixing the nodepack again did not run the
|
||||
script. The install script of a git nodepack was skipped in the same way
|
||||
when it was cloned where another version of the nodepack had been installed
|
||||
since the start, as a restore does for a snapshot that has both; it runs.
|
||||
- Write what is reserved for the next start as UTF-8, which is how the
|
||||
start-up script reads it. The install script of an update, the removal of a
|
||||
nodepack whose files are in use and a switch of version are reserved in a
|
||||
file that was written in the encoding of the system. On Windows a path with
|
||||
a character outside ASCII was lost: one that the code page cannot write,
|
||||
such as a Korean folder name with code page 1252, raised an error and
|
||||
nothing was reserved; one that it can write was read back as another path,
|
||||
and what was reserved was not carried out at the next start.
|
||||
- Remove the files of the old version from the nodepack when a switch of
|
||||
version is carried out at the next start. The files that the new version no
|
||||
longer has were looked for in `custom_nodes` in place of the directory of the
|
||||
nodepack: they stayed in the nodepack, and a file of the same name in
|
||||
`custom_nodes` was removed. A switch of version, at the next start or at
|
||||
once, removes the files that the new version no longer has before it extracts
|
||||
the archive of the new version: where two names are one file, as `./a.py` and
|
||||
`a.py`, or names that differ in case alone on Windows, a file of the new
|
||||
version was removed after it was extracted. A name of the old list that leads
|
||||
out of the nodepack, with `..` or as an absolute path, removed a file outside
|
||||
it; nothing is removed for such a name. A file that the old version has alone
|
||||
and that cannot be removed, as one that another program has open on Windows,
|
||||
is left with a warning, and the switch goes on with the files of the new
|
||||
version. A nodepack whose directory keeps its name is no longer moved onto
|
||||
itself at the next start, which Windows refuses while a file in it is open.
|
||||
When the switch moves the nodepack to another directory, the install script
|
||||
of the new version runs there; it was looked for in the directory that the
|
||||
nodepack was moved from, and did not run.
|
||||
A folder that the files of the old version left empty, or with nothing but
|
||||
the `__pycache__` of Python, stayed, and a file of the new version could not
|
||||
take its place; such a folder is removed.
|
||||
- Read the list of the files of a Registry nodepack as UTF-8, which is how it
|
||||
is written. It was read in the encoding of the system: on Windows a switch of
|
||||
version of a nodepack with a file name that the code page of the system
|
||||
cannot decode ended in the middle, with the files of the new version
|
||||
unpacked, its install script not run and the files of the old version left. A
|
||||
name of the list is read as it is written: a space at its start or its end
|
||||
was dropped, and the file of the other name was the one removed.
|
||||
|
||||
- Refuse a `db_mode` or an `update_policy` that Manager does not know in the
|
||||
legacy server. With `--enable-manager-legacy-ui`, the two setting routes
|
||||
stored whatever value a request carried and wrote it to `config.ini`. They
|
||||
answer 400 for a value that is not one of the known ones, as the default
|
||||
server does.
|
||||
- Answer 400 from the two setting routes of both servers for a JSON body that
|
||||
is not an object. It ended with status 500.
|
||||
- Name the security level `normal-` and the database mode `channel` as the
|
||||
servers do in `common/enums.py`, which had `normal-minus` and no `channel`.
|
||||
Nothing read these two members.
|
||||
|
||||
- Keep a database mode, update policy or share option that is chosen in the
|
||||
legacy Manager menu while the menu is still loading the stored value. The
|
||||
value was saved, but the menu went back to showing the old one when it
|
||||
arrived.
|
||||
|
||||
- Draw the dialogs of the legacy UI with styles of Manager's own. The Manager
|
||||
menu, the Custom Nodes Manager, the Model Manager and the Snapshot Manager
|
||||
were built with the classes of PrimeVue dialogs and buttons, and a ComfyUI
|
||||
frontend that no longer ships those styles drew them without a background:
|
||||
the buttons lay over the canvas and the nodes behind them. `main` has had
|
||||
this change since #3392.
|
||||
|
||||
## [4.4] - 2026-11-16
|
||||
|
||||
### Changed
|
||||
@@ -394,6 +719,8 @@ programmatic clients.
|
||||
perform the change from a trusted entry point. Read access via `GET` is
|
||||
unaffected.
|
||||
|
||||
[4.4.2]: https://github.com/Comfy-Org/ComfyUI-Manager/compare/v4.4.1...v4.4.2
|
||||
[4.4.1]: https://github.com/Comfy-Org/ComfyUI-Manager/compare/v4.4...v4.4.1
|
||||
[4.4]: https://github.com/Comfy-Org/ComfyUI-Manager/compare/v4.3...v4.4
|
||||
[4.3]: https://github.com/Comfy-Org/ComfyUI-Manager/compare/v4.2.2...v4.3
|
||||
[4.2.2]: https://github.com/Comfy-Org/ComfyUI-Manager/compare/v4.2.1...v4.2.2
|
||||
|
||||
+2
-1
@@ -11,4 +11,5 @@ include extras.json
|
||||
include github-stats.json
|
||||
include model-list.json
|
||||
include alter-list.json
|
||||
include comfyui_manager/channels.list.template
|
||||
include comfyui_manager/channels.list.template
|
||||
prune tests
|
||||
|
||||
@@ -330,10 +330,10 @@ The security settings are applied based on whether the ComfyUI server's listener
|
||||
|
||||
| Risky Level | features |
|
||||
|-------------|---------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| high+ | * **Switch ComfyUI version**<BR>* **Fix nodepack** |
|
||||
| high+ | * **Switch ComfyUI version**<BR>* **Restore Snapshot**<BR>* **Fix nodepack** |
|
||||
| high | _(no features at this tier — `Fix nodepack` promoted to `high+` to align the enforcement gate with the `SECURITY_MESSAGE_HIGH_P` log text)_ |
|
||||
| middle+ | * Uninstall/Update<BR>* Installation of Git/nightly nodepacks registered in the `default channel`.<BR>* Restore/Remove Snapshot<BR>* Install model |
|
||||
| middle | * Restart<BR>* Installation of CNR release versions (subject to the flagged-version policy below) |
|
||||
| middle+ | * Uninstall/Update<BR>* Installation of Git/nightly nodepacks registered in the `default channel`.<BR>* Enabling a disabled nightly in the place of an enabled Registry version.<BR>* Install model |
|
||||
| middle | * Restart<BR>* Remove Snapshot<BR>* Installation of CNR release versions (subject to the flagged-version policy below) |
|
||||
| low | * Update ComfyUI |
|
||||
|
||||
* **Note**: `Install via git url` and `pip install` are no longer gated by `security_level` — they moved to the dedicated flags `allow_git_url_install` / `allow_pip_install`. Installation of a nodepack registered not in the `default channel` likewise requires `allow_git_url_install` (in addition to the `middle+` level preconditions) instead of a `high+` security level. See the [Dedicated install flags](#dedicated-install-flags-allow_git_url_install--allow_pip_install) subsection below.
|
||||
|
||||
+21
-17
@@ -32,6 +32,7 @@ if not os.path.exists(os.path.join(comfy_path, 'folder_paths.py')):
|
||||
|
||||
|
||||
import utils.extra_config
|
||||
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
|
||||
@@ -80,7 +81,7 @@ core.check_invalid_nodes()
|
||||
def read_downgrade_blacklist():
|
||||
try:
|
||||
import configparser
|
||||
config = configparser.ConfigParser(strict=False)
|
||||
config = configparser.ConfigParser(strict=False, interpolation=None)
|
||||
config.read(context.manager_config_path)
|
||||
default_conf = config['default']
|
||||
|
||||
@@ -135,25 +136,25 @@ class Ctx:
|
||||
self.no_deps = no_deps
|
||||
|
||||
def set_user_directory(self, user_directory):
|
||||
if user_directory is None:
|
||||
return
|
||||
if user_directory is not None:
|
||||
extra_model_paths_yaml = os.path.join(user_directory, 'extra_model_paths.yaml')
|
||||
if os.path.exists(extra_model_paths_yaml):
|
||||
utils.extra_config.load_extra_path_config(extra_model_paths_yaml)
|
||||
|
||||
extra_model_paths_yaml = os.path.join(user_directory, 'extra_model_paths.yaml')
|
||||
if os.path.exists(extra_model_paths_yaml):
|
||||
utils.extra_config.load_extra_path_config(extra_model_paths_yaml)
|
||||
context.update_user_directory(user_directory)
|
||||
|
||||
context.update_user_directory(user_directory)
|
||||
if os.path.exists(context.manager_pip_overrides_path):
|
||||
with open(context.manager_pip_overrides_path, 'r', encoding="UTF-8", errors="ignore") as json_file:
|
||||
cm_global.pip_overrides = json.load(json_file)
|
||||
|
||||
if os.path.exists(context.manager_pip_overrides_path):
|
||||
with open(context.manager_pip_overrides_path, 'r', encoding="UTF-8", errors="ignore") as json_file:
|
||||
cm_global.pip_overrides = json.load(json_file)
|
||||
if os.path.exists(context.manager_pip_blacklist_path):
|
||||
with open(context.manager_pip_blacklist_path, 'r', encoding="UTF-8", errors="ignore") as f:
|
||||
for x in f.readlines():
|
||||
y = x.strip()
|
||||
if y != '':
|
||||
cm_global.pip_blacklist.add(y)
|
||||
|
||||
if os.path.exists(context.manager_pip_blacklist_path):
|
||||
with open(context.manager_pip_blacklist_path, 'r', encoding="UTF-8", errors="ignore") as f:
|
||||
for x in f.readlines():
|
||||
y = x.strip()
|
||||
if y != '':
|
||||
cm_global.pip_blacklist.add(y)
|
||||
setup_git_environment(core.get_config()['git_exe'])
|
||||
|
||||
def update_custom_nodes_dir(self, target_dir):
|
||||
import folder_paths
|
||||
@@ -1212,7 +1213,7 @@ def restore_snapshot(
|
||||
|
||||
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, context.manager_files_path)
|
||||
try:
|
||||
asyncio.run(core.restore_snapshot(snapshot_path, extras))
|
||||
is_restored = asyncio.run(core.restore_snapshot(snapshot_path, extras))
|
||||
except Exception:
|
||||
print("[bold red]ERROR: Failed to restore snapshot.[/bold red]")
|
||||
traceback.print_exc()
|
||||
@@ -1222,6 +1223,9 @@ def restore_snapshot(
|
||||
|
||||
_finalize_resolve(pip_fixer, uv_compile)
|
||||
|
||||
if not is_restored:
|
||||
raise typer.Exit(code=1)
|
||||
|
||||
|
||||
@app.command(
|
||||
"restore-dependencies", help="Restore dependencies from whole installed custom nodes."
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
"""Shared settings-file writer for glob and legacy."""
|
||||
import configparser
|
||||
import logging
|
||||
import os
|
||||
import tempfile
|
||||
|
||||
from rich import print
|
||||
|
||||
|
||||
class DirtyTrackingConfig(dict):
|
||||
"""Track keys assigned after loading the startup configuration."""
|
||||
@@ -23,17 +22,35 @@ class DirtyTrackingConfig(dict):
|
||||
super().update(incoming)
|
||||
|
||||
|
||||
SETTING_VALUES = {
|
||||
'security_level': ('normal', 'strong', 'normal-', 'weak'),
|
||||
'network_mode': ('public', 'private', 'offline', 'personal_cloud'),
|
||||
'db_mode': ('cache', 'channel', 'local', 'remote'),
|
||||
'update_policy': ('stable-comfyui', 'nightly-comfyui', 'stable', 'nightly'),
|
||||
}
|
||||
|
||||
|
||||
def with_valid_values(settings):
|
||||
for key, values in SETTING_VALUES.items():
|
||||
default = values[0]
|
||||
if settings[key] not in values:
|
||||
logging.warning(f"[ComfyUI-Manager] {key} = {settings[key]!r} in config.ini is not valid; '{default}' is used.")
|
||||
settings[key] = default
|
||||
|
||||
return settings
|
||||
|
||||
|
||||
def write_config_merged(config_path, cached, written_config_keys):
|
||||
"""Merge changed owned keys onto the latest settings on disk.
|
||||
|
||||
Preserve parsed keys and values, not INI comments or formatting."""
|
||||
config = configparser.ConfigParser(strict=False)
|
||||
config = configparser.ConfigParser(strict=False, interpolation=None)
|
||||
try:
|
||||
loaded = config.read(config_path)
|
||||
except (configparser.Error, UnicodeDecodeError) as e:
|
||||
# Preserve the existing fallback for malformed files.
|
||||
print(f"[ComfyUI-Manager] Warning: '{config_path}' could not be parsed ({e}); rewriting it from the current settings.")
|
||||
config = configparser.ConfigParser(strict=False)
|
||||
logging.warning(f"[ComfyUI-Manager] '{config_path}' could not be parsed ({e}); rewriting it from the current settings.")
|
||||
config = configparser.ConfigParser(strict=False, interpolation=None)
|
||||
else:
|
||||
# ConfigParser.read silently skips unreadable files; do not overwrite one.
|
||||
if not loaded and os.path.exists(config_path):
|
||||
|
||||
@@ -9,10 +9,11 @@ class NetworkMode(enum.Enum):
|
||||
class SecurityLevel(enum.Enum):
|
||||
STRONG = "strong"
|
||||
NORMAL = "normal"
|
||||
NORMAL_MINUS = "normal-minus"
|
||||
NORMAL_MINUS = "normal-"
|
||||
WEAK = "weak"
|
||||
|
||||
class DBMode(enum.Enum):
|
||||
LOCAL = "local"
|
||||
CACHE = "cache"
|
||||
CHANNEL = "channel"
|
||||
REMOTE = "remote"
|
||||
@@ -15,7 +15,10 @@ Exports:
|
||||
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from abc import ABC, abstractmethod
|
||||
from collections import deque
|
||||
from datetime import datetime, timezone, timedelta
|
||||
@@ -52,25 +55,91 @@ def _to_https_url(url):
|
||||
# Backend selection
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def which_on_path(name):
|
||||
"""Return the file that the directories of PATH give for a command name.
|
||||
|
||||
`shutil.which` looks in the current directory first on Windows, and takes
|
||||
a directory of PATH that is not absolute.
|
||||
"""
|
||||
names = [name]
|
||||
if os.name == 'nt':
|
||||
extensions = [x for x in os.environ.get('PATHEXT', '.COM;.EXE;.BAT;.CMD').split(os.pathsep) if x]
|
||||
if not name.lower().endswith(tuple(x.lower() for x in extensions)):
|
||||
names = [name + x for x in extensions]
|
||||
|
||||
for directory in os.get_exec_path():
|
||||
for x in names:
|
||||
path = os.path.join(directory, x)
|
||||
if os.path.isabs(directory) and os.path.isfile(path) and os.access(path, os.X_OK):
|
||||
return path
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def find_git_executable(git_exe, timeout=10):
|
||||
# A name without a directory is a command of PATH; GitPython would take it
|
||||
# as a file of the current directory.
|
||||
path = shutil.which(git_exe) if os.path.dirname(git_exe) else which_on_path(git_exe)
|
||||
if path is None:
|
||||
return None
|
||||
|
||||
try:
|
||||
# The answer goes to a file: with a pipe, Windows waits after the time
|
||||
# is up for every program that holds the pipe.
|
||||
with tempfile.TemporaryFile() as answer:
|
||||
res = subprocess.run([path, 'version'], stdout=answer, stderr=subprocess.DEVNULL,
|
||||
stdin=subprocess.DEVNULL, timeout=timeout)
|
||||
answer.seek(0)
|
||||
is_git = res.returncode == 0 and answer.read(11) == b'git version'
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
return None
|
||||
|
||||
return os.path.abspath(path) if is_git else None
|
||||
|
||||
|
||||
_PYGIT2_REQUESTED = os.environ.get('CM_USE_PYGIT2', '').strip() == '1'
|
||||
USE_PYGIT2 = _PYGIT2_REQUESTED
|
||||
|
||||
_GIT_EXE = os.environ.get('GIT_EXE_PATH')
|
||||
_GIT_EXE_FOUND = None
|
||||
|
||||
|
||||
def _find_configured_git():
|
||||
found = find_git_executable(_GIT_EXE)
|
||||
if found is not None:
|
||||
os.environ['GIT_PYTHON_GIT_EXECUTABLE'] = found
|
||||
else:
|
||||
print(f"[ComfyUI-Manager] `git_exe = {_GIT_EXE}` is not a working git executable. The default git is used.", file=sys.stderr)
|
||||
return found
|
||||
|
||||
|
||||
if not USE_PYGIT2 and _GIT_EXE:
|
||||
_GIT_EXE_FOUND = _find_configured_git()
|
||||
|
||||
if not USE_PYGIT2:
|
||||
try:
|
||||
import git as _git
|
||||
_git.Git().execute(['git', '--version'])
|
||||
_git.Git().execute([_git.Git.GIT_PYTHON_GIT_EXECUTABLE, '--version'])
|
||||
except Exception:
|
||||
USE_PYGIT2 = True
|
||||
|
||||
if USE_PYGIT2:
|
||||
# Without a git, GitPython raises already when it is imported, unless it
|
||||
# is told to keep quiet. The legacy modules import it themselves.
|
||||
os.environ.setdefault('GIT_PYTHON_REFRESH', 'quiet')
|
||||
|
||||
try:
|
||||
import pygit2 as _pygit2
|
||||
except ImportError:
|
||||
# pygit2 not available either — fall back to GitPython and let it
|
||||
# fail at the point of use, preserving pre-existing behavior.
|
||||
# fail at the point of use.
|
||||
USE_PYGIT2 = False
|
||||
if _PYGIT2_REQUESTED and _GIT_EXE:
|
||||
_GIT_EXE_FOUND = _find_configured_git()
|
||||
_PYGIT2_REQUESTED = False
|
||||
import git as _git
|
||||
if not _git.GIT_OK:
|
||||
print("[ComfyUI-Manager] No git executable was found and pygit2 is not installed. What needs git will fail.", file=sys.stderr)
|
||||
else:
|
||||
# Disable owner validation once at import time.
|
||||
# Required for Desktop 2.0 standalone installs where repo directories
|
||||
@@ -237,7 +306,14 @@ class GitRepo(ABC):
|
||||
def checkout_new_branch(self, branch_name: str, start_point: str): ...
|
||||
|
||||
@abstractmethod
|
||||
def submodule_update(self): ...
|
||||
def submodule_update(self, init=True): ...
|
||||
|
||||
def undo_pull(self, commit):
|
||||
self.reset_hard(commit)
|
||||
try:
|
||||
self.submodule_update(init=False)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def clear_cache(self): ...
|
||||
@@ -415,13 +491,17 @@ class _GitPythonRepo(GitRepo):
|
||||
self._repo.create_head(name)
|
||||
|
||||
def checkout(self, ref):
|
||||
# ref can be a _HeadProxy from get_head_by_name
|
||||
if isinstance(ref, _HeadProxy):
|
||||
ref = ref.name
|
||||
|
||||
self._repo.git.checkout(ref)
|
||||
|
||||
def checkout_new_branch(self, branch_name, start_point):
|
||||
self._repo.git.checkout('-b', branch_name, start_point)
|
||||
|
||||
def submodule_update(self):
|
||||
self._repo.git.submodule('update', '--init', '--recursive')
|
||||
def submodule_update(self, init=True):
|
||||
self._repo.git.submodule('update', *(['--init'] if init else []), '--recursive')
|
||||
|
||||
def clear_cache(self):
|
||||
self._repo.git.clear_cache()
|
||||
@@ -440,6 +520,17 @@ class _GitPythonRepo(GitRepo):
|
||||
# Pygit2 wrapper
|
||||
# ===================================================================
|
||||
|
||||
def _remote_callbacks():
|
||||
"""The callbacks of a clone or a fetch, without the one for the progress messages of the server.
|
||||
|
||||
pygit2 decodes each piece of such a message as UTF-8 before it calls that one, and a piece can end
|
||||
in the middle of a character: the clone or the fetch then ended with UnicodeDecodeError.
|
||||
"""
|
||||
callbacks = _pygit2.RemoteCallbacks()
|
||||
callbacks.sideband_progress = None
|
||||
return callbacks
|
||||
|
||||
|
||||
class _Pygit2Repo(GitRepo):
|
||||
def __init__(self, path):
|
||||
repo_path = os.path.abspath(path)
|
||||
@@ -467,12 +558,12 @@ class _Pygit2Repo(GitRepo):
|
||||
anon.fetch(
|
||||
list(refspecs) if refspecs is not None
|
||||
else list(remote.fetch_refspecs),
|
||||
proxy=_HTTP_PROXY,
|
||||
proxy=_HTTP_PROXY, callbacks=_remote_callbacks(),
|
||||
)
|
||||
elif refspecs is not None:
|
||||
remote.fetch(list(refspecs), proxy=_HTTP_PROXY)
|
||||
remote.fetch(list(refspecs), proxy=_HTTP_PROXY, callbacks=_remote_callbacks())
|
||||
else:
|
||||
remote.fetch(proxy=_HTTP_PROXY)
|
||||
remote.fetch(proxy=_HTTP_PROXY, callbacks=_remote_callbacks())
|
||||
|
||||
@property
|
||||
def working_dir(self):
|
||||
@@ -732,7 +823,11 @@ class _Pygit2Repo(GitRepo):
|
||||
|
||||
def stash(self):
|
||||
sig = _pygit2.Signature('comfyui-manager', 'manager@comfy')
|
||||
self._repo.stash(sig)
|
||||
try:
|
||||
self._repo.stash(sig)
|
||||
except KeyError:
|
||||
# nothing to stash, which is no error for git: a submodule that is at another commit makes the repository dirty
|
||||
pass
|
||||
|
||||
def pull_ff_only(self):
|
||||
branch_name = self.active_branch_name
|
||||
@@ -841,28 +936,96 @@ class _Pygit2Repo(GitRepo):
|
||||
self._repo.checkout(branch)
|
||||
self._repo.set_head(branch.name)
|
||||
|
||||
def submodule_update(self):
|
||||
@staticmethod
|
||||
def _check_out_from(git_dir, path):
|
||||
# set before the repository is opened: pygit2 does not open one whose `core.worktree` names a folder that is not there
|
||||
_pygit2.Config(os.path.join(git_dir, 'config'))['core.worktree'] = os.path.relpath(path, git_dir).replace(os.sep, '/')
|
||||
repo = _pygit2.Repository(git_dir)
|
||||
with open(os.path.join(path, '.git'), 'w', encoding='utf-8') as f:
|
||||
f.write('gitdir: ' + os.path.relpath(git_dir, path).replace(os.sep, '/') + '\n')
|
||||
if not repo.head_is_unborn:
|
||||
repo.reset(repo.head.target, _pygit2.GIT_RESET_HARD)
|
||||
|
||||
@staticmethod
|
||||
def _is_left_without_a_checkout(git_dir):
|
||||
if not os.path.exists(os.path.join(git_dir, 'HEAD')):
|
||||
return False
|
||||
# git keeps the repository of a submodule under its name, which can be the path of another one
|
||||
config = _pygit2.Config(os.path.join(git_dir, 'config'))
|
||||
return 'core.worktree' not in config or not os.path.exists(os.path.join(git_dir, config['core.worktree'], '.git'))
|
||||
|
||||
@staticmethod
|
||||
def _fetchable_submodules(repo):
|
||||
# pygit2 lists the submodules by path, and one that is looked up by its path has no url when its name is another
|
||||
names = {}
|
||||
gitmodules = os.path.join(repo.workdir, '.gitmodules')
|
||||
if os.path.exists(gitmodules):
|
||||
names = {entry.value: entry.name[len('submodule.'):-len('.path')] for entry in _pygit2.Config(gitmodules)
|
||||
if entry.name.startswith('submodule.') and entry.name.endswith('.path')}
|
||||
top = os.path.normcase(os.path.realpath(repo.workdir))
|
||||
named = [repo.submodules.get(names[path]) for path in repo.listall_submodules()
|
||||
if path in names and os.path.normcase(os.path.realpath(os.path.join(top, path))).startswith(top + os.sep)]
|
||||
return [submodule.name for submodule in named
|
||||
if submodule is not None and submodule.head_id is not None and submodule.url is not None]
|
||||
|
||||
def _update_submodules(self, repo, init):
|
||||
def checkout_of(name):
|
||||
return os.path.join(repo.workdir, repo.submodules[name].path)
|
||||
|
||||
fetchable = self._fetchable_submodules(repo)
|
||||
if init:
|
||||
for name in fetchable:
|
||||
# pygit2 does not clone into a folder that is not there
|
||||
os.makedirs(checkout_of(name), exist_ok=True)
|
||||
# a repository in `.git/modules` without a checkout: pygit2 refuses to clone into it
|
||||
leftover = os.path.join(repo.path, 'modules', repo.submodules[name].path)
|
||||
if not os.path.exists(os.path.join(checkout_of(name), '.git')) and self._is_left_without_a_checkout(leftover):
|
||||
self._check_out_from(leftover, checkout_of(name))
|
||||
checked_out = [name for name in fetchable if os.path.exists(os.path.join(checkout_of(name), '.git'))]
|
||||
names = fetchable if init else checked_out
|
||||
|
||||
if init and names:
|
||||
repo.submodules.init(names)
|
||||
for name in names:
|
||||
url = repo.config[f'submodule.{name}.url']
|
||||
if _to_https_url(url) != url:
|
||||
repo.config[f'submodule.{name}.url'] = _to_https_url(url)
|
||||
|
||||
if _HTTP_PROXY is not None:
|
||||
# `update` cannot be given the proxy: what it would fetch is fetched here, and it is left the checkout
|
||||
for name in names:
|
||||
submodule = repo.submodules[name]
|
||||
if name not in checked_out:
|
||||
# the url that `init` resolved: the one of `.gitmodules` may be relative
|
||||
_pygit2.clone_repository(repo.config[f'submodule.{name}.url'], os.path.join(repo.workdir, submodule.path),
|
||||
proxy=_HTTP_PROXY, callbacks=_remote_callbacks())
|
||||
else:
|
||||
cloned = submodule.open()
|
||||
if submodule.head_id not in cloned:
|
||||
cloned.remotes['origin'].fetch(proxy=_HTTP_PROXY, callbacks=_remote_callbacks())
|
||||
if names:
|
||||
repo.submodules.update(names, callbacks=_remote_callbacks())
|
||||
|
||||
for name in names:
|
||||
self._update_submodules(repo.submodules[name].open(), init)
|
||||
|
||||
def submodule_update(self, init=True):
|
||||
try:
|
||||
self._repo.submodules.init()
|
||||
self._repo.submodules.update()
|
||||
except Exception:
|
||||
import subprocess
|
||||
self._update_submodules(self._repo, init)
|
||||
except Exception as e:
|
||||
try:
|
||||
result = subprocess.run(
|
||||
['git', 'submodule', 'update', '--init', '--recursive'],
|
||||
['git', 'submodule', 'update', *(['--init'] if init else []), '--recursive'],
|
||||
cwd=self._working_dir,
|
||||
capture_output=True, timeout=120,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
raise GitCommandError(
|
||||
f"submodule update failed (exit {result.returncode}): "
|
||||
f"{result.stderr.decode(errors='replace')}")
|
||||
except FileNotFoundError:
|
||||
print("[ComfyUI-Manager] pygit2: submodule update requires system git (not installed)", file=sys.stderr)
|
||||
except GitCommandError:
|
||||
raise
|
||||
except Exception as sub_e:
|
||||
print(f"[ComfyUI-Manager] pygit2: submodule update failed: {sub_e}", file=sys.stderr)
|
||||
raise GitCommandError(f"submodule update failed: {e}") from e
|
||||
|
||||
if result.returncode != 0:
|
||||
raise GitCommandError(
|
||||
f"submodule update failed (exit {result.returncode}): "
|
||||
f"{result.stderr.decode(errors='replace')}")
|
||||
|
||||
def clear_cache(self):
|
||||
pass
|
||||
@@ -918,9 +1081,9 @@ def clone_repo(url, dest, progress=None):
|
||||
# configured so proxy-less installs keep working on older pygit2.
|
||||
# (A configured proxy still needs >=1.18 — see requirements.txt.)
|
||||
if _HTTP_PROXY is not None:
|
||||
_pygit2.clone_repository(_to_https_url(url), dest, proxy=_HTTP_PROXY)
|
||||
_pygit2.clone_repository(_to_https_url(url), dest, proxy=_HTTP_PROXY, callbacks=_remote_callbacks())
|
||||
else:
|
||||
_pygit2.clone_repository(_to_https_url(url), dest)
|
||||
_pygit2.clone_repository(_to_https_url(url), dest, callbacks=_remote_callbacks())
|
||||
repo = _Pygit2Repo(dest)
|
||||
repo.submodule_update()
|
||||
return repo
|
||||
@@ -934,7 +1097,15 @@ def clone_repo(url, dest, progress=None):
|
||||
|
||||
def setup_git_environment(git_exe):
|
||||
"""Configure the git executable path (GitPython only)."""
|
||||
if USE_PYGIT2:
|
||||
if USE_PYGIT2 or not git_exe:
|
||||
return
|
||||
if git_exe:
|
||||
_git.Git().update_environment(GIT_PYTHON_GIT_EXECUTABLE=git_exe)
|
||||
|
||||
if git_exe == _GIT_EXE:
|
||||
found = _GIT_EXE_FOUND
|
||||
else:
|
||||
found = find_git_executable(git_exe)
|
||||
if found is None:
|
||||
print(f"[ComfyUI-Manager] `git_exe = {git_exe}` is not a working git executable. The default git is used.", file=sys.stderr)
|
||||
|
||||
if found is not None and _git.Git.GIT_PYTHON_GIT_EXECUTABLE != found:
|
||||
_git.refresh(found)
|
||||
|
||||
@@ -6,7 +6,7 @@ import traceback
|
||||
# Make git_compat importable as a standalone subprocess script
|
||||
sys.path.insert(0, os.path.dirname(__file__))
|
||||
|
||||
from git_compat import open_repo, clone_repo, GitCommandError, setup_git_environment
|
||||
from git_compat import open_repo, clone_repo, GitCommandError
|
||||
import json
|
||||
import yaml
|
||||
import requests
|
||||
@@ -18,7 +18,6 @@ except ImportError:
|
||||
|
||||
|
||||
comfy_path = os.environ.get('COMFYUI_PATH')
|
||||
git_exe_path = os.environ.get('GIT_EXE_PATH')
|
||||
|
||||
if comfy_path is None:
|
||||
print("git_helper: environment variable 'COMFYUI_PATH' is not specified.")
|
||||
@@ -267,6 +266,7 @@ def gitpull(path):
|
||||
print("CUSTOM NODE PULL: None") # there is no update
|
||||
return
|
||||
|
||||
tip_before_pull = repo.head_commit_hexsha
|
||||
try:
|
||||
repo.pull_ff_only()
|
||||
except GitCommandError:
|
||||
@@ -276,7 +276,12 @@ def gitpull(path):
|
||||
repo.reset_hard(f'{remote_name}/{branch_name}')
|
||||
print(f"[ComfyUI-Manager] Reset to {remote_name}/{branch_name}")
|
||||
|
||||
repo.submodule_update()
|
||||
try:
|
||||
repo.submodule_update()
|
||||
except Exception:
|
||||
repo.undo_pull(tip_before_pull)
|
||||
raise
|
||||
|
||||
new_commit_hash = repo.head_commit_hexsha
|
||||
|
||||
if commit_hash != new_commit_hash:
|
||||
@@ -286,6 +291,7 @@ def gitpull(path):
|
||||
except Exception as e:
|
||||
print(e)
|
||||
print("CUSTOM NODE PULL: Fail") # unknown git error
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def checkout_comfyui_hash(target_hash):
|
||||
@@ -537,14 +543,6 @@ def restore_pip_snapshot(pips, options):
|
||||
print(f"Installation failed for pip packages: {failed}")
|
||||
|
||||
|
||||
def setup_environment():
|
||||
if git_exe_path is not None:
|
||||
setup_git_environment(git_exe_path)
|
||||
|
||||
|
||||
setup_environment()
|
||||
|
||||
|
||||
try:
|
||||
if sys.argv[1] == "--clone":
|
||||
repo_path = None
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import os
|
||||
import configparser
|
||||
import logging
|
||||
|
||||
|
||||
GITHUB_ENDPOINT = os.getenv('GITHUB_ENDPOINT')
|
||||
@@ -12,26 +13,110 @@ def is_git_repo(path: str) -> bool:
|
||||
return os.path.exists(os.path.join(path, '.git'))
|
||||
|
||||
|
||||
def get_commit_hash(fullpath):
|
||||
git_head = os.path.join(fullpath, '.git', 'HEAD')
|
||||
if os.path.exists(git_head):
|
||||
with open(git_head) as f:
|
||||
line = f.readline()
|
||||
def file_name_of_git_for_windows(name):
|
||||
"""The name that Git for Windows gives the file of a ref, whose name is `name` in bytes.
|
||||
|
||||
if line.startswith("ref: "):
|
||||
ref = os.path.join(fullpath, '.git', line[5:].strip())
|
||||
if os.path.exists(ref):
|
||||
with open(ref) as f2:
|
||||
return f2.readline().strip()
|
||||
else:
|
||||
return "unknown"
|
||||
else:
|
||||
# Detached HEAD: the file holds the commit hash and a newline.
|
||||
return line.strip()
|
||||
A name that is not UTF-8 is no name of a file there: a byte that is not of a character becomes
|
||||
the character of its number, or below 0xa0 its two hex digits, as in `xutftowcsn` of compat/mingw.c of git."""
|
||||
file_name = ''
|
||||
at = 0
|
||||
while at < len(name):
|
||||
size = 1 if name[at] < 0xc2 else 2 if name[at] < 0xe0 else 3 if name[at] < 0xf0 else 4
|
||||
try:
|
||||
file_name += name[at:at + size].decode('utf-8', 'surrogatepass')
|
||||
at += size
|
||||
except UnicodeDecodeError:
|
||||
file_name += chr(name[at]) if name[at] >= 0xa0 else '%02x' % name[at]
|
||||
at += 1
|
||||
|
||||
return file_name
|
||||
|
||||
|
||||
def get_commit_hash(fullpath):
|
||||
git_dir = os.path.join(fullpath, '.git')
|
||||
try:
|
||||
with open(os.path.join(git_dir, 'HEAD'), 'rb') as f:
|
||||
line = f.readline().strip()
|
||||
|
||||
if not line.startswith(b"ref:"):
|
||||
return line.decode('ascii', errors='replace')
|
||||
|
||||
ref_name = line[4:].strip()
|
||||
# put together as git does it, and not with `os.path.join`, for which a name can lead elsewhere
|
||||
if os.name == 'nt':
|
||||
ref = git_dir + '/' + file_name_of_git_for_windows(ref_name)
|
||||
else:
|
||||
ref = os.fsencode(git_dir) + b'/' + ref_name
|
||||
# a folder there is no ref, as for git: a branch `feature/x` beside the unborn branch `feature`
|
||||
if os.path.isfile(ref):
|
||||
with open(ref, 'rb') as f:
|
||||
return f.readline().strip().decode('ascii', errors='replace')
|
||||
|
||||
# after `git pack-refs` or `git gc` the ref is a line of packed-refs
|
||||
with open(os.path.join(git_dir, 'packed-refs'), 'rb') as f:
|
||||
for packed in f:
|
||||
fields = packed.split()
|
||||
if len(fields) == 2 and fields[1] == ref_name:
|
||||
return fields[0].decode('ascii', errors='replace')
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
return "unknown"
|
||||
|
||||
|
||||
warned_git_configs = set()
|
||||
|
||||
|
||||
def lines_of_git_config(lines):
|
||||
"""
|
||||
the lines as git takes them: a `\\` at the end of a line makes the next line more of the same value,
|
||||
and a line may be indented by any amount
|
||||
"""
|
||||
whole, quoted = '', False
|
||||
for line in lines:
|
||||
line = line.rstrip('\n')
|
||||
goes_on = False
|
||||
i = 0
|
||||
while i < len(line):
|
||||
if line[i] == '\\':
|
||||
goes_on = i == len(line) - 1
|
||||
i += 1
|
||||
elif line[i] == '"':
|
||||
quoted = not quoted
|
||||
elif line[i] in '#;' and not quoted:
|
||||
break
|
||||
i += 1
|
||||
|
||||
if goes_on:
|
||||
whole += line[:-1]
|
||||
else:
|
||||
yield (whole + line).lstrip() + '\n'
|
||||
whole, quoted = '', False
|
||||
|
||||
if whole:
|
||||
yield whole.lstrip() + '\n'
|
||||
|
||||
|
||||
def read_git_config(git_config_path) -> 'configparser.ConfigParser | None':
|
||||
# Set `strict=False` to allow duplicate `vscode-merge-base` sections, addressing <https://github.com/ltdrdata/ComfyUI-Manager/issues/1529>
|
||||
# a url may hold a `%`, git accepts a key without a value, the file may start with a BOM,
|
||||
# and a value that is not UTF-8 does not make the others unreadable
|
||||
config = configparser.ConfigParser(strict=False, interpolation=None, allow_no_value=True)
|
||||
try:
|
||||
with open(git_config_path, encoding='utf-8-sig', errors='replace') as f:
|
||||
# the parser would take a line that is indented more as more of the value before it
|
||||
config.read_file(lines_of_git_config(f))
|
||||
except (configparser.Error, OSError) as e:
|
||||
if git_config_path not in warned_git_configs:
|
||||
warned_git_configs.add(git_config_path)
|
||||
# the message of a parsing error holds lines of the file, and a url in them can hold a token
|
||||
reason = e.strerror if isinstance(e, OSError) else type(e).__name__
|
||||
logging.warning(f"[ComfyUI-Manager] Cannot read '{git_config_path}': {reason}")
|
||||
return None
|
||||
|
||||
return config
|
||||
|
||||
|
||||
def git_url(fullpath):
|
||||
"""
|
||||
resolve version of unclassified custom node based on remote url in .git/config
|
||||
@@ -41,12 +126,12 @@ def git_url(fullpath):
|
||||
if not os.path.exists(git_config_path):
|
||||
return None
|
||||
|
||||
# Set `strict=False` to allow duplicate `vscode-merge-base` sections, addressing <https://github.com/ltdrdata/ComfyUI-Manager/issues/1529>
|
||||
config = configparser.ConfigParser(strict=False)
|
||||
config.read(git_config_path)
|
||||
config = read_git_config(git_config_path)
|
||||
if config is None:
|
||||
return None
|
||||
|
||||
for k, v in config.items():
|
||||
if k.startswith('remote ') and 'url' in v:
|
||||
if k.startswith('remote ') and v.get('url'):
|
||||
if 'Comfy-Org/ComfyUI-Manager' in v['url']:
|
||||
return "https://github.com/ltdrdata/ComfyUI-Manager"
|
||||
return v['url']
|
||||
|
||||
@@ -1,21 +1,10 @@
|
||||
"""Security helpers for CSRF protection and Content-Type gating.
|
||||
|
||||
reject_simple_form_post() is applied ONLY to POST handlers that do not consume
|
||||
a request body (e.g., snapshot/save, queue/reset, queue/start, reboot). These
|
||||
are vulnerable to cross-origin <form method=POST> attacks because the server
|
||||
accepts the request without parsing any body — the attacker needs no ability
|
||||
to forge a valid payload, only to point a hidden form at the URL.
|
||||
|
||||
Handlers that DO read a body via ``await request.json()`` (install/git_url,
|
||||
install/pip, queue/install_model, db_mode POST, policy/update POST,
|
||||
channel_url_list POST, queue/batch, queue/task, import_fail_info, etc.) are
|
||||
NOT gated here — a cross-origin <form method=POST> cannot forge a valid JSON
|
||||
body because the browser refuses to send ``application/json`` without a CORS
|
||||
preflight, which this server rejects by not responding with an appropriate
|
||||
Access-Control-Allow-Origin.
|
||||
|
||||
DO NOT add the gate to body-reading handlers (redundant + UX-breaking).
|
||||
DO NOT remove the gate from no-body handlers (this is the bypass vector).
|
||||
reject_non_json_post() is applied to every POST handler that changes something.
|
||||
A page of another origin can make a browser send a POST without a CORS
|
||||
preflight: as a form, or with no Content-Type at all, with or without a body.
|
||||
``request.json()`` parses a body whatever its Content-Type. The page cannot
|
||||
send ``application/json`` without a preflight.
|
||||
"""
|
||||
|
||||
import logging
|
||||
@@ -50,44 +39,11 @@ FLAGGED_NODEPACK_INSTALL_GUIDANCE = (
|
||||
)
|
||||
|
||||
|
||||
# CORS "simple request" Content-Type set per Fetch spec §3.2.3. Browsers send
|
||||
# <form method=POST> submissions with one of these three MIME types and do NOT
|
||||
# trigger a CORS preflight, so a malicious cross-origin page can silently POST
|
||||
# into state-changing endpoints if we only gate on HTTP method. Blocking these
|
||||
# three Content-Types on our mutation endpoints forces any non-same-origin POST
|
||||
# to use a non-simple Content-Type (e.g. application/json), which triggers a
|
||||
# preflight that this server rejects (no Access-Control-Allow-Origin response).
|
||||
_SIMPLE_FORM_CONTENT_TYPES = frozenset({
|
||||
'application/x-www-form-urlencoded',
|
||||
'multipart/form-data',
|
||||
'text/plain',
|
||||
})
|
||||
|
||||
|
||||
def reject_simple_form_post(request) -> Optional[web.Response]:
|
||||
"""Reject Content-Types that enable preflight-less <form method=POST> CSRF.
|
||||
|
||||
These 3 MIME types are the complete CORS "simple request" Content-Type set
|
||||
(Fetch spec §3.2.3 "CORS-safelisted request-header"). Blocking them
|
||||
eliminates the <form method=POST> cross-origin CSRF vector, because any
|
||||
other Content-Type triggers a browser-enforced CORS preflight — and this
|
||||
server does not answer preflights with ``Access-Control-Allow-Origin``,
|
||||
effectively blocking cross-origin requests that use non-simple types.
|
||||
|
||||
Returns:
|
||||
web.Response(status=400) when the request has a simple-form
|
||||
Content-Type that must be rejected. None when the request is allowed
|
||||
to proceed (no body, application/json, or any non-simple Content-Type).
|
||||
|
||||
Note:
|
||||
aiohttp's ``request.content_type`` normalizes the header (lower-cases,
|
||||
strips parameters), so a ``multipart/form-data; boundary=----X`` header
|
||||
is compared as ``multipart/form-data``.
|
||||
"""
|
||||
if request.content_type in _SIMPLE_FORM_CONTENT_TYPES:
|
||||
def reject_non_json_post(request) -> Optional[web.Response]:
|
||||
if request.content_type != 'application/json':
|
||||
return web.Response(
|
||||
status=400,
|
||||
text='Invalid Content-Type for this endpoint. Use application/json or omit body.',
|
||||
text='Invalid Content-Type for this endpoint. Use application/json.',
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
@@ -323,6 +323,70 @@ def extract_package_as_zip(file_path, extract_path):
|
||||
return None
|
||||
|
||||
|
||||
def is_inside(directory, name):
|
||||
directory = os.path.abspath(directory)
|
||||
try:
|
||||
return os.path.commonpath((directory, os.path.abspath(os.path.join(directory, name)))) == directory
|
||||
except ValueError:
|
||||
# on Windows, a path of another drive
|
||||
return False
|
||||
|
||||
|
||||
def switch_package_files(file_path, path):
|
||||
import zipfile
|
||||
try:
|
||||
with zipfile.ZipFile(file_path, "r") as zip_ref:
|
||||
extracted = zip_ref.namelist()
|
||||
except zipfile.BadZipFile:
|
||||
logging.error(f"File '{file_path}' is not a zip or is corrupted.")
|
||||
return None
|
||||
|
||||
with open(os.path.join(path, '.tracking'), 'r', encoding='utf-8') as f:
|
||||
# As the list is written: a name can start or end with a space.
|
||||
prev_files = {line.rstrip('\n') for line in f}
|
||||
root = os.path.abspath(path)
|
||||
garbage = prev_files - set(extracted)
|
||||
garbage = [os.path.abspath(os.path.join(root, x)) for x in garbage if is_inside(root, x)]
|
||||
|
||||
for x in garbage:
|
||||
try:
|
||||
if os.path.isfile(x):
|
||||
os.remove(x)
|
||||
except OSError as e:
|
||||
logging.warning(f"[ComfyUI-Manager] A file of the old version is left: {e}")
|
||||
|
||||
folders = set()
|
||||
for x in garbage:
|
||||
while len(x) > len(root):
|
||||
folders.add(x)
|
||||
x = os.path.dirname(x)
|
||||
|
||||
real_root = os.path.realpath(root)
|
||||
|
||||
def reached_without_a_link(x):
|
||||
return os.path.normcase(os.path.realpath(x)) == os.path.normcase(real_root + x[len(root):])
|
||||
|
||||
for x in sorted(folders, key=len, reverse=True):
|
||||
try:
|
||||
if not os.path.isdir(x) or not reached_without_a_link(x):
|
||||
continue
|
||||
|
||||
# the files of a `__pycache__` are caches of the modules that were there, as those of Python and of numba
|
||||
cache = os.path.join(x, '__pycache__')
|
||||
if os.listdir(x) == ['__pycache__'] and reached_without_a_link(cache):
|
||||
for name in os.listdir(cache):
|
||||
os.remove(os.path.join(cache, name))
|
||||
os.rmdir(cache)
|
||||
|
||||
if not os.listdir(x):
|
||||
os.rmdir(x)
|
||||
except OSError as e:
|
||||
logging.warning(f"[ComfyUI-Manager] A folder of the old version is left: {e}")
|
||||
|
||||
# after the files are removed: two names can be one file, as names that differ in case alone are on Windows
|
||||
return extract_package_as_zip(file_path, path)
|
||||
|
||||
|
||||
def normalize_pip_name(name):
|
||||
"""Return the key used to compare pip package names.
|
||||
|
||||
@@ -963,3 +1027,4 @@ def restore_pip_snapshot(pips, options):
|
||||
failed.append(x)
|
||||
|
||||
print(f"Installation failed for pip packages: {failed}")
|
||||
return failed
|
||||
|
||||
@@ -224,8 +224,12 @@ class UpdateComfyUIQueryParams(BaseModel):
|
||||
)
|
||||
ui_id: str = Field(..., description="UI identifier for task tracking")
|
||||
stable: Optional[bool] = Field(
|
||||
True,
|
||||
description="Whether to update to stable version (true) or nightly (false)",
|
||||
None,
|
||||
description="Whether to update to stable version (true) or nightly (false). When neither this nor `is_stable` is given, the update policy decides.",
|
||||
)
|
||||
is_stable: Optional[bool] = Field(
|
||||
None,
|
||||
description="Another name for `stable`, the one the task parameters use. Read when `stable` is not given.",
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -29,13 +29,15 @@ from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
|
||||
orig_print = print
|
||||
|
||||
from rich import print
|
||||
import rich
|
||||
from rich.console import Console
|
||||
from rich.markup import escape
|
||||
from packaging import version
|
||||
|
||||
import uuid
|
||||
|
||||
from ..common import cm_global
|
||||
from ..common.config_writer import DirtyTrackingConfig, write_config_merged
|
||||
from ..common.config_writer import DirtyTrackingConfig, with_valid_values, write_config_merged
|
||||
from ..common import cnr_utils
|
||||
from ..common import manager_util
|
||||
from ..common import manager_security
|
||||
@@ -46,6 +48,12 @@ from ..common.enums import NetworkMode, SecurityLevel, DBMode
|
||||
from ..common import context
|
||||
|
||||
|
||||
def print(*objects, sep=" ", end="\n", file=None):
|
||||
# rich's print with its highlighting only, so that a path, a URL or an error text is written as it is
|
||||
console = rich.get_console() if file is None else Console(file=file)
|
||||
console.print(*objects, sep=sep, end=end, markup=False, emoji=False, soft_wrap=True)
|
||||
|
||||
|
||||
try:
|
||||
from importlib.metadata import version as _pkg_version
|
||||
_raw_version = _pkg_version("comfyui-manager")
|
||||
@@ -699,7 +707,7 @@ class UnifiedManager:
|
||||
channel_url = normalize_channel(channel)
|
||||
if channel_url:
|
||||
if mode not in ['remote', 'local', 'cache']:
|
||||
print(f"[bold red]ERROR: Invalid mode is specified `--mode {mode}`[/bold red]", file=sys.stderr)
|
||||
rich.print(f"[bold red]ERROR: Invalid mode is specified `--mode {escape(mode)}`[/bold red]", file=sys.stderr)
|
||||
return {}
|
||||
|
||||
# validate channel - only the channel set by the user is allowed.
|
||||
@@ -793,25 +801,27 @@ class UnifiedManager:
|
||||
for line in lines:
|
||||
package_name = remap_pip_package(line.strip())
|
||||
if package_name and not package_name.startswith('#') and package_name not in self.processed_install:
|
||||
self.processed_install.add(package_name)
|
||||
clean_package_name = package_name.split('#')[0].strip()
|
||||
install_cmd = manager_util.make_pip_cmd(["install", clean_package_name])
|
||||
if clean_package_name != "" and not clean_package_name.startswith('#'):
|
||||
res = res and try_install_script(url, repo_path, install_cmd, instant_execution=instant_execution)
|
||||
if res:
|
||||
self.processed_install.add(package_name)
|
||||
|
||||
pip_fixer.fix_broken()
|
||||
|
||||
if os.path.exists(install_script_path) and install_script_path not in self.processed_install:
|
||||
self.processed_install.add(install_script_path)
|
||||
print("Install: install script")
|
||||
install_cmd = [sys.executable, "install.py"]
|
||||
return res and try_install_script(url, repo_path, install_cmd, instant_execution=instant_execution)
|
||||
res = res and try_install_script(url, repo_path, install_cmd, instant_execution=instant_execution)
|
||||
if res:
|
||||
self.processed_install.add(install_script_path)
|
||||
|
||||
return res
|
||||
|
||||
def reserve_cnr_switch(self, target, zip_url, from_path, to_path, no_deps, status=''):
|
||||
script_path = os.path.join(context.manager_startup_script_path, "install-scripts.txt")
|
||||
with open(script_path, "a") as file:
|
||||
with open(script_path, "a", encoding="utf-8") as file:
|
||||
obj = [target, "#LAZY-CNR-SWITCH-SCRIPT", zip_url, from_path, to_path, no_deps, get_default_custom_nodes_path(), sys.executable, status]
|
||||
file.write(f"{obj}\n")
|
||||
|
||||
@@ -897,10 +907,11 @@ class UnifiedManager:
|
||||
download_path = os.path.join(get_default_custom_nodes_path(), archive_name)
|
||||
manager_downloader.basic_download_url(node_info.download_url, get_default_custom_nodes_path(), archive_name)
|
||||
|
||||
# 2. extract files into <node_id>
|
||||
install_path = self.active_nodes[node_id][1]
|
||||
extracted = manager_util.extract_package_as_zip(download_path, install_path)
|
||||
os.remove(download_path)
|
||||
try:
|
||||
extracted = manager_util.switch_package_files(download_path, install_path)
|
||||
finally:
|
||||
os.remove(download_path)
|
||||
|
||||
if extracted is None:
|
||||
if len(os.listdir(install_path)) == 0:
|
||||
@@ -908,32 +919,10 @@ class UnifiedManager:
|
||||
|
||||
return result.fail(f'Empty archive file: {node_id}@{version_spec}')
|
||||
|
||||
# 3. calculate garbage files (.tracking - extracted)
|
||||
tracking_info_file = os.path.join(install_path, '.tracking')
|
||||
prev_files = set()
|
||||
with open(tracking_info_file, 'r') as f:
|
||||
for line in f:
|
||||
prev_files.add(line.strip())
|
||||
garbage = prev_files.difference(extracted)
|
||||
garbage = [os.path.join(install_path, x) for x in garbage]
|
||||
|
||||
# 4-1. remove garbage files
|
||||
for x in garbage:
|
||||
if os.path.isfile(x):
|
||||
os.remove(x)
|
||||
|
||||
# 4-2. remove garbage dir if empty
|
||||
for x in garbage:
|
||||
if os.path.isdir(x):
|
||||
if not os.listdir(x):
|
||||
os.rmdir(x)
|
||||
|
||||
# 5. create .tracking file
|
||||
tracking_info_file = os.path.join(install_path, '.tracking')
|
||||
with open(tracking_info_file, "w", encoding='utf-8') as file:
|
||||
file.write('\n'.join(list(extracted)))
|
||||
|
||||
# 6. post install
|
||||
result.target = version_spec
|
||||
|
||||
def postinstall():
|
||||
@@ -1318,6 +1307,9 @@ class UnifiedManager:
|
||||
repo.clear_cache()
|
||||
repo.close()
|
||||
|
||||
# an install script that ran in this folder was of the pack that was there before the clone
|
||||
self.processed_install.discard(os.path.join(repo_path, 'install.py'))
|
||||
|
||||
def postinstall():
|
||||
return self.execute_install_script(url, repo_path, instant_execution=instant_execution, no_deps=no_deps)
|
||||
|
||||
@@ -1692,7 +1684,7 @@ def write_config():
|
||||
|
||||
def read_config():
|
||||
try:
|
||||
config = configparser.ConfigParser(strict=False)
|
||||
config = configparser.ConfigParser(strict=False, interpolation=None)
|
||||
config.read(context.manager_config_path)
|
||||
default_conf = config['default']
|
||||
|
||||
@@ -1705,9 +1697,10 @@ def read_config():
|
||||
# Re-reading from config would undo the fallback.
|
||||
manager_util.bypass_ssl = get_bool('bypass_ssl', False)
|
||||
|
||||
return {
|
||||
return with_valid_values({
|
||||
'http_channel_enabled': get_bool('http_channel_enabled', False),
|
||||
'git_exe': default_conf.get('git_exe', ''),
|
||||
# read as written: a path of Windows may hold a `%`, which the parser takes as the start of a reference
|
||||
'git_exe': default_conf.get('git_exe', '', raw=True),
|
||||
'use_uv': get_bool('use_uv', True),
|
||||
'use_unified_resolver': get_bool('use_unified_resolver', False),
|
||||
'channel_url': default_conf.get('channel_url', DEFAULT_CHANNEL),
|
||||
@@ -1727,9 +1720,12 @@ def read_config():
|
||||
'allow_git_url_install': get_bool('allow_git_url_install', False),
|
||||
'allow_pip_install': get_bool('allow_pip_install', False),
|
||||
'allow_flagged_nodepack_install': get_bool('allow_flagged_nodepack_install', False),
|
||||
}
|
||||
})
|
||||
|
||||
except Exception as e:
|
||||
if os.path.exists(context.manager_config_path):
|
||||
logging.warning(f"[ComfyUI-Manager] '{context.manager_config_path}' could not be read ({e!r}); the default settings are used.")
|
||||
|
||||
except Exception:
|
||||
import importlib.util
|
||||
# temporary disable `uv` on Windows by default (https://github.com/Comfy-Org/ComfyUI-Manager/issues/1969)
|
||||
manager_util.use_uv = importlib.util.find_spec("uv") is not None and platform.system() != "Windows"
|
||||
@@ -1834,7 +1830,7 @@ def reserve_script(repo_path, install_cmds):
|
||||
os.makedirs(context.manager_startup_script_path)
|
||||
|
||||
script_path = os.path.join(context.manager_startup_script_path, "install-scripts.txt")
|
||||
with open(script_path, "a") as file:
|
||||
with open(script_path, "a", encoding="utf-8") as file:
|
||||
obj = [repo_path] + install_cmds
|
||||
file.write(f"{obj}\n")
|
||||
|
||||
@@ -1957,7 +1953,8 @@ def __win_check_git_update(path, do_fetch=False, do_update=False):
|
||||
def __win_check_git_pull(path):
|
||||
command = [sys.executable, context.git_script_path, "--pull", path]
|
||||
process = subprocess.Popen(command, env=get_script_env(), cwd=get_default_custom_nodes_path())
|
||||
process.wait()
|
||||
if process.wait() != 0:
|
||||
raise ValueError(f"Failed to pull: {path}")
|
||||
|
||||
|
||||
def execute_install_script(url, repo_path, lazy_mode=False, instant_execution=False, no_deps=False):
|
||||
@@ -2165,9 +2162,14 @@ class GitProgress(RemoteProgress):
|
||||
|
||||
def is_valid_url(url):
|
||||
# Check for HTTP/HTTPS URL format
|
||||
result = urlparse(url)
|
||||
if result.scheme and result.netloc:
|
||||
return True
|
||||
try:
|
||||
result = urlparse(url)
|
||||
if result.scheme and result.netloc:
|
||||
return True
|
||||
except ValueError:
|
||||
# What cannot be parsed, as a host with a bracket that is not closed,
|
||||
# is not such a URL.
|
||||
pass
|
||||
|
||||
# Check for SSH git URL format
|
||||
if SSH_URL_PATTERN.match(url):
|
||||
@@ -2273,6 +2275,7 @@ def git_pull(path):
|
||||
raise ValueError(f"Failed to switch to default branch while pulling: {path}")
|
||||
|
||||
branch_name = repo.active_branch_name
|
||||
commit_hash = repo.head_commit_hexsha
|
||||
remote_name = repo.get_tracking_remote_name()
|
||||
|
||||
try:
|
||||
@@ -2284,7 +2287,11 @@ def git_pull(path):
|
||||
repo.reset_hard(f'{remote_name}/{branch_name}')
|
||||
logging.info(f"[ComfyUI-Manager] Reset to {remote_name}/{branch_name}")
|
||||
|
||||
repo.submodule_update()
|
||||
try:
|
||||
repo.submodule_update()
|
||||
except Exception:
|
||||
repo.undo_pull(commit_hash)
|
||||
raise
|
||||
|
||||
return True
|
||||
|
||||
@@ -3124,6 +3131,30 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
|
||||
installed_node_packs = []
|
||||
failed = []
|
||||
|
||||
def run_postinstall(res):
|
||||
try:
|
||||
return res.postinstall()
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
def attempt(step, *args):
|
||||
try:
|
||||
return step(*args)
|
||||
except Exception as e:
|
||||
logging.error(f"[ComfyUI-Manager] {e}")
|
||||
return ManagedResult('fail').fail(str(e))
|
||||
|
||||
def finish_clone(res, name, path, commit_hash):
|
||||
is_switched = repo_switch_commit(path, commit_hash)
|
||||
is_installed = run_postinstall(res)
|
||||
if is_switched is None:
|
||||
failed.append(f"{name}@{commit_hash}")
|
||||
elif not is_installed:
|
||||
failed.append(name)
|
||||
else:
|
||||
cloned_repos.append(name)
|
||||
|
||||
await unified_manager.reload('cache')
|
||||
await unified_manager.get_custom_nodes('default', 'cache')
|
||||
|
||||
@@ -3133,8 +3164,6 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
|
||||
|
||||
print("Restore snapshot.")
|
||||
|
||||
postinstalls = []
|
||||
|
||||
with open(snapshot_path, 'r', encoding="UTF-8") as snapshot_file:
|
||||
if snapshot_path.endswith('.json'):
|
||||
info = json.load(snapshot_file)
|
||||
@@ -3169,11 +3198,16 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
|
||||
skip_node_packs.append(k)
|
||||
|
||||
for x in todo_disable:
|
||||
unified_manager.unified_disable(x, False)
|
||||
disabled_repos.append(x)
|
||||
if attempt(unified_manager.unified_disable, x, False).result:
|
||||
disabled_repos.append(x)
|
||||
else:
|
||||
failed.append(x)
|
||||
|
||||
for x in todo_checkout:
|
||||
ps = unified_manager.cnr_switch_version(x[0], x[1], instant_execution=True, no_deps=True, return_postinstall=False)
|
||||
try:
|
||||
ps = unified_manager.cnr_switch_version(x[0], x[1], instant_execution=True, no_deps=True, return_postinstall=False)
|
||||
except Exception as e:
|
||||
ps = ManagedResult('switch-cnr').fail(str(e))
|
||||
if ps.action == 'switch-cnr' and ps.result:
|
||||
switched_node_packs.append(f"{x[0]}@{x[1]}")
|
||||
elif ps.action == 'skip':
|
||||
@@ -3188,18 +3222,17 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
|
||||
if 'comfyui-manager' in k or k in checked_cnr:
|
||||
continue
|
||||
|
||||
ps = await unified_manager.install_by_id(k, version_spec=v, instant_execution=True, return_postinstall=True)
|
||||
if ps.action == 'install-cnr' and ps.result:
|
||||
installed_node_packs.append(f"{k}@{v}")
|
||||
elif not ps.result:
|
||||
try:
|
||||
ps = await unified_manager.install_by_id(k, version_spec=v, instant_execution=True, return_postinstall=True)
|
||||
except Exception as e:
|
||||
ps = ManagedResult('install-cnr').fail(str(e))
|
||||
if not ps.result:
|
||||
failed.append(f"{k}@{v}")
|
||||
logging.error(ps.msg)
|
||||
|
||||
if ps is not None and ps.result:
|
||||
if hasattr(ps, 'postinstall'):
|
||||
postinstalls.append(ps.postinstall)
|
||||
else:
|
||||
print("cm-cli: unexpected [0001]")
|
||||
elif not run_postinstall(ps):
|
||||
failed.append(f"{k}@{v}")
|
||||
elif ps.action == 'install-cnr':
|
||||
installed_node_packs.append(f"{k}@{v}")
|
||||
|
||||
# for nightly restore
|
||||
_git_info = info.get('git_custom_nodes')
|
||||
@@ -3211,6 +3244,8 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
|
||||
if 'comfyui-manager' in k.lower():
|
||||
continue
|
||||
|
||||
v.setdefault('hash', 'unknown')
|
||||
|
||||
# Snapshots saved at a detached HEAD used to keep the newline that follows the hash.
|
||||
if isinstance(v.get('hash'), str):
|
||||
v['hash'] = v['hash'].strip()
|
||||
@@ -3236,7 +3271,8 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
|
||||
todo_disable.append(k)
|
||||
else:
|
||||
commit_hash = git_info[normalized_url]['hash']
|
||||
todo_checkout.append((v[1], commit_hash))
|
||||
todo_checkout.append((k, v[1], commit_hash))
|
||||
processed_urls.append(normalized_url)
|
||||
|
||||
for k, v in unified_manager.nightly_inactive_nodes.items():
|
||||
if 'comfyui-manager' in k:
|
||||
@@ -3252,35 +3288,52 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
|
||||
processed_urls.append(normalized_url)
|
||||
|
||||
for x in todo_disable:
|
||||
unified_manager.unified_disable(x, False)
|
||||
disabled_repos.append(x)
|
||||
if attempt(unified_manager.unified_disable, x, False).result:
|
||||
disabled_repos.append(x)
|
||||
else:
|
||||
failed.append(x)
|
||||
|
||||
for x in todo_enable:
|
||||
res = unified_manager.unified_enable(x[0], 'nightly')
|
||||
res = attempt(unified_manager.unified_enable, x[0], 'nightly')
|
||||
|
||||
is_switched = False
|
||||
if res and res.target:
|
||||
is_switched = repo_switch_commit(res.target, x[1])
|
||||
|
||||
if is_switched:
|
||||
if not res.result:
|
||||
failed.append(x[0])
|
||||
elif is_switched is None:
|
||||
failed.append(f"{x[0]}@{x[1]}")
|
||||
elif is_switched:
|
||||
checkout_repos.append(f"{x[0]}@{x[1]}")
|
||||
else:
|
||||
enabled_repos.append(x[0])
|
||||
|
||||
for x in todo_checkout:
|
||||
is_switched = repo_switch_commit(x[0], x[1])
|
||||
for name, path, commit_hash in todo_checkout:
|
||||
is_switched = repo_switch_commit(path, commit_hash)
|
||||
|
||||
if is_switched:
|
||||
checkout_repos.append(f"{x[0]}@{x[1]}")
|
||||
checkout_repos.append(f"{name}@{commit_hash}")
|
||||
elif is_switched is None:
|
||||
failed.append(f"{name}@{commit_hash}")
|
||||
else:
|
||||
skip_node_packs.append(name)
|
||||
|
||||
for x in git_info.keys():
|
||||
if x in processed_urls:
|
||||
continue
|
||||
|
||||
normalized_url = git_utils.normalize_url(x)
|
||||
cnr = unified_manager.repo_cnr_map.get(normalized_url)
|
||||
if cnr is not None:
|
||||
pack_id = cnr['id']
|
||||
res = await unified_manager.install_by_id(pack_id, 'nightly', instant_execution=True, no_deps=False, return_postinstall=False)
|
||||
try:
|
||||
res = await unified_manager.install_by_id(pack_id, 'nightly', instant_execution=True, no_deps=False, return_postinstall=True)
|
||||
except Exception as e:
|
||||
logging.error(f"[ComfyUI-Manager] {e}")
|
||||
res = ManagedResult('fail').fail(str(e))
|
||||
if res.action == 'install-git' and res.result:
|
||||
cloned_repos.append(pack_id)
|
||||
finish_clone(res, pack_id, unified_manager.active_nodes[pack_id][1], git_info[x]['hash'])
|
||||
elif res.action == 'skip':
|
||||
skip_node_packs.append(pack_id)
|
||||
elif not res.result:
|
||||
@@ -3298,6 +3351,9 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
|
||||
processed_urls = []
|
||||
|
||||
for k2, v2 in unified_manager.unknown_active_nodes.items():
|
||||
if 'comfyui-manager' in k2.lower():
|
||||
continue
|
||||
|
||||
repo_url = resolve_giturl_from_path(v2[1])
|
||||
|
||||
if repo_url is None:
|
||||
@@ -3309,7 +3365,7 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
|
||||
todo_disable.append(k2)
|
||||
else:
|
||||
commit_hash = git_info[normalized_url]['hash']
|
||||
todo_checkout.append((k2, commit_hash))
|
||||
todo_checkout.append((k2, v2[1], commit_hash))
|
||||
processed_urls.append(normalized_url)
|
||||
|
||||
for k2, v2 in unified_manager.unknown_inactive_nodes.items():
|
||||
@@ -3326,28 +3382,36 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
|
||||
processed_urls.append(normalized_url)
|
||||
|
||||
for x in todo_disable:
|
||||
unified_manager.unified_disable(x, True)
|
||||
disabled_repos.append(x)
|
||||
if attempt(unified_manager.unified_disable, x, True).result:
|
||||
disabled_repos.append(x)
|
||||
else:
|
||||
failed.append(x)
|
||||
|
||||
for x in todo_enable:
|
||||
res = unified_manager.unified_enable(x[0], 'unknown')
|
||||
res = attempt(unified_manager.unified_enable, x[0], 'unknown')
|
||||
|
||||
is_switched = False
|
||||
if res and res.target:
|
||||
is_switched = repo_switch_commit(res.target, x[1])
|
||||
|
||||
if is_switched:
|
||||
if not res.result:
|
||||
failed.append(x[0])
|
||||
elif is_switched is None:
|
||||
failed.append(f"{x[0]}@{x[1]}")
|
||||
elif is_switched:
|
||||
checkout_repos.append(f"{x[0]}@{x[1]}")
|
||||
else:
|
||||
enabled_repos.append(x[0])
|
||||
|
||||
for x in todo_checkout:
|
||||
is_switched = repo_switch_commit(x[0], x[1])
|
||||
for name, path, commit_hash in todo_checkout:
|
||||
is_switched = repo_switch_commit(path, commit_hash)
|
||||
|
||||
if is_switched:
|
||||
checkout_repos.append(f"{x[0]}@{x[1]}")
|
||||
checkout_repos.append(f"{name}@{commit_hash}")
|
||||
elif is_switched is None:
|
||||
failed.append(f"{name}@{commit_hash}")
|
||||
else:
|
||||
skip_node_packs.append(x[0])
|
||||
skip_node_packs.append(name)
|
||||
|
||||
for x in processed_urls:
|
||||
if x in git_info:
|
||||
@@ -3359,10 +3423,14 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
|
||||
repo_name = repo_name[:-4]
|
||||
|
||||
to_path = os.path.join(get_default_custom_nodes_path(), repo_name)
|
||||
unified_manager.repo_install(repo_url, to_path, instant_execution=True, no_deps=False, return_postinstall=False)
|
||||
cloned_repos.append(repo_name)
|
||||
res = unified_manager.repo_install(repo_url, to_path, instant_execution=True, no_deps=False, return_postinstall=True)
|
||||
if not res.result:
|
||||
failed.append(repo_name)
|
||||
continue
|
||||
|
||||
manager_util.restore_pip_snapshot(pips, git_helper_extras)
|
||||
finish_clone(res, repo_name, to_path, git_info[repo_url]['hash'])
|
||||
|
||||
pips_not_installed = manager_util.restore_pip_snapshot(pips, git_helper_extras)
|
||||
|
||||
# print summary
|
||||
for x in cloned_repos:
|
||||
@@ -3379,11 +3447,15 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
|
||||
print(f"[ DISABLED ] {x}")
|
||||
for x in skip_node_packs:
|
||||
print(f"[ SKIPPED ] {x}")
|
||||
for x in failed:
|
||||
for x in dict.fromkeys(failed):
|
||||
print(f"[ FAILED ] {x}")
|
||||
|
||||
# if is_failed:
|
||||
# print("[bold red]ERROR: Failed to restore snapshot.[/bold red]")
|
||||
return not failed and not pips_not_installed
|
||||
|
||||
|
||||
def parse_semver(tag_name):
|
||||
match = re.fullmatch(r'v(\d+)\.(\d+)\.(\d+)', tag_name)
|
||||
return tuple(int(x) for x in match.groups()) if match else None
|
||||
|
||||
|
||||
def get_comfyui_versions(repo=None):
|
||||
@@ -3398,10 +3470,6 @@ def get_comfyui_versions(repo=None):
|
||||
except Exception:
|
||||
logging.error("[ComfyUI-Manager] Failed to fetch ComfyUI")
|
||||
|
||||
def parse_semver(tag_name):
|
||||
match = re.match(r'^v(\d+)\.(\d+)\.(\d+)$', tag_name)
|
||||
return tuple(int(x) for x in match.groups()) if match else None
|
||||
|
||||
def normalize_describe(tag_name):
|
||||
if not tag_name:
|
||||
return None
|
||||
@@ -3469,6 +3537,22 @@ def get_comfyui_versions(repo=None):
|
||||
repo.close()
|
||||
|
||||
|
||||
def is_comfyui_downgrade(tag):
|
||||
if tag == 'nightly':
|
||||
return False
|
||||
|
||||
with open_repo(context.comfy_path) as repo:
|
||||
described = repo.describe_tags() or ''
|
||||
|
||||
release, _, commits_after_release = described.partition('-')
|
||||
current = parse_semver(release)
|
||||
target = parse_semver(tag)
|
||||
if current is None or target is None:
|
||||
return True
|
||||
|
||||
return target <= current if commits_after_release else target < current
|
||||
|
||||
|
||||
def switch_comfyui(tag):
|
||||
with open_repo(context.comfy_path) as repo:
|
||||
if tag == 'nightly':
|
||||
@@ -3490,23 +3574,35 @@ def resolve_giturl_from_path(fullpath):
|
||||
if not os.path.exists(git_config_path):
|
||||
return "unknown"
|
||||
|
||||
config = configparser.ConfigParser(strict=False)
|
||||
config.read(git_config_path)
|
||||
config = git_utils.read_git_config(git_config_path)
|
||||
if config is None:
|
||||
return None
|
||||
|
||||
for k, v in config.items():
|
||||
if k.startswith('remote ') and 'url' in v:
|
||||
if k.startswith('remote ') and v.get('url'):
|
||||
return v['url'].replace("git@github.com:", "https://github.com/")
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def redo_submodule_update(repo, repo_path):
|
||||
if os.path.exists(os.path.join(repo_path, '.gitmodules')):
|
||||
repo.submodule_update(init=False)
|
||||
|
||||
|
||||
def repo_switch_commit(repo_path, commit_hash):
|
||||
if commit_hash == 'unknown':
|
||||
return False
|
||||
|
||||
try:
|
||||
with open_repo(repo_path) as repo:
|
||||
if repo.head_commit_hexsha == commit_hash:
|
||||
return False
|
||||
if repo.head_commit_hexsha != commit_hash:
|
||||
repo.checkout(commit_hash)
|
||||
repo.submodule_update()
|
||||
return True
|
||||
|
||||
repo.checkout(commit_hash)
|
||||
return True
|
||||
except Exception:
|
||||
redo_submodule_update(repo, repo_path)
|
||||
return False
|
||||
except Exception as e:
|
||||
logging.error(f"[ComfyUI-Manager] Failed to check out '{repo_path}' at {commit_hash}: {e}")
|
||||
return None
|
||||
|
||||
@@ -816,6 +816,11 @@ class TaskQueue:
|
||||
task_queue = TaskQueue()
|
||||
|
||||
|
||||
def replaces_cnr_with_nightly(node_id):
|
||||
unified = core.unified_manager
|
||||
return unified.is_enabled(node_id, 'cnr') and unified.resolve_unspecified_version(node_id, guess_mode='inactive') == 'nightly'
|
||||
|
||||
|
||||
async def task_worker():
|
||||
logging.debug("[ComfyUI-Manager] Task worker started")
|
||||
await core.unified_manager.reload(ManagerDatabaseSource.cache.value)
|
||||
@@ -881,6 +886,9 @@ async def task_worker():
|
||||
async def do_enable(params: EnablePackParams) -> str:
|
||||
cnr_id = params.cnr_id
|
||||
logging.debug("[ComfyUI-Manager] Enabling node: cnr_id=%s", cnr_id)
|
||||
if replaces_cnr_with_nightly(cnr_id) and not security_utils.is_allowed_security_level('middle+'):
|
||||
logging.error(SECURITY_MESSAGE_MIDDLE_P)
|
||||
return OperationResult.failed.value
|
||||
core.unified_manager.unified_enable(cnr_id)
|
||||
return OperationResult.success.value
|
||||
|
||||
@@ -938,6 +946,10 @@ async def task_worker():
|
||||
|
||||
# Check if this is a version switch operation
|
||||
if params.target_version:
|
||||
if core.is_comfyui_downgrade(params.target_version) and not security_utils.is_allowed_security_level('high+'):
|
||||
logging.error(SECURITY_MESSAGE_HIGH_P)
|
||||
return OperationResult.failed.value
|
||||
|
||||
# Switch to specific version
|
||||
logging.info(f"Switching ComfyUI to version: {params.target_version}")
|
||||
core.switch_comfyui(params.target_version)
|
||||
@@ -1256,6 +1268,10 @@ async def queue_task(request) -> web.Response:
|
||||
Returns:
|
||||
web.Response: HTTP 200 on successful queueing, HTTP 400 on validation error
|
||||
"""
|
||||
rejection = security_utils.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
try:
|
||||
json_data = await request.json()
|
||||
# Validate input using Pydantic model
|
||||
@@ -1451,7 +1467,7 @@ async def fetch_updates(request):
|
||||
|
||||
@routes.post("/v2/manager/queue/update_all")
|
||||
async def update_all(request: web.Request) -> web.Response:
|
||||
rejection = security_utils.reject_simple_form_post(request)
|
||||
rejection = security_utils.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
try:
|
||||
@@ -1564,7 +1580,7 @@ async def get_snapshot_list(request):
|
||||
|
||||
@routes.post("/v2/snapshot/remove")
|
||||
async def remove_snapshot(request):
|
||||
rejection = security_utils.reject_simple_form_post(request)
|
||||
rejection = security_utils.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
if not security_utils.is_allowed_security_level("middle"):
|
||||
@@ -1589,11 +1605,11 @@ async def remove_snapshot(request):
|
||||
|
||||
@routes.post("/v2/snapshot/restore")
|
||||
async def restore_snapshot(request):
|
||||
rejection = security_utils.reject_simple_form_post(request)
|
||||
rejection = security_utils.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
if not security_utils.is_allowed_security_level("middle+"):
|
||||
logging.error(SECURITY_MESSAGE_MIDDLE_P)
|
||||
if not security_utils.is_allowed_security_level("high+"):
|
||||
logging.error(SECURITY_MESSAGE_HIGH_P)
|
||||
return web.Response(status=403)
|
||||
|
||||
try:
|
||||
@@ -1634,7 +1650,7 @@ async def get_current_snapshot_api(request):
|
||||
|
||||
@routes.post("/v2/snapshot/save")
|
||||
async def save_snapshot(request):
|
||||
rejection = security_utils.reject_simple_form_post(request)
|
||||
rejection = security_utils.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
try:
|
||||
@@ -1675,6 +1691,10 @@ def unzip_install(files):
|
||||
|
||||
@routes.post("/v2/customnode/import_fail_info")
|
||||
async def import_fail_info(request):
|
||||
rejection = security_utils.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
try:
|
||||
json_data = await request.json()
|
||||
|
||||
@@ -1709,6 +1729,10 @@ async def import_fail_info(request):
|
||||
|
||||
@routes.post("/v2/customnode/import_fail_info_bulk")
|
||||
async def import_fail_info_bulk(request):
|
||||
rejection = security_utils.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
try:
|
||||
json_data = await request.json()
|
||||
|
||||
@@ -1770,7 +1794,7 @@ async def import_fail_info_bulk(request):
|
||||
|
||||
@routes.post("/v2/manager/queue/reset")
|
||||
async def reset_queue(request):
|
||||
rejection = security_utils.reject_simple_form_post(request)
|
||||
rejection = security_utils.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
logging.debug("[ComfyUI-Manager] Queue reset requested")
|
||||
@@ -1833,7 +1857,7 @@ async def queue_count(request):
|
||||
|
||||
@routes.post("/v2/manager/queue/start")
|
||||
async def queue_start(request):
|
||||
rejection = security_utils.reject_simple_form_post(request)
|
||||
rejection = security_utils.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
logging.debug("[ComfyUI-Manager] Queue start requested")
|
||||
@@ -1850,7 +1874,7 @@ async def queue_start(request):
|
||||
@routes.post("/v2/manager/queue/update_comfyui")
|
||||
async def update_comfyui(request):
|
||||
"""Queue a ComfyUI update based on the configured update policy."""
|
||||
rejection = security_utils.reject_simple_form_post(request)
|
||||
rejection = security_utils.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
try:
|
||||
@@ -1860,10 +1884,12 @@ async def update_comfyui(request):
|
||||
)
|
||||
|
||||
# Check if stable parameter was provided, otherwise use config
|
||||
if query_params.stable is None:
|
||||
is_stable = core.get_config()["update_policy"] != "nightly-comfyui"
|
||||
else:
|
||||
if query_params.stable is not None:
|
||||
is_stable = query_params.stable
|
||||
elif query_params.is_stable is not None:
|
||||
is_stable = query_params.is_stable
|
||||
else:
|
||||
is_stable = core.get_config()["update_policy"] not in ("nightly", "nightly-comfyui")
|
||||
|
||||
client_id = query_params.client_id
|
||||
ui_id = query_params.ui_id
|
||||
@@ -1901,10 +1927,10 @@ async def comfyui_versions(request):
|
||||
|
||||
@routes.post("/v2/comfyui_manager/comfyui_switch_version")
|
||||
async def comfyui_switch_version(request):
|
||||
# Body-reading handler — Content-Type gate omitted per
|
||||
# comfyui_manager/common/manager_security.py module policy: a cross-origin
|
||||
# <form method=POST> cannot forge a valid application/json body because
|
||||
# the browser would trigger a CORS preflight that this server refuses.
|
||||
rejection = security_utils.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
if not security_utils.is_allowed_security_level("high+"):
|
||||
logging.error(SECURITY_MESSAGE_HIGH_P)
|
||||
return web.Response(status=403)
|
||||
@@ -1943,6 +1969,10 @@ async def comfyui_switch_version(request):
|
||||
|
||||
@routes.post("/v2/manager/queue/install_model")
|
||||
async def install_model(request):
|
||||
rejection = security_utils.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
try:
|
||||
json_data = await request.json()
|
||||
|
||||
@@ -1980,11 +2010,12 @@ async def db_mode(request):
|
||||
|
||||
@routes.post("/v2/manager/db_mode")
|
||||
async def set_db_mode_api(request):
|
||||
rejection = security_utils.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
# Config writes are at the same risk tier as uninstall/update — apply the
|
||||
# 'middle' gate consistent with snapshot/remove, etc. Content-Type gate is
|
||||
# NOT applied here: this handler consumes application/json and a
|
||||
# cross-origin <form method=POST> cannot forge that without triggering
|
||||
# CORS preflight (see module docstring in common/manager_security.py).
|
||||
# 'middle' gate consistent with snapshot/remove, etc.
|
||||
if not security_utils.is_allowed_security_level("middle"):
|
||||
logging.error(SECURITY_MESSAGE_MIDDLE)
|
||||
return web.Response(status=403)
|
||||
@@ -1993,7 +2024,7 @@ async def set_db_mode_api(request):
|
||||
environment_utils.set_db_mode(data["value"])
|
||||
core.write_config()
|
||||
return web.Response(status=200)
|
||||
except (json.JSONDecodeError, KeyError):
|
||||
except (json.JSONDecodeError, KeyError, TypeError):
|
||||
return web.Response(status=400, text="Invalid request")
|
||||
except ValueError as e:
|
||||
return web.Response(status=400, text=str(e))
|
||||
@@ -2006,7 +2037,10 @@ async def update_policy(request):
|
||||
|
||||
@routes.post("/v2/manager/policy/update")
|
||||
async def set_update_policy_api(request):
|
||||
# See set_db_mode_api above for gate rationale.
|
||||
rejection = security_utils.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
if not security_utils.is_allowed_security_level("middle"):
|
||||
logging.error(SECURITY_MESSAGE_MIDDLE)
|
||||
return web.Response(status=403)
|
||||
@@ -2015,7 +2049,7 @@ async def set_update_policy_api(request):
|
||||
environment_utils.set_update_policy(data["value"])
|
||||
core.write_config()
|
||||
return web.Response(status=200)
|
||||
except (json.JSONDecodeError, KeyError):
|
||||
except (json.JSONDecodeError, KeyError, TypeError):
|
||||
return web.Response(status=400, text="Invalid request")
|
||||
except ValueError as e:
|
||||
return web.Response(status=400, text=str(e))
|
||||
@@ -2038,7 +2072,10 @@ async def channel_url_list(request):
|
||||
|
||||
@routes.post("/v2/manager/channel_url_list")
|
||||
async def set_channel_url(request):
|
||||
# See set_db_mode_api above for gate rationale.
|
||||
rejection = security_utils.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
if not security_utils.is_allowed_security_level("middle"):
|
||||
logging.error(SECURITY_MESSAGE_MIDDLE)
|
||||
return web.Response(status=403)
|
||||
@@ -2063,7 +2100,7 @@ async def set_channel_url(request):
|
||||
|
||||
@routes.post("/v2/manager/reboot")
|
||||
def restart(request):
|
||||
rejection = security_utils.reject_simple_form_post(request)
|
||||
rejection = security_utils.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
if not security_utils.is_allowed_security_level("middle"):
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import mimetypes
|
||||
from ..common import context
|
||||
from ..common import manager_security
|
||||
from . import manager_core as core
|
||||
|
||||
import os
|
||||
@@ -20,17 +21,35 @@ except Exception:
|
||||
matrix_nio_is_available = False
|
||||
|
||||
|
||||
SHARE_OPTIONS = ('all', 'none', 'youml', 'matrix')
|
||||
|
||||
|
||||
@PromptServer.instance.routes.get("/v2/manager/share_option")
|
||||
async def share_option(request):
|
||||
if "value" in request.rel_url.query:
|
||||
core.get_config()['share_option'] = request.rel_url.query['value']
|
||||
core.write_config()
|
||||
else:
|
||||
return web.Response(text=core.get_config()['share_option'], status=200)
|
||||
return web.Response(text=core.get_config()['share_option'], status=200)
|
||||
|
||||
|
||||
@PromptServer.instance.routes.post("/v2/manager/share_option")
|
||||
async def set_share_option(request):
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
try:
|
||||
value = (await request.json())['value']
|
||||
except (json.JSONDecodeError, UnicodeDecodeError, KeyError, TypeError):
|
||||
return web.Response(status=400, text='Invalid request')
|
||||
if value not in SHARE_OPTIONS:
|
||||
return web.Response(status=400, text='Invalid request')
|
||||
core.get_config()['share_option'] = value
|
||||
core.write_config()
|
||||
return web.Response(status=200)
|
||||
|
||||
|
||||
def is_matrix_org(homeserver):
|
||||
return homeserver.replace("http://", "https://").removeprefix("https://") == "matrix.org"
|
||||
|
||||
|
||||
def get_matrix_auth():
|
||||
if not os.path.exists(os.path.join(context.manager_files_path, "matrix_auth")):
|
||||
return None
|
||||
@@ -38,7 +57,7 @@ def get_matrix_auth():
|
||||
with open(os.path.join(context.manager_files_path, "matrix_auth"), "r") as f:
|
||||
matrix_auth = f.read()
|
||||
homeserver, username, password = matrix_auth.strip().split("\n")
|
||||
if not homeserver or not username or not password:
|
||||
if not is_matrix_org(homeserver) or not username or not password:
|
||||
return None
|
||||
return {
|
||||
"homeserver": homeserver,
|
||||
@@ -49,44 +68,12 @@ def get_matrix_auth():
|
||||
return None
|
||||
|
||||
|
||||
def get_youml_settings():
|
||||
if not os.path.exists(os.path.join(context.manager_files_path, ".youml")):
|
||||
return None
|
||||
try:
|
||||
with open(os.path.join(context.manager_files_path, ".youml"), "r") as f:
|
||||
youml_settings = f.read().strip()
|
||||
return youml_settings if youml_settings else None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def set_youml_settings(settings):
|
||||
with open(os.path.join(context.manager_files_path, ".youml"), "w") as f:
|
||||
f.write(settings)
|
||||
|
||||
|
||||
@PromptServer.instance.routes.get("/v2/manager/get_matrix_auth")
|
||||
async def api_get_matrix_auth(request):
|
||||
# print("Getting stored Matrix credentials...")
|
||||
matrix_auth = get_matrix_auth()
|
||||
if not matrix_auth:
|
||||
return web.Response(status=404)
|
||||
return web.json_response(matrix_auth)
|
||||
|
||||
|
||||
@PromptServer.instance.routes.get("/v2/manager/youml/settings")
|
||||
async def api_get_youml_settings(request):
|
||||
youml_settings = get_youml_settings()
|
||||
if not youml_settings:
|
||||
return web.Response(status=404)
|
||||
return web.json_response(json.loads(youml_settings))
|
||||
|
||||
|
||||
@PromptServer.instance.routes.post("/v2/manager/youml/settings")
|
||||
async def api_set_youml_settings(request):
|
||||
json_data = await request.json()
|
||||
set_youml_settings(json.dumps(json_data))
|
||||
return web.Response(status=200)
|
||||
return web.json_response({"homeserver": matrix_auth["homeserver"], "username": matrix_auth["username"]})
|
||||
|
||||
|
||||
@PromptServer.instance.routes.get("/v2/manager/get_matrix_dep_status")
|
||||
@@ -98,11 +85,17 @@ async def get_matrix_dep_status(request):
|
||||
|
||||
|
||||
def set_matrix_auth(json_data):
|
||||
homeserver = json_data['homeserver']
|
||||
username = json_data['username']
|
||||
password = json_data['password']
|
||||
with open(os.path.join(context.manager_files_path, "matrix_auth"), "w") as f:
|
||||
f.write("\n".join([homeserver, username, password]))
|
||||
path = os.path.join(context.manager_files_path, "matrix_auth")
|
||||
# The mode of os.open is for a new file; a file that is there gets the mode before the password is written.
|
||||
with open(os.open(path, os.O_WRONLY | os.O_CREAT, 0o600), "w") as f:
|
||||
try:
|
||||
os.chmod(path, 0o600)
|
||||
except OSError:
|
||||
pass # a file of another owner keeps its mode
|
||||
f.truncate()
|
||||
f.write("\n".join(["matrix.org", username, password]))
|
||||
|
||||
|
||||
def has_provided_matrix_auth(matrix_auth):
|
||||
@@ -112,11 +105,17 @@ def has_provided_matrix_auth(matrix_auth):
|
||||
@PromptServer.instance.routes.post("/v2/manager/share")
|
||||
async def share_art(request):
|
||||
# get json data
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
json_data = await request.json()
|
||||
|
||||
matrix_auth = json_data['matrix_auth']
|
||||
|
||||
set_matrix_auth(matrix_auth)
|
||||
saved = get_matrix_auth()
|
||||
if saved and not matrix_auth['password'] and matrix_auth['username'] == saved['username']:
|
||||
matrix_auth['password'] = saved['password']
|
||||
|
||||
share_destinations = json_data['share_destinations']
|
||||
credits = json_data['credits']
|
||||
@@ -171,14 +170,10 @@ async def share_art(request):
|
||||
content_type = assetFileType
|
||||
|
||||
try:
|
||||
homeserver = 'matrix.org'
|
||||
if matrix_auth:
|
||||
homeserver = matrix_auth.get('homeserver', 'matrix.org')
|
||||
homeserver = homeserver.replace("http://", "https://")
|
||||
if not homeserver.startswith("https://"):
|
||||
homeserver = "https://" + homeserver
|
||||
if not is_matrix_org(matrix_auth.get('homeserver', 'matrix.org')):
|
||||
return web.json_response({"error": "Only an account of matrix.org can share."}, content_type='application/json', status=400)
|
||||
|
||||
client = AsyncClient(homeserver, matrix_auth['username'])
|
||||
client = AsyncClient("https://matrix.org", matrix_auth['username'])
|
||||
|
||||
# Login
|
||||
login_resp = await client.login(matrix_auth['password'])
|
||||
@@ -186,6 +181,8 @@ async def share_art(request):
|
||||
await client.close()
|
||||
return web.json_response({"error": "Invalid Matrix credentials."}, content_type='application/json', status=400)
|
||||
|
||||
set_matrix_auth(matrix_auth)
|
||||
|
||||
# Upload asset
|
||||
with open(asset_filepath, 'rb') as f:
|
||||
upload_resp, _maybe_keys = await client.upload(f, content_type=content_type, filename=filename)
|
||||
|
||||
@@ -5,7 +5,7 @@ from comfyui_manager.common.manager_security import (
|
||||
is_loopback,
|
||||
is_safe_path_target,
|
||||
get_safe_file_path,
|
||||
reject_simple_form_post,
|
||||
reject_non_json_post,
|
||||
)
|
||||
|
||||
# Re-export for backward compatibility
|
||||
@@ -13,7 +13,7 @@ __all__ = [
|
||||
'is_loopback',
|
||||
'is_safe_path_target',
|
||||
'get_safe_file_path',
|
||||
'reject_simple_form_post',
|
||||
'reject_non_json_post',
|
||||
'is_allowed_security_level',
|
||||
'get_risky_level',
|
||||
]
|
||||
|
||||
@@ -134,7 +134,7 @@ async function tryInstallCustomNode(event) {
|
||||
|
||||
let response;
|
||||
try {
|
||||
response = await api.fetchApi("/v2/manager/reboot", { method: 'POST' });
|
||||
response = await api.fetchApi("/v2/manager/reboot", { method: 'POST', headers: { 'Content-Type': 'application/json' } });
|
||||
}
|
||||
catch(exception) {
|
||||
// The server restarts without answering.
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
.cm-ui-overlay {
|
||||
z-index: 1000;
|
||||
background: rgb(0 0 0 / 50%);
|
||||
}
|
||||
|
||||
.cm-ui-dialog {
|
||||
max-width: calc(100vw - 2rem);
|
||||
max-height: calc(100vh - 2rem);
|
||||
border: 1px solid var(--border, var(--border-color));
|
||||
border-radius: 12px;
|
||||
background: var(--background, var(--comfy-menu-bg));
|
||||
color: var(--foreground, var(--fg-color));
|
||||
box-shadow: var(--shadow-lg, 0 8px 24px rgb(0 0 0 / 30%));
|
||||
}
|
||||
|
||||
.cm-ui-header {
|
||||
flex-shrink: 0;
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.cm-ui-content {
|
||||
padding: 0 1rem 1rem;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.cm-ui-muted {
|
||||
color: var(--muted-foreground, var(--fg-color));
|
||||
}
|
||||
|
||||
:where(.cm-ui-button) {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.5rem 0.75rem;
|
||||
border: 1px solid var(--border, var(--border-color));
|
||||
border-radius: 6px;
|
||||
background: var(--secondary, var(--comfy-input-bg));
|
||||
color: var(--foreground, var(--input-text));
|
||||
font: inherit;
|
||||
line-height: 1.25;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
:where(.cm-ui-input) {
|
||||
padding: 0.5rem;
|
||||
border: 1px solid var(--border, var(--border-color));
|
||||
border-radius: 6px;
|
||||
background: var(--secondary, var(--comfy-input-bg));
|
||||
color: var(--foreground, var(--input-text));
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.cm-ui-button:not(:disabled):hover {
|
||||
filter: brightness(115%);
|
||||
}
|
||||
|
||||
.cm-ui-button:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.cm-ui-button:focus-visible,
|
||||
.cm-ui-input:focus-visible {
|
||||
outline: 2px solid var(--ring, var(--input-text));
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.cm-ui-close {
|
||||
width: 2rem;
|
||||
height: 2rem;
|
||||
flex-shrink: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: 50%;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.cm-ui-close:not(:disabled):hover {
|
||||
background: var(--accent, var(--comfy-input-bg));
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
import { $el } from "../../scripts/ui.js";
|
||||
import { loadCss } from "./common.js";
|
||||
|
||||
loadCss("./comfyui-gui-builder.css");
|
||||
|
||||
function normalizeContent(content) {
|
||||
const tmp = document.createElement('div');
|
||||
@@ -16,7 +19,7 @@ export function createSettingsCombo(label, content) {
|
||||
const settingItem = $el("div.setting-item", {}, [
|
||||
$el("div.flex.flex-row.items-center.gap-2",[
|
||||
$el("div.form-label.flex.grow.items-center", [
|
||||
$el("span.text-muted", { textContent: label },)
|
||||
$el("span.cm-ui-muted", { textContent: label },)
|
||||
]),
|
||||
$el("div.form-input.flex.justify-end",
|
||||
[content]
|
||||
@@ -28,51 +31,27 @@ export function createSettingsCombo(label, content) {
|
||||
}
|
||||
|
||||
export function buildGuiFrame(dialogId, title, iconClass, content, owner) {
|
||||
const dialog_mask = $el("div.p-dialog-mask.p-overlay-mask.p-overlay-mask-enter", {
|
||||
const dialog_mask = $el("div.cm-ui-overlay.fixed.inset-0.flex.items-center.justify-center", {
|
||||
parent: document.body,
|
||||
style: {
|
||||
position: "fixed",
|
||||
height: "100%",
|
||||
width: "100%",
|
||||
left: "0px",
|
||||
top: "0px",
|
||||
display: "flex",
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
pointerEvents: "auto",
|
||||
zIndex: "1000"
|
||||
},
|
||||
onclick: (e) => {
|
||||
if (e.target === dialog_mask) {
|
||||
owner.close();
|
||||
}
|
||||
}
|
||||
// data-pc-section="mask"
|
||||
});
|
||||
|
||||
const header_actions = $el("div.p-dialog-header-actions", {
|
||||
// [TODO]
|
||||
// data-pc-section="headeractions"
|
||||
}
|
||||
);
|
||||
const header_actions = $el("div.flex.items-center");
|
||||
|
||||
const close_button = $el("button.p-button.p-component.p-button-icon-only.p-button-secondary.p-button-rounded.p-button-text.p-dialog-close-button", {
|
||||
$el("button.cm-ui-button.cm-ui-close", {
|
||||
parent: header_actions,
|
||||
type: "button",
|
||||
ariaLabel: "Close",
|
||||
onclick: () => owner.close(),
|
||||
// "data-pc-name": "pcclosebutton",
|
||||
// "data-p-disabled": "false",
|
||||
// "data-p-severity": "secondary",
|
||||
// "data-pc-group-section": "headericon",
|
||||
// "data-pc-extend": "button",
|
||||
// "data-pc-section": "root",
|
||||
// [FIXME] Not sure how to do most of the SVG using $el
|
||||
innerHTML: '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg" class="p-icon p-button-icon" aria-hidden="true"><path d="M8.01186 7.00933L12.27 2.75116C12.341 2.68501 12.398 2.60524 12.4375 2.51661C12.4769 2.42798 12.4982 2.3323 12.4999 2.23529C12.5016 2.13827 12.4838 2.0419 12.4474 1.95194C12.4111 1.86197 12.357 1.78024 12.2884 1.71163C12.2198 1.64302 12.138 1.58893 12.0481 1.55259C11.9581 1.51625 11.8617 1.4984 11.7647 1.50011C11.6677 1.50182 11.572 1.52306 11.4834 1.56255C11.3948 1.60204 11.315 1.65898 11.2488 1.72997L6.99067 5.98814L2.7325 1.72997C2.59553 1.60234 2.41437 1.53286 2.22718 1.53616C2.03999 1.53946 1.8614 1.61529 1.72901 1.74767C1.59663 1.88006 1.5208 2.05865 1.5175 2.24584C1.5142 2.43303 1.58368 2.61419 1.71131 2.75116L5.96948 7.00933L1.71131 11.2675C1.576 11.403 1.5 11.5866 1.5 11.7781C1.5 11.9696 1.576 12.1532 1.71131 12.2887C1.84679 12.424 2.03043 12.5 2.2219 12.5C2.41338 12.5 2.59702 12.424 2.7325 12.2887L6.99067 8.03052L11.2488 12.2887C11.3843 12.424 11.568 12.5 11.7594 12.5C11.9509 12.5 12.1346 12.424 12.27 12.2887C12.4053 12.1532 12.4813 11.9696 12.4813 11.7781C12.4813 11.5866 12.4053 11.403 12.27 11.2675L8.01186 7.00933Z" fill="currentColor"></path></svg><span class="p-button-label" data-pc-section="label"> </span><!---->'
|
||||
innerHTML: '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M8.01186 7.00933L12.27 2.75116C12.341 2.68501 12.398 2.60524 12.4375 2.51661C12.4769 2.42798 12.4982 2.3323 12.4999 2.23529C12.5016 2.13827 12.4838 2.0419 12.4474 1.95194C12.4111 1.86197 12.357 1.78024 12.2884 1.71163C12.2198 1.64302 12.138 1.58893 12.0481 1.55259C11.9581 1.51625 11.8617 1.4984 11.7647 1.50011C11.6677 1.50182 11.572 1.52306 11.4834 1.56255C11.3948 1.60204 11.315 1.65898 11.2488 1.72997L6.99067 5.98814L2.7325 1.72997C2.59553 1.60234 2.41437 1.53286 2.22718 1.53616C2.03999 1.53946 1.8614 1.61529 1.72901 1.74767C1.59663 1.88006 1.5208 2.05865 1.5175 2.24584C1.5142 2.43303 1.58368 2.61419 1.71131 2.75116L5.96948 7.00933L1.71131 11.2675C1.576 11.403 1.5 11.5866 1.5 11.7781C1.5 11.9696 1.576 12.1532 1.71131 12.2887C1.84679 12.424 2.03043 12.5 2.2219 12.5C2.41338 12.5 2.59702 12.424 2.7325 12.2887L6.99067 8.03052L11.2488 12.2887C11.3843 12.424 11.568 12.5 11.7594 12.5C11.9509 12.5 12.1346 12.424 12.27 12.2887C12.4053 12.1532 12.4813 11.9696 12.4813 11.7781C12.4813 11.5866 12.4053 11.403 12.27 11.2675L8.01186 7.00933Z" fill="currentColor"></path></svg>'
|
||||
}
|
||||
);
|
||||
|
||||
const dialog_header = $el("div.p-dialog-header",
|
||||
const dialog_header = $el("div.cm-ui-header.flex.items-center.justify-between.gap-2",
|
||||
[
|
||||
$el("div", [
|
||||
$el("div",
|
||||
@@ -96,8 +75,8 @@ export function buildGuiFrame(dialogId, title, iconClass, content, owner) {
|
||||
]
|
||||
);
|
||||
|
||||
const contentFrame = $el("div.p-dialog-content", {}, normalizeContent(content));
|
||||
const manager_dialog = $el("div.p-dialog.p-component.global-dialog", {
|
||||
const contentFrame = $el("div.cm-ui-content.min-h-0", {}, normalizeContent(content));
|
||||
$el("div.cm-ui-dialog.global-dialog.flex.flex-col", {
|
||||
id: dialogId,
|
||||
parent: dialog_mask,
|
||||
style: {
|
||||
@@ -108,76 +87,35 @@ export function buildGuiFrame(dialogId, title, iconClass, content, owner) {
|
||||
},
|
||||
role: 'dialog',
|
||||
ariaModal: 'true',
|
||||
// [TODO]
|
||||
// ariaLabbelledby: 'cm-title',
|
||||
// maximized: 'false',
|
||||
// data-pc-name: 'dialog',
|
||||
// data-pc-section: 'root',
|
||||
// data-pd-focustrap: 'true'
|
||||
},
|
||||
[ dialog_header, contentFrame ]
|
||||
);
|
||||
|
||||
const hidden_accessible = $el("span.p-hidden-accessible.p-hidden-focusable", {
|
||||
parent: manager_dialog,
|
||||
tabindex: "0",
|
||||
role: "presentation",
|
||||
ariaHidden: "true",
|
||||
"data-p-hidden-accessible": "true",
|
||||
"data-p-hidden-focusable": "true",
|
||||
"data-pc-section": "firstfocusableelement"
|
||||
});
|
||||
|
||||
return dialog_mask;
|
||||
}
|
||||
|
||||
export function buildGuiFrameCustomHeader(dialogId, customHeader, content, owner) {
|
||||
const dialog_mask = $el("div.p-dialog-mask.p-overlay-mask.p-overlay-mask-enter", {
|
||||
const dialog_mask = $el("div.cm-ui-overlay.fixed.inset-0.flex.items-center.justify-center", {
|
||||
parent: document.body,
|
||||
style: {
|
||||
position: "fixed",
|
||||
height: "100%",
|
||||
width: "100%",
|
||||
left: "0px",
|
||||
top: "0px",
|
||||
display: "flex",
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
pointerEvents: "auto",
|
||||
zIndex: "1000"
|
||||
},
|
||||
onclick: (e) => {
|
||||
if (e.target === dialog_mask) {
|
||||
owner.close();
|
||||
}
|
||||
}
|
||||
// data-pc-section="mask"
|
||||
});
|
||||
|
||||
const header_actions = $el("div.p-dialog-header-actions", {
|
||||
// [TODO]
|
||||
// data-pc-section="headeractions"
|
||||
}
|
||||
);
|
||||
const header_actions = $el("div.flex.items-center");
|
||||
|
||||
const close_button = $el("button.p-button.p-component.p-button-icon-only.p-button-secondary.p-button-rounded.p-button-text.p-dialog-close-button", {
|
||||
$el("button.cm-ui-button.cm-ui-close", {
|
||||
parent: header_actions,
|
||||
type: "button",
|
||||
ariaLabel: "Close",
|
||||
onclick: () => owner.close(),
|
||||
// "data-pc-name": "pcclosebutton",
|
||||
// "data-p-disabled": "false",
|
||||
// "data-p-severity": "secondary",
|
||||
// "data-pc-group-section": "headericon",
|
||||
// "data-pc-extend": "button",
|
||||
// "data-pc-section": "root",
|
||||
// [FIXME] Not sure how to do most of the SVG using $el
|
||||
innerHTML: '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg" class="p-icon p-button-icon" aria-hidden="true"><path d="M8.01186 7.00933L12.27 2.75116C12.341 2.68501 12.398 2.60524 12.4375 2.51661C12.4769 2.42798 12.4982 2.3323 12.4999 2.23529C12.5016 2.13827 12.4838 2.0419 12.4474 1.95194C12.4111 1.86197 12.357 1.78024 12.2884 1.71163C12.2198 1.64302 12.138 1.58893 12.0481 1.55259C11.9581 1.51625 11.8617 1.4984 11.7647 1.50011C11.6677 1.50182 11.572 1.52306 11.4834 1.56255C11.3948 1.60204 11.315 1.65898 11.2488 1.72997L6.99067 5.98814L2.7325 1.72997C2.59553 1.60234 2.41437 1.53286 2.22718 1.53616C2.03999 1.53946 1.8614 1.61529 1.72901 1.74767C1.59663 1.88006 1.5208 2.05865 1.5175 2.24584C1.5142 2.43303 1.58368 2.61419 1.71131 2.75116L5.96948 7.00933L1.71131 11.2675C1.576 11.403 1.5 11.5866 1.5 11.7781C1.5 11.9696 1.576 12.1532 1.71131 12.2887C1.84679 12.424 2.03043 12.5 2.2219 12.5C2.41338 12.5 2.59702 12.424 2.7325 12.2887L6.99067 8.03052L11.2488 12.2887C11.3843 12.424 11.568 12.5 11.7594 12.5C11.9509 12.5 12.1346 12.424 12.27 12.2887C12.4053 12.1532 12.4813 11.9696 12.4813 11.7781C12.4813 11.5866 12.4053 11.403 12.27 11.2675L8.01186 7.00933Z" fill="currentColor"></path></svg><span class="p-button-label" data-pc-section="label"> </span><!---->'
|
||||
innerHTML: '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M8.01186 7.00933L12.27 2.75116C12.341 2.68501 12.398 2.60524 12.4375 2.51661C12.4769 2.42798 12.4982 2.3323 12.4999 2.23529C12.5016 2.13827 12.4838 2.0419 12.4474 1.95194C12.4111 1.86197 12.357 1.78024 12.2884 1.71163C12.2198 1.64302 12.138 1.58893 12.0481 1.55259C11.9581 1.51625 11.8617 1.4984 11.7647 1.50011C11.6677 1.50182 11.572 1.52306 11.4834 1.56255C11.3948 1.60204 11.315 1.65898 11.2488 1.72997L6.99067 5.98814L2.7325 1.72997C2.59553 1.60234 2.41437 1.53286 2.22718 1.53616C2.03999 1.53946 1.8614 1.61529 1.72901 1.74767C1.59663 1.88006 1.5208 2.05865 1.5175 2.24584C1.5142 2.43303 1.58368 2.61419 1.71131 2.75116L5.96948 7.00933L1.71131 11.2675C1.576 11.403 1.5 11.5866 1.5 11.7781C1.5 11.9696 1.576 12.1532 1.71131 12.2887C1.84679 12.424 2.03043 12.5 2.2219 12.5C2.41338 12.5 2.59702 12.424 2.7325 12.2887L6.99067 8.03052L11.2488 12.2887C11.3843 12.424 11.568 12.5 11.7594 12.5C11.9509 12.5 12.1346 12.424 12.27 12.2887C12.4053 12.1532 12.4813 11.9696 12.4813 11.7781C12.4813 11.5866 12.4053 11.403 12.27 11.2675L8.01186 7.00933Z" fill="currentColor"></path></svg>'
|
||||
}
|
||||
);
|
||||
|
||||
const _customHeader = normalizeContent(customHeader);
|
||||
const dialog_header = $el("div.p-dialog-header",
|
||||
const dialog_header = $el("div.cm-ui-header.flex.items-center.justify-between.gap-2",
|
||||
[
|
||||
$el("div", [
|
||||
$el("div",
|
||||
@@ -191,8 +129,8 @@ export function buildGuiFrameCustomHeader(dialogId, customHeader, content, owner
|
||||
]
|
||||
);
|
||||
|
||||
const contentFrame = $el("div.p-dialog-content", {}, normalizeContent(content));
|
||||
const manager_dialog = $el("div.p-dialog.p-component.global-dialog", {
|
||||
const contentFrame = $el("div.cm-ui-content.min-h-0", {}, normalizeContent(content));
|
||||
$el("div.cm-ui-dialog.global-dialog.flex.flex-col", {
|
||||
id: dialogId,
|
||||
parent: dialog_mask,
|
||||
style: {
|
||||
@@ -203,25 +141,8 @@ export function buildGuiFrameCustomHeader(dialogId, customHeader, content, owner
|
||||
},
|
||||
role: 'dialog',
|
||||
ariaModal: 'true',
|
||||
// [TODO]
|
||||
// ariaLabbelledby: 'cm-title',
|
||||
// maximized: 'false',
|
||||
// data-pc-name: 'dialog',
|
||||
// data-pc-section: 'root',
|
||||
// data-pd-focustrap: 'true'
|
||||
},
|
||||
[ dialog_header, contentFrame ]
|
||||
);
|
||||
|
||||
const hidden_accessible = $el("span.p-hidden-accessible.p-hidden-focusable", {
|
||||
parent: manager_dialog,
|
||||
tabindex: "0",
|
||||
role: "presentation",
|
||||
ariaHidden: "true",
|
||||
"data-p-hidden-accessible": "true",
|
||||
"data-p-hidden-focusable": "true",
|
||||
"data-pc-section": "firstfocusableelement"
|
||||
});
|
||||
|
||||
return dialog_mask;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -232,6 +232,7 @@ var switch_comfyui_button = null;
|
||||
var update_all_button = null;
|
||||
var restart_stop_button = null;
|
||||
var update_policy_combo = null;
|
||||
var update_policy_chosen = false;
|
||||
|
||||
let share_option = 'all';
|
||||
const share_options = [
|
||||
@@ -494,6 +495,7 @@ async function updateComfyUI() {
|
||||
|
||||
const res = await api.fetchApi(`/v2/manager/queue/batch`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(batch)
|
||||
});
|
||||
}
|
||||
@@ -643,15 +645,6 @@ async function switchComfyUI() {
|
||||
}
|
||||
|
||||
showVersionSelectorDialog(versions, obj.current, async (selected_version) => {
|
||||
if(selected_version == 'nightly') {
|
||||
update_policy_combo.value = 'nightly-comfyui';
|
||||
api.fetchApi('/v2/manager/policy/update', { method: 'POST', body: JSON.stringify({value: 'nightly-comfyui'}) });
|
||||
}
|
||||
else {
|
||||
update_policy_combo.value = 'stable-comfyui';
|
||||
api.fetchApi('/v2/manager/policy/update', { method: 'POST', body: JSON.stringify({value: 'stable-comfyui'}) });
|
||||
}
|
||||
|
||||
let response = await api.fetchApi('/v2/comfyui_manager/comfyui_switch_version', {
|
||||
method: 'POST',
|
||||
cache: "no-store",
|
||||
@@ -663,8 +656,16 @@ async function switchComfyUI() {
|
||||
}),
|
||||
});
|
||||
if (response.status == 200) {
|
||||
const update_policy = selected_version == 'nightly' ? 'nightly-comfyui' : 'stable-comfyui';
|
||||
update_policy_chosen = true;
|
||||
update_policy_combo.value = update_policy;
|
||||
api.fetchApi('/v2/manager/policy/update', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({value: update_policy}) });
|
||||
|
||||
infoToast(`ComfyUI version is switched to ${selected_version}`);
|
||||
}
|
||||
else if (response.status == 403) {
|
||||
customAlert('This action is not allowed with this security level configuration.');
|
||||
}
|
||||
else {
|
||||
customAlert('Failed to switch ComfyUI version.');
|
||||
}
|
||||
@@ -813,6 +814,7 @@ async function updateAll(update_comfyui) {
|
||||
|
||||
const res = await api.fetchApi(`/v2/manager/queue/batch`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(batch)
|
||||
});
|
||||
}
|
||||
@@ -829,7 +831,7 @@ function restartOrStop() {
|
||||
rebootAPI();
|
||||
}
|
||||
else {
|
||||
api.fetchApi('/v2/manager/queue/reset', { method: 'POST' });
|
||||
api.fetchApi('/v2/manager/queue/reset', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
|
||||
infoToast('Cancel', 'Remaining tasks will stop after completing the current task.');
|
||||
}
|
||||
}
|
||||
@@ -841,7 +843,7 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
const isElectron = 'electronAPI' in window;
|
||||
|
||||
update_comfyui_button =
|
||||
$el("button.p-button.p-component.cm-button", {
|
||||
$el("button.cm-ui-button.cm-button", {
|
||||
type: "button",
|
||||
textContent: "Update ComfyUI",
|
||||
style: {
|
||||
@@ -852,7 +854,7 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
});
|
||||
|
||||
switch_comfyui_button =
|
||||
$el("button.p-button.p-component.cm-button", {
|
||||
$el("button.cm-ui-button.cm-button", {
|
||||
type: "button",
|
||||
textContent: "Switch ComfyUI",
|
||||
style: {
|
||||
@@ -863,7 +865,7 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
});
|
||||
|
||||
restart_stop_button =
|
||||
$el("button.p-button.p-component.cm-button-red", {
|
||||
$el("button.cm-ui-button.cm-button-red", {
|
||||
type: "button",
|
||||
textContent: "Restart",
|
||||
onclick: () => restartOrStop()
|
||||
@@ -871,7 +873,7 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
|
||||
if(isElectron) {
|
||||
update_all_button =
|
||||
$el("button.p-button.p-component.cm-button", {
|
||||
$el("button.cm-ui-button.cm-button", {
|
||||
type: "button",
|
||||
textContent: "Update All Custom Nodes",
|
||||
onclick:
|
||||
@@ -880,7 +882,7 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
}
|
||||
else {
|
||||
update_all_button =
|
||||
$el("button.p-button.p-component.cm-button", {
|
||||
$el("button.cm-ui-button.cm-button", {
|
||||
type: "button",
|
||||
textContent: "Update All",
|
||||
onclick:
|
||||
@@ -890,7 +892,7 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
|
||||
const res =
|
||||
[
|
||||
$el("button.p-button.p-component.cm-button", {
|
||||
$el("button.cm-ui-button.cm-button", {
|
||||
type: "button",
|
||||
textContent: "Custom Nodes Manager",
|
||||
onclick:
|
||||
@@ -902,7 +904,7 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
}
|
||||
}),
|
||||
|
||||
$el("button.p-button.p-component.cm-button", {
|
||||
$el("button.cm-ui-button.cm-button", {
|
||||
type: "button",
|
||||
textContent: "Install Missing Custom Nodes",
|
||||
onclick:
|
||||
@@ -914,7 +916,7 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
}
|
||||
}),
|
||||
|
||||
$el("button.p-button.p-component.cm-button", {
|
||||
$el("button.cm-ui-button.cm-button", {
|
||||
type: "button",
|
||||
textContent: "Custom Nodes In Workflow",
|
||||
onclick:
|
||||
@@ -927,7 +929,7 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
}),
|
||||
|
||||
$el("div", {}, []),
|
||||
$el("button.p-button.p-component.cm-button", {
|
||||
$el("button.cm-ui-button.cm-button", {
|
||||
type: "button",
|
||||
textContent: "Model Manager",
|
||||
onclick:
|
||||
@@ -939,7 +941,7 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
}
|
||||
}),
|
||||
|
||||
$el("button.p-button.p-component.cm-button", {
|
||||
$el("button.cm-ui-button.cm-button", {
|
||||
type: "button",
|
||||
textContent: "Install via Git URL",
|
||||
onclick: async () => {
|
||||
@@ -973,17 +975,20 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
|
||||
this.datasrc_combo = document.createElement("select");
|
||||
this.datasrc_combo.setAttribute("title", "Configure where to retrieve node/model information. If set to 'local,' the channel is ignored, and if set to 'channel (remote),' it fetches the latest information each time the list is opened.");
|
||||
this.datasrc_combo.className = "cm-menu-combo p-select p-component p-inputwrapper p-inputwrapper-filled ";
|
||||
this.datasrc_combo.className = "cm-menu-combo cm-ui-input ";
|
||||
this.datasrc_combo.appendChild($el('option', { value: 'cache', text: 'Channel (1day cache)' }, []));
|
||||
this.datasrc_combo.appendChild($el('option', { value: 'local', text: 'Local' }, []));
|
||||
this.datasrc_combo.appendChild($el('option', { value: 'remote', text: 'Channel (remote)' }, []));
|
||||
|
||||
// a choice made before the stored value arrives is not to be replaced by it
|
||||
let db_mode_chosen = false;
|
||||
api.fetchApi('/v2/manager/db_mode')
|
||||
.then(response => response.text())
|
||||
.then(data => { this.datasrc_combo.value = data; });
|
||||
.then(data => { if(!db_mode_chosen) this.datasrc_combo.value = data; });
|
||||
|
||||
this.datasrc_combo.addEventListener('change', function (event) {
|
||||
api.fetchApi('/v2/manager/db_mode', { method: 'POST', body: JSON.stringify({value: event.target.value}) });
|
||||
db_mode_chosen = true;
|
||||
api.fetchApi('/v2/manager/db_mode', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({value: event.target.value}) });
|
||||
});
|
||||
|
||||
const dbRetrievalSetttingItem = createSettingsCombo("DB", this.datasrc_combo);
|
||||
@@ -991,7 +996,7 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
// channel
|
||||
let channel_combo = document.createElement("select");
|
||||
channel_combo.setAttribute("title", "Configure the channel for retrieving data from the Custom Node list (including missing nodes) or the Model list.");
|
||||
channel_combo.className = "cm-menu-combo p-select p-component p-inputwrapper p-inputwrapper-filled";
|
||||
channel_combo.className = "cm-menu-combo cm-ui-input";
|
||||
api.fetchApi('/v2/manager/channel_url_list')
|
||||
.then(response => response.json())
|
||||
.then(async data => {
|
||||
@@ -1005,7 +1010,7 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
}
|
||||
|
||||
channel_combo.addEventListener('change', function (event) {
|
||||
api.fetchApi('/v2/manager/channel_url_list', { method: 'POST', body: JSON.stringify({value: event.target.value}) });
|
||||
api.fetchApi('/v2/manager/channel_url_list', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({value: event.target.value}) });
|
||||
});
|
||||
|
||||
channel_combo.value = data.selected;
|
||||
@@ -1021,22 +1026,26 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
// share
|
||||
let share_combo = document.createElement("select");
|
||||
share_combo.setAttribute("title", "Hide the share button in the main menu or set the default action upon clicking it. Additionally, configure the default share site when sharing via the context menu's share button.");
|
||||
share_combo.className = "cm-menu-combo p-select p-component p-inputwrapper p-inputwrapper-filled";
|
||||
share_combo.className = "cm-menu-combo cm-ui-input";
|
||||
for (const option of share_options) {
|
||||
share_combo.appendChild($el('option', { value: option[0], text: `${option[1]}` }, []));
|
||||
}
|
||||
|
||||
let share_option_chosen = false;
|
||||
api.fetchApi('/v2/manager/share_option')
|
||||
.then(response => response.text())
|
||||
.then(data => {
|
||||
share_option = to_share_option(data);
|
||||
share_combo.value = share_option;
|
||||
if(!share_option_chosen) {
|
||||
share_option = to_share_option(data);
|
||||
share_combo.value = share_option;
|
||||
}
|
||||
});
|
||||
|
||||
share_combo.addEventListener('change', function (event) {
|
||||
share_option_chosen = true;
|
||||
const value = event.target.value;
|
||||
share_option = value;
|
||||
api.fetchApi(`/v2/manager/share_option?value=${value}`);
|
||||
api.fetchApi('/v2/manager/share_option', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ value }) });
|
||||
const shareButton = document.getElementById("shareButton");
|
||||
if (value === 'none') {
|
||||
shareButton.style.display = "none";
|
||||
@@ -1050,17 +1059,19 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
update_policy_combo = document.createElement("select");
|
||||
|
||||
update_policy_combo.setAttribute("title", "Sets the policy to be applied when performing an update.");
|
||||
update_policy_combo.className = "cm-menu-combo p-select p-component p-inputwrapper p-inputwrapper-filled";
|
||||
update_policy_combo.className = "cm-menu-combo cm-ui-input";
|
||||
update_policy_combo.appendChild($el('option', { value: 'stable-comfyui', text: 'ComfyUI Stable Version' }, []));
|
||||
update_policy_combo.appendChild($el('option', { value: 'nightly-comfyui', text: 'ComfyUI Nightly Version' }, []));
|
||||
api.fetchApi('/v2/manager/policy/update')
|
||||
.then(response => response.text())
|
||||
.then(data => {
|
||||
update_policy_combo.value = data;
|
||||
if(!update_policy_chosen)
|
||||
update_policy_combo.value = data;
|
||||
});
|
||||
|
||||
update_policy_combo.addEventListener('change', function (event) {
|
||||
api.fetchApi('/v2/manager/policy/update', { method: 'POST', body: JSON.stringify({value: event.target.value}) });
|
||||
update_policy_chosen = true;
|
||||
api.fetchApi('/v2/manager/policy/update', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({value: event.target.value}) });
|
||||
});
|
||||
|
||||
const updateSetttingItem = createSettingsCombo("Update", update_policy_combo);
|
||||
@@ -1076,7 +1087,7 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
//[TODO] replace mt-2 with wrapper div with flex column gap
|
||||
$el("filedset.cm-experimental.mt-auto", {}, [
|
||||
$el("legend.cm-experimental-legend", {}, ["EXPERIMENTAL"]),
|
||||
$el("button.p-button.p-component.cm-button.cm-experimental-button", {
|
||||
$el("button.cm-ui-button.cm-button.cm-experimental-button", {
|
||||
type: "button",
|
||||
textContent: "Snapshot Manager",
|
||||
onclick:
|
||||
@@ -1086,7 +1097,7 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
SnapshotManager.instance.show();
|
||||
}
|
||||
}),
|
||||
$el("button.p-button.p-component.cm-button.cm-experimental-button.mt-2", {
|
||||
$el("button.cm-ui-button.cm-button.cm-experimental-button.mt-2", {
|
||||
type: "button",
|
||||
textContent: "Install PIP packages",
|
||||
onclick:
|
||||
@@ -1104,7 +1115,7 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
|
||||
createControlsRight() {
|
||||
const elts = [
|
||||
$el("button.p-button.p-component.cm-button", {
|
||||
$el("button.cm-ui-button.cm-button", {
|
||||
id: 'cm-manual-button',
|
||||
type: "button",
|
||||
textContent: "Community Manual",
|
||||
@@ -1155,7 +1166,7 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
})
|
||||
]),
|
||||
|
||||
$el("button.p-button.p-component.cm-button", {
|
||||
$el("button.cm-ui-button.cm-button", {
|
||||
id: 'workflowgallery-button',
|
||||
type: "button",
|
||||
style: {
|
||||
@@ -1198,7 +1209,7 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
})
|
||||
]),
|
||||
|
||||
$el("button.p-button.p-component.cm-button", {
|
||||
$el("button.cm-ui-button.cm-button", {
|
||||
id: 'cm-nodeinfo-button',
|
||||
type: "button",
|
||||
textContent: "Nodes Info",
|
||||
|
||||
@@ -380,7 +380,7 @@ export class ShareDialogChooser extends ComfyDialog {
|
||||
}
|
||||
export class ShareDialog extends ComfyDialog {
|
||||
static instance = null;
|
||||
static matrix_auth = { homeserver: "matrix.org", username: "", password: "" };
|
||||
static matrix_auth = { homeserver: "matrix.org", username: "" };
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
@@ -419,9 +419,9 @@ export class ShareDialog extends ComfyDialog {
|
||||
.catch(error => {});
|
||||
} catch (error) {}
|
||||
|
||||
this.matrix_homeserver_input = $el("input", { type: 'text', id: "matrix_homeserver", placeholder: "matrix.org", value: ShareDialog.matrix_auth.homeserver || 'matrix.org' }, []);
|
||||
this.matrix_homeserver_input = $el("input", { type: 'text', id: "matrix_homeserver", value: "matrix.org", readOnly: true, title: "The share room is on matrix.org; only an account of matrix.org can share." }, []);
|
||||
this.matrix_username_input = $el("input", { type: 'text', placeholder: "Username", value: ShareDialog.matrix_auth.username || '' }, []);
|
||||
this.matrix_password_input = $el("input", { type: 'password', placeholder: "Password", value: ShareDialog.matrix_auth.password || '' }, []);
|
||||
this.matrix_password_input = $el("input", { type: 'password', placeholder: "Password" }, []);
|
||||
|
||||
this.credits_input = $el("input", {
|
||||
type: "text",
|
||||
@@ -635,15 +635,14 @@ export class ShareDialog extends ComfyDialog {
|
||||
]);
|
||||
|
||||
// get the user's existing matrix auth
|
||||
ShareDialog.matrix_auth = { homeserver: "matrix.org", username: "", password: "" };
|
||||
ShareDialog.matrix_auth = { homeserver: "matrix.org", username: "" };
|
||||
try {
|
||||
api.fetchApi(`/v2/manager/get_matrix_auth`)
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
ShareDialog.matrix_auth = data;
|
||||
this.matrix_homeserver_input.value = ShareDialog.matrix_auth.homeserver;
|
||||
this.matrix_username_input.value = ShareDialog.matrix_auth.username;
|
||||
this.matrix_password_input.value = ShareDialog.matrix_auth.password;
|
||||
this.matrix_password_input.placeholder = "Saved password (leave empty to use it)";
|
||||
})
|
||||
.catch(error => {
|
||||
// console.log(error);
|
||||
@@ -665,7 +664,8 @@ export class ShareDialog extends ComfyDialog {
|
||||
|
||||
// if destinations includes matrix, make an api call to /manager/check_matrix to ensure that the user has configured their matrix settings
|
||||
if (destinations.includes("matrix")) {
|
||||
let definedMatrixAuth = !!this.matrix_homeserver_input.value && !!this.matrix_username_input.value && !!this.matrix_password_input.value;
|
||||
const usesSavedPassword = this.matrix_username_input.value == ShareDialog.matrix_auth.username;
|
||||
let definedMatrixAuth = !!this.matrix_username_input.value && (!!this.matrix_password_input.value || usesSavedPassword);
|
||||
if (!definedMatrixAuth) {
|
||||
customAlert("Please set your Matrix account details.");
|
||||
return;
|
||||
@@ -735,6 +735,7 @@ export class ShareDialog extends ComfyDialog {
|
||||
|
||||
if (response_json.matrix.success) {
|
||||
this.final_message.innerHTML = "Your art has been shared in the ComfyUI Matrix server's #share channel!";
|
||||
ShareDialog.matrix_auth = { homeserver: this.matrix_homeserver_input.value, username: this.matrix_username_input.value };
|
||||
}
|
||||
|
||||
this.final_message.style.color = "green";
|
||||
|
||||
@@ -176,25 +176,12 @@ export class YouMLShareDialog extends ComfyDialog {
|
||||
this.selectedFile = null;
|
||||
}
|
||||
|
||||
async loadToken() {
|
||||
let key = ""
|
||||
try {
|
||||
const response = await api.fetchApi(`/v2/manager/youml/settings`)
|
||||
const settings = await response.json()
|
||||
return settings.token
|
||||
} catch (error) {
|
||||
}
|
||||
return key || "";
|
||||
loadToken() {
|
||||
return localStorage.getItem("youml_token") || "";
|
||||
}
|
||||
|
||||
async saveToken(value) {
|
||||
await api.fetchApi(`/v2/manager/youml/settings`, {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({
|
||||
token: value
|
||||
})
|
||||
});
|
||||
saveToken(value) {
|
||||
localStorage.setItem("youml_token", value);
|
||||
}
|
||||
|
||||
createLayout() {
|
||||
@@ -342,7 +329,7 @@ export class YouMLShareDialog extends ComfyDialog {
|
||||
|
||||
async handleShareButtonClick() {
|
||||
this.message.textContent = "";
|
||||
await this.saveToken(this.apiTokenInput.value);
|
||||
this.saveToken(this.apiTokenInput.value);
|
||||
try {
|
||||
this.shareButton.disabled = true;
|
||||
this.shareButton.textContent = "Sharing...";
|
||||
@@ -560,8 +547,7 @@ export class YouMLShareDialog extends ComfyDialog {
|
||||
this.message.innerHTML = "";
|
||||
this.message.textContent = "";
|
||||
|
||||
const token = await this.loadToken();
|
||||
this.apiTokenInput.value = token;
|
||||
this.apiTokenInput.value = this.loadToken();
|
||||
this.uploadedImages = [];
|
||||
|
||||
this.element.style.display = "block";
|
||||
|
||||
@@ -172,7 +172,7 @@ export function rebootAPI() {
|
||||
customConfirm("Are you sure you'd like to reboot the server?").then((isConfirmed) => {
|
||||
if (isConfirmed) {
|
||||
try {
|
||||
api.fetchApi("/v2/manager/reboot", { method: 'POST' });
|
||||
api.fetchApi("/v2/manager/reboot", { method: 'POST', headers: { 'Content-Type': 'application/json' } });
|
||||
}
|
||||
catch(exception) {}
|
||||
}
|
||||
@@ -212,7 +212,8 @@ export async function install_pip(packages) {
|
||||
|
||||
const res = await api.fetchApi("/v2/customnode/install/pip", {
|
||||
method: "POST",
|
||||
body: packages,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ packages: packages }),
|
||||
});
|
||||
|
||||
if(res.status == 403) {
|
||||
@@ -247,7 +248,8 @@ export async function install_via_git_url(url, manager_dialog) {
|
||||
|
||||
const res = await api.fetchApi("/v2/customnode/install/git_url", {
|
||||
method: "POST",
|
||||
body: url,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ url: url }),
|
||||
});
|
||||
|
||||
if(res.status == 403) {
|
||||
|
||||
@@ -103,7 +103,7 @@
|
||||
line-height: 28px;
|
||||
|
||||
cursor: pointer;
|
||||
padding: 0.5em 0.5em;
|
||||
padding: 0 0.5em;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 6px;
|
||||
background: var(--comfy-input-bg);
|
||||
@@ -726,4 +726,4 @@
|
||||
|
||||
.cn-manager-light .cn-btn-install {
|
||||
background-color: #333;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,13 +26,13 @@ const pageHtml = `
|
||||
<div class="cn-manager-selection"></div>
|
||||
<div class="cn-manager-message"></div>
|
||||
<div class="cn-manager-footer">
|
||||
<button class="cn-manager-restart p-button p-component">Restart</button>
|
||||
<button class="cn-manager-stop p-button p-component">Stop</button>
|
||||
<button class="cn-manager-restart cm-ui-button">Restart</button>
|
||||
<button class="cn-manager-stop cm-ui-button">Stop</button>
|
||||
<div class="cn-flex-auto"></div>
|
||||
<button class="cn-manager-used-in-workflow p-button p-component">Used In Workflow</button>
|
||||
<button class="cn-manager-check-update p-button p-component">Check Update</button>
|
||||
<button class="cn-manager-check-missing p-button p-component">Check Missing</button>
|
||||
<button class="cn-manager-install-url p-button p-component">Install via Git URL</button>
|
||||
<button class="cn-manager-used-in-workflow cm-ui-button">Used In Workflow</button>
|
||||
<button class="cn-manager-check-update cm-ui-button">Check Update</button>
|
||||
<button class="cn-manager-check-missing cm-ui-button">Check Missing</button>
|
||||
<button class="cn-manager-install-url cm-ui-button">Install via Git URL</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
@@ -85,7 +85,7 @@ export class CustomNodesManager {
|
||||
// $el("select.cn-manager-filter")
|
||||
// ]),
|
||||
createSettingsCombo("Filter", $el("select.cn-manager-filter")),
|
||||
$el("input.cn-manager-keywords.p-inputtext.p-component", { type: "search", placeholder: "Search" }),
|
||||
$el("input.cn-manager-keywords.cm-ui-input", { type: "search", placeholder: "Search" }),
|
||||
$el("div.cn-manager-status"),
|
||||
$el("div.cn-flex-auto"),
|
||||
$el("div.cn-manager-channel")
|
||||
@@ -378,7 +378,7 @@ export class CustomNodesManager {
|
||||
return shown.map(id => {
|
||||
const bt = buttons[id];
|
||||
// `action` is registry-derived and lands in an attribute.
|
||||
return `<button class="cn-btn-${id} p-button p-component" group="${sanitizeHTML(String(action ?? ''))}" mode="${bt.mode}">${bt.label}</button>`;
|
||||
return `<button class="cn-btn-${id} cm-ui-button" group="${sanitizeHTML(String(action ?? ''))}" mode="${bt.mode}">${bt.label}</button>`;
|
||||
}).join("");
|
||||
}
|
||||
|
||||
@@ -465,7 +465,7 @@ export class CustomNodesManager {
|
||||
|
||||
".cn-manager-stop": {
|
||||
click: () => {
|
||||
api.fetchApi('/v2/manager/queue/reset', { method: 'POST' });
|
||||
api.fetchApi('/v2/manager/queue/reset', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
|
||||
infoToast('Cancel', 'Remaining tasks will stop after completing the current task.');
|
||||
}
|
||||
},
|
||||
@@ -1553,6 +1553,7 @@ export class CustomNodesManager {
|
||||
try {
|
||||
const { data, error } = await fetchData(`/v2/manager/queue/batch`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(batch)
|
||||
});
|
||||
if (error) throw error;
|
||||
|
||||
@@ -71,7 +71,7 @@
|
||||
line-height: 28px;
|
||||
|
||||
cursor: pointer;
|
||||
padding: 0.5em 0.5em;
|
||||
padding: 0 0.5em;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 6px;
|
||||
background: var(--comfy-input-bg);
|
||||
@@ -234,4 +234,4 @@
|
||||
|
||||
.cmm-manager-light .cmm-btn-install {
|
||||
background-color: #333;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,8 +26,8 @@ const pageHtml = `
|
||||
<div class="cmm-manager-selection"></div>
|
||||
<div class="cmm-manager-message"></div>
|
||||
<div class="cmm-manager-footer">
|
||||
<button class="cmm-manager-refresh p-button p-component">Refresh</button>
|
||||
<button class="cmm-manager-stop p-button p-component">Stop</button>
|
||||
<button class="cmm-manager-refresh cm-ui-button">Refresh</button>
|
||||
<button class="cmm-manager-stop cm-ui-button">Stop</button>
|
||||
<div class="cmm-flex-auto"></div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -59,7 +59,7 @@ export class ModelManager {
|
||||
createSettingsCombo("Filter", $el("select.cmm-manager-filter")),
|
||||
createSettingsCombo("Type", $el("select.cmm-manager-type")),
|
||||
createSettingsCombo("Base", $el("select.cmm-manager-base")),
|
||||
$el("input.cmm-manager-keywords.p-inputtext.p-component", { type: "search", placeholder: "Search" }),
|
||||
$el("input.cmm-manager-keywords.cm-ui-input", { type: "search", placeholder: "Search" }),
|
||||
$el("div.cmm-manager-status"),
|
||||
$el("div.cmm-flex-auto")
|
||||
]);
|
||||
@@ -173,7 +173,7 @@ export class ModelManager {
|
||||
|
||||
".cmm-manager-stop": {
|
||||
click: () => {
|
||||
api.fetchApi('/v2/manager/queue/reset', { method: 'POST' });
|
||||
api.fetchApi('/v2/manager/queue/reset', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
|
||||
infoToast('Cancel', 'Remaining tasks will stop after completing the current task.');
|
||||
}
|
||||
},
|
||||
@@ -353,7 +353,7 @@ export class ModelManager {
|
||||
if (installed === "True") {
|
||||
return `<div class="cmm-icon-passed">${icons.passed}</div>`;
|
||||
}
|
||||
return `<button class="cmm-btn-install p-button p-component" mode="install">Install</button>`;
|
||||
return `<button class="cmm-btn-install cm-ui-button" mode="install">Install</button>`;
|
||||
}
|
||||
}, {
|
||||
id: 'url',
|
||||
@@ -434,7 +434,7 @@ export class ModelManager {
|
||||
}
|
||||
|
||||
this.selectedModels = selectedList;
|
||||
this.showSelection(`<span>Selected <b>${selectedList.length}</b> models <button class="cmm-btn-install p-button p-component" mode="install">Install</button>`);
|
||||
this.showSelection(`<span>Selected <b>${selectedList.length}</b> models <button class="cmm-btn-install cm-ui-button" mode="install">Install</button>`);
|
||||
}
|
||||
|
||||
focusInstall(item) {
|
||||
@@ -492,6 +492,7 @@ export class ModelManager {
|
||||
try {
|
||||
const { data, error } = await fetchData(`/v2/manager/queue/batch`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(batch)
|
||||
});
|
||||
if (error) throw error;
|
||||
|
||||
@@ -18,7 +18,7 @@ async function restore_snapshot(target) {
|
||||
if(SnapshotManager.instance) {
|
||||
let scheduled = false;
|
||||
try {
|
||||
const response = await api.fetchApi(`/v2/snapshot/restore?target=${target}`, { method: 'POST', cache: "no-store" });
|
||||
const response = await api.fetchApi(`/v2/snapshot/restore?target=${target}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, cache: "no-store" });
|
||||
|
||||
if(response.status == 403) {
|
||||
show_message('This action is not allowed with this security level configuration.');
|
||||
@@ -41,7 +41,7 @@ async function restore_snapshot(target) {
|
||||
finally {
|
||||
await SnapshotManager.instance.invalidateControl();
|
||||
if(scheduled) {
|
||||
SnapshotManager.instance.updateMessage("<BR>To apply the snapshot, please <button id='cm-reboot-button2' class='p-button p-component'>RESTART</button> ComfyUI. And refresh browser.", 'cm-reboot-button2');
|
||||
SnapshotManager.instance.updateMessage("<BR>To apply the snapshot, please <button id='cm-reboot-button2' class='cm-ui-button'>RESTART</button> ComfyUI. And refresh browser.", 'cm-reboot-button2');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -50,7 +50,7 @@ async function restore_snapshot(target) {
|
||||
async function remove_snapshot(target) {
|
||||
if(SnapshotManager.instance) {
|
||||
try {
|
||||
const response = await api.fetchApi(`/v2/snapshot/remove?target=${target}`, { method: 'POST', cache: "no-store" });
|
||||
const response = await api.fetchApi(`/v2/snapshot/remove?target=${target}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, cache: "no-store" });
|
||||
|
||||
if(response.status == 403) {
|
||||
show_message('This action is not allowed with this security level configuration.');
|
||||
@@ -77,7 +77,7 @@ async function remove_snapshot(target) {
|
||||
|
||||
async function save_current_snapshot() {
|
||||
try {
|
||||
const response = await api.fetchApi('/v2/snapshot/save', { method: 'POST', cache: "no-store" });
|
||||
const response = await api.fetchApi('/v2/snapshot/save', { method: 'POST', headers: { 'Content-Type': 'application/json' }, cache: "no-store" });
|
||||
app.ui.dialog.close();
|
||||
return true;
|
||||
}
|
||||
@@ -136,7 +136,7 @@ export class SnapshotManager extends ComfyDialog {
|
||||
|
||||
createControls() {
|
||||
return [
|
||||
$el("button.p-button.p-component", {
|
||||
$el("button.cm-ui-button", {
|
||||
type: "button",
|
||||
textContent: "Close",
|
||||
onclick: () => { this.close(); }
|
||||
@@ -234,7 +234,7 @@ export class SnapshotManager extends ComfyDialog {
|
||||
data_button.className = "data-btns";
|
||||
|
||||
var restoreBtn = document.createElement('button');
|
||||
restoreBtn.className = "snapshot-restore-btn p-button p-component";
|
||||
restoreBtn.className = "snapshot-restore-btn cm-ui-button";
|
||||
restoreBtn.innerHTML = 'Restore';
|
||||
restoreBtn.style.width = "100px";
|
||||
|
||||
@@ -243,7 +243,7 @@ export class SnapshotManager extends ComfyDialog {
|
||||
});
|
||||
|
||||
var removeBtn = document.createElement('button');
|
||||
removeBtn.className = "snapshot-remove-btn p-button p-component";
|
||||
removeBtn.className = "snapshot-remove-btn cm-ui-button";
|
||||
removeBtn.innerHTML = 'Remove';
|
||||
removeBtn.style.width = "100px";
|
||||
|
||||
@@ -293,7 +293,7 @@ export class SnapshotManager extends ComfyDialog {
|
||||
|
||||
async createBottomControls() {
|
||||
var save_button = document.createElement("button");
|
||||
save_button.className = "p-button p-component";
|
||||
save_button.className = "cm-ui-button";
|
||||
save_button.innerHTML = "Save snapshot";
|
||||
save_button.onclick = () => { save_current_snapshot(); }
|
||||
save_button.style.horizontalAlign = "right";
|
||||
|
||||
@@ -27,13 +27,15 @@ from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
|
||||
orig_print = print
|
||||
|
||||
from rich import print
|
||||
import rich
|
||||
from rich.console import Console
|
||||
from rich.markup import escape
|
||||
from packaging import version
|
||||
|
||||
import uuid
|
||||
|
||||
from ..common import cm_global
|
||||
from ..common.config_writer import DirtyTrackingConfig, write_config_merged
|
||||
from ..common.config_writer import DirtyTrackingConfig, with_valid_values, write_config_merged
|
||||
from ..common import cnr_utils
|
||||
from ..common import manager_util
|
||||
from ..common import manager_security
|
||||
@@ -44,6 +46,12 @@ from ..common.enums import NetworkMode, SecurityLevel, DBMode
|
||||
from ..common import context
|
||||
|
||||
|
||||
def print(*objects, sep=" ", end="\n", file=None):
|
||||
# rich's print with its highlighting only, so that a path, a URL or an error text is written as it is
|
||||
console = rich.get_console() if file is None else Console(file=file)
|
||||
console.print(*objects, sep=sep, end=end, markup=False, emoji=False, soft_wrap=True)
|
||||
|
||||
|
||||
try:
|
||||
from importlib.metadata import version as _pkg_version
|
||||
_raw_version = _pkg_version("comfyui-manager")
|
||||
@@ -689,7 +697,7 @@ class UnifiedManager:
|
||||
channel_url = normalize_channel(channel)
|
||||
if channel_url:
|
||||
if mode not in ['remote', 'local', 'cache']:
|
||||
print(f"[bold red]ERROR: Invalid mode is specified `--mode {mode}`[/bold red]", file=sys.stderr)
|
||||
rich.print(f"[bold red]ERROR: Invalid mode is specified `--mode {escape(mode)}`[/bold red]", file=sys.stderr)
|
||||
return {}
|
||||
|
||||
# validate channel - only the channel set by the user is allowed.
|
||||
@@ -780,24 +788,26 @@ class UnifiedManager:
|
||||
for line in lines:
|
||||
package_name = remap_pip_package(line.strip())
|
||||
if package_name and not package_name.startswith('#') and package_name not in self.processed_install:
|
||||
self.processed_install.add(package_name)
|
||||
install_cmd = manager_util.make_pip_cmd(["install", package_name])
|
||||
if package_name.strip() != "" and not package_name.startswith('#'):
|
||||
res = res and try_install_script(url, repo_path, install_cmd, instant_execution=instant_execution)
|
||||
if res:
|
||||
self.processed_install.add(package_name)
|
||||
|
||||
pip_fixer.fix_broken()
|
||||
|
||||
if os.path.exists(install_script_path) and install_script_path not in self.processed_install:
|
||||
self.processed_install.add(install_script_path)
|
||||
print("Install: install script")
|
||||
install_cmd = [sys.executable, "install.py"]
|
||||
return res and try_install_script(url, repo_path, install_cmd, instant_execution=instant_execution)
|
||||
res = res and try_install_script(url, repo_path, install_cmd, instant_execution=instant_execution)
|
||||
if res:
|
||||
self.processed_install.add(install_script_path)
|
||||
|
||||
return res
|
||||
|
||||
def reserve_cnr_switch(self, target, zip_url, from_path, to_path, no_deps, status=''):
|
||||
script_path = os.path.join(context.manager_startup_script_path, "install-scripts.txt")
|
||||
with open(script_path, "a") as file:
|
||||
with open(script_path, "a", encoding="utf-8") as file:
|
||||
obj = [target, "#LAZY-CNR-SWITCH-SCRIPT", zip_url, from_path, to_path, no_deps, get_default_custom_nodes_path(), sys.executable, status]
|
||||
file.write(f"{obj}\n")
|
||||
|
||||
@@ -883,10 +893,11 @@ class UnifiedManager:
|
||||
download_path = os.path.join(get_default_custom_nodes_path(), archive_name)
|
||||
manager_downloader.basic_download_url(node_info.download_url, get_default_custom_nodes_path(), archive_name)
|
||||
|
||||
# 2. extract files into <node_id>
|
||||
install_path = self.active_nodes[node_id][1]
|
||||
extracted = manager_util.extract_package_as_zip(download_path, install_path)
|
||||
os.remove(download_path)
|
||||
try:
|
||||
extracted = manager_util.switch_package_files(download_path, install_path)
|
||||
finally:
|
||||
os.remove(download_path)
|
||||
|
||||
if extracted is None:
|
||||
if len(os.listdir(install_path)) == 0:
|
||||
@@ -894,32 +905,10 @@ class UnifiedManager:
|
||||
|
||||
return result.fail(f'Empty archive file: {node_id}@{version_spec}')
|
||||
|
||||
# 3. calculate garbage files (.tracking - extracted)
|
||||
tracking_info_file = os.path.join(install_path, '.tracking')
|
||||
prev_files = set()
|
||||
with open(tracking_info_file, 'r') as f:
|
||||
for line in f:
|
||||
prev_files.add(line.strip())
|
||||
garbage = prev_files.difference(extracted)
|
||||
garbage = [os.path.join(install_path, x) for x in garbage]
|
||||
|
||||
# 4-1. remove garbage files
|
||||
for x in garbage:
|
||||
if os.path.isfile(x):
|
||||
os.remove(x)
|
||||
|
||||
# 4-2. remove garbage dir if empty
|
||||
for x in garbage:
|
||||
if os.path.isdir(x):
|
||||
if not os.listdir(x):
|
||||
os.rmdir(x)
|
||||
|
||||
# 5. create .tracking file
|
||||
tracking_info_file = os.path.join(install_path, '.tracking')
|
||||
with open(tracking_info_file, "w", encoding='utf-8') as file:
|
||||
file.write('\n'.join(list(extracted)))
|
||||
|
||||
# 6. post install
|
||||
result.target = version_spec
|
||||
|
||||
def postinstall():
|
||||
@@ -1305,6 +1294,9 @@ class UnifiedManager:
|
||||
repo.git.clear_cache()
|
||||
repo.close()
|
||||
|
||||
# an install script that ran in this folder was of the pack that was there before the clone
|
||||
self.processed_install.discard(os.path.join(repo_path, 'install.py'))
|
||||
|
||||
def postinstall():
|
||||
return self.execute_install_script(url, repo_path, instant_execution=instant_execution, no_deps=no_deps)
|
||||
|
||||
@@ -1706,7 +1698,7 @@ def write_config():
|
||||
|
||||
def read_config():
|
||||
try:
|
||||
config = configparser.ConfigParser(strict=False)
|
||||
config = configparser.ConfigParser(strict=False, interpolation=None)
|
||||
config.read(context.manager_config_path)
|
||||
default_conf = config['default']
|
||||
|
||||
@@ -1716,9 +1708,10 @@ def read_config():
|
||||
manager_util.use_uv = default_conf['use_uv'].lower() == 'true' if 'use_uv' in default_conf else False
|
||||
manager_util.bypass_ssl = get_bool('bypass_ssl', False)
|
||||
|
||||
return {
|
||||
return with_valid_values({
|
||||
'http_channel_enabled': get_bool('http_channel_enabled', False),
|
||||
'git_exe': default_conf.get('git_exe', ''),
|
||||
# read as written: a path of Windows may hold a `%`, which the parser takes as the start of a reference
|
||||
'git_exe': default_conf.get('git_exe', '', raw=True),
|
||||
'use_uv': get_bool('use_uv', True),
|
||||
'channel_url': default_conf.get('channel_url', DEFAULT_CHANNEL),
|
||||
'default_cache_as_channel_url': get_bool('default_cache_as_channel_url', False),
|
||||
@@ -1736,9 +1729,12 @@ def read_config():
|
||||
'allow_git_url_install': get_bool('allow_git_url_install', False),
|
||||
'allow_pip_install': get_bool('allow_pip_install', False),
|
||||
'allow_flagged_nodepack_install': get_bool('allow_flagged_nodepack_install', False),
|
||||
}
|
||||
})
|
||||
|
||||
except Exception as e:
|
||||
if os.path.exists(context.manager_config_path):
|
||||
logging.warning(f"[ComfyUI-Manager] '{context.manager_config_path}' could not be read ({e!r}); the default settings are used.")
|
||||
|
||||
except Exception:
|
||||
manager_util.use_uv = False
|
||||
manager_util.bypass_ssl = False
|
||||
|
||||
@@ -1838,7 +1834,7 @@ def reserve_script(repo_path, install_cmds):
|
||||
os.makedirs(context.manager_startup_script_path)
|
||||
|
||||
script_path = os.path.join(context.manager_startup_script_path, "install-scripts.txt")
|
||||
with open(script_path, "a") as file:
|
||||
with open(script_path, "a", encoding="utf-8") as file:
|
||||
obj = [repo_path] + install_cmds
|
||||
file.write(f"{obj}\n")
|
||||
|
||||
@@ -1971,7 +1967,8 @@ def __win_check_git_update(path, do_fetch=False, do_update=False):
|
||||
def __win_check_git_pull(path):
|
||||
command = [sys.executable, context.git_script_path, "--pull", path]
|
||||
process = subprocess.Popen(command, env=get_script_env(), cwd=get_default_custom_nodes_path())
|
||||
process.wait()
|
||||
if process.wait() != 0:
|
||||
raise ValueError(f"Failed to pull: {path}")
|
||||
|
||||
|
||||
def execute_install_script(url, repo_path, lazy_mode=False, instant_execution=False, no_deps=False):
|
||||
@@ -2182,9 +2179,14 @@ class GitProgress(RemoteProgress):
|
||||
|
||||
def is_valid_url(url):
|
||||
# Check for HTTP/HTTPS URL format
|
||||
result = urlparse(url)
|
||||
if result.scheme and result.netloc:
|
||||
return True
|
||||
try:
|
||||
result = urlparse(url)
|
||||
if result.scheme and result.netloc:
|
||||
return True
|
||||
except ValueError:
|
||||
# What cannot be parsed, as a host with a bracket that is not closed,
|
||||
# is not such a URL.
|
||||
pass
|
||||
|
||||
# Check for SSH git URL format
|
||||
if SSH_URL_PATTERN.match(url):
|
||||
@@ -2257,6 +2259,14 @@ async def gitclone_install(url, instant_execution=False, msg_prefix='', no_deps=
|
||||
return result.fail(f"Install(git-clone)[1] error: {url} / {e}")
|
||||
|
||||
|
||||
def undo_pull(repo, commit):
|
||||
repo.git.reset('--hard', commit)
|
||||
try:
|
||||
repo.git.submodule('update', '--recursive')
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def git_pull(path):
|
||||
# Check if the path is a git repository
|
||||
if not os.path.exists(os.path.join(path, '.git')):
|
||||
@@ -2279,6 +2289,7 @@ def git_pull(path):
|
||||
current_branch = repo.active_branch
|
||||
remote_name = current_branch.tracking_branch().remote_name
|
||||
branch_name = current_branch.name
|
||||
commit_hash = repo.head.commit.hexsha
|
||||
|
||||
try:
|
||||
repo.git.pull('--ff-only')
|
||||
@@ -2289,7 +2300,11 @@ def git_pull(path):
|
||||
repo.git.reset('--hard', f'{remote_name}/{branch_name}')
|
||||
logging.info(f"[ComfyUI-Manager] Reset to {remote_name}/{branch_name}")
|
||||
|
||||
repo.git.submodule('update', '--init', '--recursive')
|
||||
try:
|
||||
repo.git.submodule('update', '--init', '--recursive')
|
||||
except Exception:
|
||||
undo_pull(repo, commit_hash)
|
||||
raise
|
||||
|
||||
repo.close()
|
||||
|
||||
@@ -3137,6 +3152,30 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
|
||||
installed_node_packs = []
|
||||
failed = []
|
||||
|
||||
def run_postinstall(res):
|
||||
try:
|
||||
return res.postinstall()
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
def attempt(step, *args):
|
||||
try:
|
||||
return step(*args)
|
||||
except Exception as e:
|
||||
logging.error(f"[ComfyUI-Manager] {e}")
|
||||
return ManagedResult('fail').fail(str(e))
|
||||
|
||||
def finish_clone(res, name, path, commit_hash):
|
||||
is_switched = repo_switch_commit(path, commit_hash)
|
||||
is_installed = run_postinstall(res)
|
||||
if is_switched is None:
|
||||
failed.append(f"{name}@{commit_hash}")
|
||||
elif not is_installed:
|
||||
failed.append(name)
|
||||
else:
|
||||
cloned_repos.append(name)
|
||||
|
||||
await unified_manager.reload('cache')
|
||||
await unified_manager.get_custom_nodes('default', 'cache')
|
||||
|
||||
@@ -3146,8 +3185,6 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
|
||||
|
||||
print("Restore snapshot.")
|
||||
|
||||
postinstalls = []
|
||||
|
||||
with open(snapshot_path, 'r', encoding="UTF-8") as snapshot_file:
|
||||
if snapshot_path.endswith('.json'):
|
||||
info = json.load(snapshot_file)
|
||||
@@ -3182,11 +3219,16 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
|
||||
skip_node_packs.append(k)
|
||||
|
||||
for x in todo_disable:
|
||||
unified_manager.unified_disable(x, False)
|
||||
disabled_repos.append(x)
|
||||
if attempt(unified_manager.unified_disable, x, False).result:
|
||||
disabled_repos.append(x)
|
||||
else:
|
||||
failed.append(x)
|
||||
|
||||
for x in todo_checkout:
|
||||
ps = unified_manager.cnr_switch_version(x[0], x[1], instant_execution=True, no_deps=True, return_postinstall=False)
|
||||
try:
|
||||
ps = unified_manager.cnr_switch_version(x[0], x[1], instant_execution=True, no_deps=True, return_postinstall=False)
|
||||
except Exception as e:
|
||||
ps = ManagedResult('switch-cnr').fail(str(e))
|
||||
if ps.action == 'switch-cnr' and ps.result:
|
||||
switched_node_packs.append(f"{x[0]}@{x[1]}")
|
||||
elif ps.action == 'skip':
|
||||
@@ -3201,18 +3243,17 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
|
||||
if 'comfyui-manager' in k or k in checked_cnr:
|
||||
continue
|
||||
|
||||
ps = await unified_manager.install_by_id(k, version_spec=v, instant_execution=True, return_postinstall=True)
|
||||
if ps.action == 'install-cnr' and ps.result:
|
||||
installed_node_packs.append(f"{k}@{v}")
|
||||
elif not ps.result:
|
||||
try:
|
||||
ps = await unified_manager.install_by_id(k, version_spec=v, instant_execution=True, return_postinstall=True)
|
||||
except Exception as e:
|
||||
ps = ManagedResult('install-cnr').fail(str(e))
|
||||
if not ps.result:
|
||||
failed.append(f"{k}@{v}")
|
||||
logging.error(ps.msg)
|
||||
|
||||
if ps is not None and ps.result:
|
||||
if hasattr(ps, 'postinstall'):
|
||||
postinstalls.append(ps.postinstall)
|
||||
else:
|
||||
print("cm-cli: unexpected [0001]")
|
||||
elif not run_postinstall(ps):
|
||||
failed.append(f"{k}@{v}")
|
||||
elif ps.action == 'install-cnr':
|
||||
installed_node_packs.append(f"{k}@{v}")
|
||||
|
||||
# for nightly restore
|
||||
_git_info = info.get('git_custom_nodes')
|
||||
@@ -3224,6 +3265,8 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
|
||||
if 'comfyui-manager' in k.lower():
|
||||
continue
|
||||
|
||||
v.setdefault('hash', 'unknown')
|
||||
|
||||
# Snapshots saved at a detached HEAD used to keep the newline that follows the hash.
|
||||
if isinstance(v.get('hash'), str):
|
||||
v['hash'] = v['hash'].strip()
|
||||
@@ -3249,7 +3292,8 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
|
||||
todo_disable.append(k)
|
||||
else:
|
||||
commit_hash = git_info[normalized_url]['hash']
|
||||
todo_checkout.append((v[1], commit_hash))
|
||||
todo_checkout.append((k, v[1], commit_hash))
|
||||
processed_urls.append(normalized_url)
|
||||
|
||||
for k, v in unified_manager.nightly_inactive_nodes.items():
|
||||
if 'comfyui-manager' in k:
|
||||
@@ -3265,35 +3309,52 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
|
||||
processed_urls.append(normalized_url)
|
||||
|
||||
for x in todo_disable:
|
||||
unified_manager.unified_disable(x, False)
|
||||
disabled_repos.append(x)
|
||||
if attempt(unified_manager.unified_disable, x, False).result:
|
||||
disabled_repos.append(x)
|
||||
else:
|
||||
failed.append(x)
|
||||
|
||||
for x in todo_enable:
|
||||
res = unified_manager.unified_enable(x[0], 'nightly')
|
||||
res = attempt(unified_manager.unified_enable, x[0], 'nightly')
|
||||
|
||||
is_switched = False
|
||||
if res and res.target:
|
||||
is_switched = repo_switch_commit(res.target, x[1])
|
||||
|
||||
if is_switched:
|
||||
if not res.result:
|
||||
failed.append(x[0])
|
||||
elif is_switched is None:
|
||||
failed.append(f"{x[0]}@{x[1]}")
|
||||
elif is_switched:
|
||||
checkout_repos.append(f"{x[0]}@{x[1]}")
|
||||
else:
|
||||
enabled_repos.append(x[0])
|
||||
|
||||
for x in todo_checkout:
|
||||
is_switched = repo_switch_commit(x[0], x[1])
|
||||
for name, path, commit_hash in todo_checkout:
|
||||
is_switched = repo_switch_commit(path, commit_hash)
|
||||
|
||||
if is_switched:
|
||||
checkout_repos.append(f"{x[0]}@{x[1]}")
|
||||
checkout_repos.append(f"{name}@{commit_hash}")
|
||||
elif is_switched is None:
|
||||
failed.append(f"{name}@{commit_hash}")
|
||||
else:
|
||||
skip_node_packs.append(name)
|
||||
|
||||
for x in git_info.keys():
|
||||
if x in processed_urls:
|
||||
continue
|
||||
|
||||
normalized_url = git_utils.normalize_url(x)
|
||||
cnr = unified_manager.repo_cnr_map.get(normalized_url)
|
||||
if cnr is not None:
|
||||
pack_id = cnr['id']
|
||||
res = await unified_manager.install_by_id(pack_id, 'nightly', instant_execution=True, no_deps=False, return_postinstall=False)
|
||||
try:
|
||||
res = await unified_manager.install_by_id(pack_id, 'nightly', instant_execution=True, no_deps=False, return_postinstall=True)
|
||||
except Exception as e:
|
||||
logging.error(f"[ComfyUI-Manager] {e}")
|
||||
res = ManagedResult('fail').fail(str(e))
|
||||
if res.action == 'install-git' and res.result:
|
||||
cloned_repos.append(pack_id)
|
||||
finish_clone(res, pack_id, unified_manager.active_nodes[pack_id][1], git_info[x]['hash'])
|
||||
elif res.action == 'skip':
|
||||
skip_node_packs.append(pack_id)
|
||||
elif not res.result:
|
||||
@@ -3311,6 +3372,9 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
|
||||
processed_urls = []
|
||||
|
||||
for k2, v2 in unified_manager.unknown_active_nodes.items():
|
||||
if 'comfyui-manager' in k2.lower():
|
||||
continue
|
||||
|
||||
repo_url = resolve_giturl_from_path(v2[1])
|
||||
|
||||
if repo_url is None:
|
||||
@@ -3322,7 +3386,7 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
|
||||
todo_disable.append(k2)
|
||||
else:
|
||||
commit_hash = git_info[normalized_url]['hash']
|
||||
todo_checkout.append((k2, commit_hash))
|
||||
todo_checkout.append((k2, v2[1], commit_hash))
|
||||
processed_urls.append(normalized_url)
|
||||
|
||||
for k2, v2 in unified_manager.unknown_inactive_nodes.items():
|
||||
@@ -3339,28 +3403,36 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
|
||||
processed_urls.append(normalized_url)
|
||||
|
||||
for x in todo_disable:
|
||||
unified_manager.unified_disable(x, True)
|
||||
disabled_repos.append(x)
|
||||
if attempt(unified_manager.unified_disable, x, True).result:
|
||||
disabled_repos.append(x)
|
||||
else:
|
||||
failed.append(x)
|
||||
|
||||
for x in todo_enable:
|
||||
res = unified_manager.unified_enable(x[0], 'unknown')
|
||||
res = attempt(unified_manager.unified_enable, x[0], 'unknown')
|
||||
|
||||
is_switched = False
|
||||
if res and res.target:
|
||||
is_switched = repo_switch_commit(res.target, x[1])
|
||||
|
||||
if is_switched:
|
||||
if not res.result:
|
||||
failed.append(x[0])
|
||||
elif is_switched is None:
|
||||
failed.append(f"{x[0]}@{x[1]}")
|
||||
elif is_switched:
|
||||
checkout_repos.append(f"{x[0]}@{x[1]}")
|
||||
else:
|
||||
enabled_repos.append(x[0])
|
||||
|
||||
for x in todo_checkout:
|
||||
is_switched = repo_switch_commit(x[0], x[1])
|
||||
for name, path, commit_hash in todo_checkout:
|
||||
is_switched = repo_switch_commit(path, commit_hash)
|
||||
|
||||
if is_switched:
|
||||
checkout_repos.append(f"{x[0]}@{x[1]}")
|
||||
checkout_repos.append(f"{name}@{commit_hash}")
|
||||
elif is_switched is None:
|
||||
failed.append(f"{name}@{commit_hash}")
|
||||
else:
|
||||
skip_node_packs.append(x[0])
|
||||
skip_node_packs.append(name)
|
||||
|
||||
for x in processed_urls:
|
||||
if x in git_info:
|
||||
@@ -3372,10 +3444,14 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
|
||||
repo_name = repo_name[:-4]
|
||||
|
||||
to_path = os.path.join(get_default_custom_nodes_path(), repo_name)
|
||||
unified_manager.repo_install(repo_url, to_path, instant_execution=True, no_deps=False, return_postinstall=False)
|
||||
cloned_repos.append(repo_name)
|
||||
res = unified_manager.repo_install(repo_url, to_path, instant_execution=True, no_deps=False, return_postinstall=True)
|
||||
if not res.result:
|
||||
failed.append(repo_name)
|
||||
continue
|
||||
|
||||
manager_util.restore_pip_snapshot(pips, git_helper_extras)
|
||||
finish_clone(res, repo_name, to_path, git_info[repo_url]['hash'])
|
||||
|
||||
pips_not_installed = manager_util.restore_pip_snapshot(pips, git_helper_extras)
|
||||
|
||||
# print summary
|
||||
for x in cloned_repos:
|
||||
@@ -3392,11 +3468,10 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
|
||||
print(f"[ DISABLED ] {x}")
|
||||
for x in skip_node_packs:
|
||||
print(f"[ SKIPPED ] {x}")
|
||||
for x in failed:
|
||||
for x in dict.fromkeys(failed):
|
||||
print(f"[ FAILED ] {x}")
|
||||
|
||||
# if is_failed:
|
||||
# print("[bold red]ERROR: Failed to restore snapshot.[/bold red]")
|
||||
return not failed and not pips_not_installed
|
||||
|
||||
|
||||
def get_comfyui_versions(repo=None):
|
||||
@@ -3506,23 +3581,35 @@ def resolve_giturl_from_path(fullpath):
|
||||
if not os.path.exists(git_config_path):
|
||||
return "unknown"
|
||||
|
||||
config = configparser.ConfigParser(strict=False)
|
||||
config.read(git_config_path)
|
||||
config = git_utils.read_git_config(git_config_path)
|
||||
if config is None:
|
||||
return None
|
||||
|
||||
for k, v in config.items():
|
||||
if k.startswith('remote ') and 'url' in v:
|
||||
if k.startswith('remote ') and v.get('url'):
|
||||
return v['url'].replace("git@github.com:", "https://github.com/")
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def redo_submodule_update(repo, repo_path):
|
||||
if os.path.exists(os.path.join(repo_path, '.gitmodules')):
|
||||
repo.git.submodule('update', '--recursive')
|
||||
|
||||
|
||||
def repo_switch_commit(repo_path, commit_hash):
|
||||
if commit_hash == 'unknown':
|
||||
return False
|
||||
|
||||
try:
|
||||
repo = git.Repo(repo_path)
|
||||
if repo.head.commit.hexsha == commit_hash:
|
||||
return False
|
||||
if repo.head.commit.hexsha != commit_hash:
|
||||
repo.git.checkout(commit_hash)
|
||||
repo.git.submodule('update', '--init', '--recursive')
|
||||
return True
|
||||
|
||||
repo.git.checkout(commit_hash)
|
||||
return True
|
||||
except Exception:
|
||||
redo_submodule_update(repo, repo_path)
|
||||
return False
|
||||
except Exception as e:
|
||||
logging.error(f"[ComfyUI-Manager] Failed to check out '{repo_path}' at {commit_hash}: {e}")
|
||||
return None
|
||||
|
||||
@@ -25,6 +25,7 @@ from ..common import cm_global
|
||||
from ..common import manager_downloader
|
||||
from ..common import context
|
||||
from ..common import manager_security
|
||||
from ..common.git_compat import setup_git_environment
|
||||
|
||||
|
||||
logging.info(f"### Loading: ComfyUI-Manager ({core.version_str})")
|
||||
@@ -199,10 +200,18 @@ local_db_custom_node_list = os.path.join(manager_util.comfyui_manager_path, "cus
|
||||
local_db_extension_node_mappings = os.path.join(manager_util.comfyui_manager_path, "extension-node-map.json")
|
||||
|
||||
|
||||
ALLOWED_UPDATE_POLICIES = ('stable', 'stable-comfyui', 'nightly', 'nightly-comfyui')
|
||||
ALLOWED_DB_MODES = ('cache', 'channel', 'local', 'remote')
|
||||
|
||||
|
||||
def set_update_policy(mode):
|
||||
if mode not in ALLOWED_UPDATE_POLICIES:
|
||||
raise ValueError(f"Invalid update_policy {mode!r}; must be one of {ALLOWED_UPDATE_POLICIES}")
|
||||
core.get_config()['update_policy'] = mode
|
||||
|
||||
def set_db_mode(mode):
|
||||
if mode not in ALLOWED_DB_MODES:
|
||||
raise ValueError(f"Invalid db_mode {mode!r}; must be one of {ALLOWED_DB_MODES}")
|
||||
core.get_config()['db_mode'] = mode
|
||||
|
||||
def print_comfyui_version():
|
||||
@@ -270,7 +279,7 @@ def setup_environment():
|
||||
git_exe = core.get_config()['git_exe']
|
||||
|
||||
if git_exe != '':
|
||||
git.Git().update_environment(GIT_PYTHON_GIT_EXECUTABLE=git_exe)
|
||||
setup_git_environment(git_exe)
|
||||
|
||||
|
||||
setup_environment()
|
||||
@@ -467,6 +476,11 @@ def finalize_temp_queue_batch(batch_json=None, failed=None):
|
||||
temp_queue_batch = []
|
||||
|
||||
|
||||
def replaces_cnr_with_nightly(node_id):
|
||||
unified = core.unified_manager
|
||||
return unified.is_enabled(node_id, 'cnr') and unified.resolve_unspecified_version(node_id, guess_mode='inactive') == 'nightly'
|
||||
|
||||
|
||||
async def task_worker():
|
||||
global task_queue
|
||||
global tasks_in_progress
|
||||
@@ -508,6 +522,9 @@ async def task_worker():
|
||||
|
||||
async def do_enable(item) -> str:
|
||||
ui_id, cnr_id = item
|
||||
if replaces_cnr_with_nightly(cnr_id) and not is_allowed_security_level('middle+'):
|
||||
logging.error(SECURITY_MESSAGE_MIDDLE_P)
|
||||
return 'failed'
|
||||
core.unified_manager.unified_enable(cnr_id)
|
||||
return 'success'
|
||||
|
||||
@@ -775,6 +792,10 @@ async def task_worker():
|
||||
|
||||
@routes.post("/v2/manager/queue/batch")
|
||||
async def queue_batch(request):
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
json_data = await request.json()
|
||||
|
||||
failed = set()
|
||||
@@ -802,7 +823,8 @@ async def queue_batch(request):
|
||||
failed.add(x['id'])
|
||||
|
||||
elif k == 'update_comfyui':
|
||||
await update_comfyui(None)
|
||||
if v:
|
||||
_update_comfyui()
|
||||
|
||||
elif k == 'disable':
|
||||
for x in v:
|
||||
@@ -929,7 +951,7 @@ async def fetch_updates(request):
|
||||
|
||||
@routes.post("/v2/manager/queue/update_all")
|
||||
async def update_all(request):
|
||||
rejection = manager_security.reject_simple_form_post(request)
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
json_data = dict(request.rel_url.query)
|
||||
@@ -1214,7 +1236,7 @@ async def get_snapshot_list(request):
|
||||
|
||||
@routes.post("/v2/snapshot/remove")
|
||||
async def remove_snapshot(request):
|
||||
rejection = manager_security.reject_simple_form_post(request)
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
if not is_allowed_security_level('middle'):
|
||||
@@ -1240,11 +1262,11 @@ async def remove_snapshot(request):
|
||||
|
||||
@routes.post("/v2/snapshot/restore")
|
||||
async def restore_snapshot(request):
|
||||
rejection = manager_security.reject_simple_form_post(request)
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
if not is_allowed_security_level('middle+'):
|
||||
logging.error(SECURITY_MESSAGE_MIDDLE_P)
|
||||
if not is_allowed_security_level('high+'):
|
||||
logging.error(SECURITY_MESSAGE_HIGH_P)
|
||||
return web.Response(status=403)
|
||||
|
||||
try:
|
||||
@@ -1282,7 +1304,7 @@ async def get_current_snapshot_api(request):
|
||||
|
||||
@routes.post("/v2/snapshot/save")
|
||||
async def save_snapshot(request):
|
||||
rejection = manager_security.reject_simple_form_post(request)
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
try:
|
||||
@@ -1313,7 +1335,7 @@ def unzip_install(files):
|
||||
|
||||
os.remove(temp_filename)
|
||||
except Exception as e:
|
||||
logging.error(f"Install(unzip) error: {url} / {e}", file=sys.stderr)
|
||||
logging.error(f"Install(unzip) error: {url} / {e}")
|
||||
return False
|
||||
|
||||
logging.info("Installation was successful.")
|
||||
@@ -1349,6 +1371,10 @@ async def get_disabled_versions(request):
|
||||
|
||||
@routes.post("/v2/customnode/import_fail_info")
|
||||
async def import_fail_info(request):
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
json_data = await request.json()
|
||||
|
||||
if 'cnr_id' in json_data:
|
||||
@@ -1366,6 +1392,10 @@ async def import_fail_info(request):
|
||||
|
||||
@routes.post("/v2/customnode/import_fail_info_bulk")
|
||||
async def import_fail_info_bulk(request):
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
try:
|
||||
json_data = await request.json()
|
||||
|
||||
@@ -1425,7 +1455,7 @@ async def import_fail_info_bulk(request):
|
||||
|
||||
@routes.post("/v2/manager/queue/reset")
|
||||
async def reset_queue(request):
|
||||
rejection = manager_security.reject_simple_form_post(request)
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
global task_batch_queue
|
||||
@@ -1536,7 +1566,7 @@ task_worker_thread:threading.Thread = None
|
||||
|
||||
@routes.post("/v2/manager/queue/start")
|
||||
async def queue_start(request):
|
||||
rejection = manager_security.reject_simple_form_post(request)
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
with task_worker_lock:
|
||||
@@ -1576,6 +1606,10 @@ async def _fix_custom_node(json_data):
|
||||
|
||||
@routes.post("/v2/customnode/install/git_url")
|
||||
async def install_custom_node_git_url(request):
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
# goal265 S-A: dedicated-flag gate, decoupled from security_level (spec §1.2).
|
||||
if not _dedicated_install_allowed('allow_git_url_install'):
|
||||
logging.error(SECURITY_MESSAGE_FLAG_GIT_URL.format(
|
||||
@@ -1583,7 +1617,13 @@ async def install_custom_node_git_url(request):
|
||||
# Only the flag name goes on the wire; the full message is logged above.
|
||||
return web.json_response({'reason': 'allow_git_url_install'}, status=403)
|
||||
|
||||
url = await request.text()
|
||||
try:
|
||||
json_data = await request.json()
|
||||
url = json_data['url']
|
||||
except (KeyError, TypeError, ValueError):
|
||||
url = None
|
||||
if not isinstance(url, str):
|
||||
return web.Response(status=400, text="Invalid request body: expected JSON object with a 'url' field")
|
||||
res = await core.gitclone_install(url)
|
||||
|
||||
if res.action == 'skip':
|
||||
@@ -1599,6 +1639,10 @@ async def install_custom_node_git_url(request):
|
||||
|
||||
@routes.post("/v2/customnode/install/pip")
|
||||
async def install_custom_node_pip(request):
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
# goal265 S-B: dedicated-flag gate, decoupled from security_level (spec §1.2).
|
||||
if not _dedicated_install_allowed('allow_pip_install'):
|
||||
logging.error(SECURITY_MESSAGE_FLAG_PIP.format(
|
||||
@@ -1606,7 +1650,13 @@ async def install_custom_node_pip(request):
|
||||
# Only the flag name goes on the wire; the full message is logged above.
|
||||
return web.json_response({'reason': 'allow_pip_install'}, status=403)
|
||||
|
||||
packages = await request.text()
|
||||
try:
|
||||
json_data = await request.json()
|
||||
packages = json_data['packages']
|
||||
except (KeyError, TypeError, ValueError):
|
||||
packages = None
|
||||
if not isinstance(packages, str):
|
||||
return web.Response(status=400, text="Invalid request body: expected JSON object with a 'packages' field")
|
||||
core.pip_install(packages.split(' '))
|
||||
|
||||
return web.Response(status=200)
|
||||
@@ -1652,31 +1702,35 @@ async def _update_custom_node(json_data):
|
||||
|
||||
@routes.post("/v2/manager/queue/update_comfyui")
|
||||
async def update_comfyui(request):
|
||||
rejection = manager_security.reject_simple_form_post(request)
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
is_stable = core.get_config()['update_policy'] != 'nightly-comfyui'
|
||||
temp_queue_batch.append(("update-comfyui", ('comfyui', is_stable)))
|
||||
_update_comfyui()
|
||||
return web.Response(status=200)
|
||||
|
||||
|
||||
def _update_comfyui():
|
||||
is_stable = core.get_config()['update_policy'] not in ('nightly', 'nightly-comfyui')
|
||||
temp_queue_batch.append(("update-comfyui", ('comfyui', is_stable)))
|
||||
|
||||
|
||||
@routes.get("/v2/comfyui_manager/comfyui_versions")
|
||||
async def comfyui_versions(request):
|
||||
try:
|
||||
res, current, latest = core.get_comfyui_versions()
|
||||
return web.json_response({'versions': res, 'current': current}, status=200, content_type='application/json')
|
||||
except Exception as e:
|
||||
logging.error(f"ComfyUI update fail: {e}", file=sys.stderr)
|
||||
logging.error(f"ComfyUI update fail: {e}")
|
||||
|
||||
return web.Response(status=400)
|
||||
|
||||
|
||||
@routes.post("/v2/comfyui_manager/comfyui_switch_version")
|
||||
async def comfyui_switch_version(request):
|
||||
# Body-reading handler — Content-Type gate omitted per
|
||||
# comfyui_manager/common/manager_security.py module policy: a cross-origin
|
||||
# <form method=POST> cannot forge a valid application/json body because
|
||||
# the browser would trigger a CORS preflight that this server refuses.
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
if not is_allowed_security_level('high+'):
|
||||
logging.error(SECURITY_MESSAGE_HIGH_P)
|
||||
return web.Response(status=403)
|
||||
@@ -1691,7 +1745,7 @@ async def comfyui_switch_version(request):
|
||||
except json.JSONDecodeError:
|
||||
return web.Response(status=400, text="Invalid JSON body")
|
||||
except Exception as e:
|
||||
logging.error(f"ComfyUI update fail: {e}", file=sys.stderr)
|
||||
logging.error(f"ComfyUI update fail: {e}")
|
||||
return web.Response(status=400)
|
||||
|
||||
|
||||
@@ -1727,6 +1781,10 @@ async def check_whitelist_for_model(item):
|
||||
|
||||
@routes.post("/v2/manager/queue/install_model")
|
||||
async def install_model(request):
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
json_data = await request.json()
|
||||
return await _install_model(json_data)
|
||||
|
||||
@@ -1767,11 +1825,12 @@ async def db_mode(request):
|
||||
|
||||
@routes.post("/v2/manager/db_mode")
|
||||
async def set_db_mode_api(request):
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
# Config writes are at the same risk tier as uninstall/update — apply the
|
||||
# 'middle' gate consistent with snapshot/remove, etc. Content-Type gate is
|
||||
# NOT applied here: this handler consumes application/json and a
|
||||
# cross-origin <form method=POST> cannot forge that without triggering
|
||||
# CORS preflight (see module docstring in common/manager_security.py).
|
||||
# 'middle' gate consistent with snapshot/remove, etc.
|
||||
if not is_allowed_security_level('middle'):
|
||||
logging.error(SECURITY_MESSAGE_MIDDLE)
|
||||
return web.Response(status=403)
|
||||
@@ -1780,8 +1839,10 @@ async def set_db_mode_api(request):
|
||||
set_db_mode(data['value'])
|
||||
core.write_config()
|
||||
return web.Response(status=200)
|
||||
except (json.JSONDecodeError, KeyError):
|
||||
except (json.JSONDecodeError, KeyError, TypeError):
|
||||
return web.Response(status=400, text='Invalid request')
|
||||
except ValueError as e:
|
||||
return web.Response(status=400, text=str(e))
|
||||
|
||||
|
||||
@routes.get("/v2/manager/policy/update")
|
||||
@@ -1791,7 +1852,10 @@ async def update_policy(request):
|
||||
|
||||
@routes.post("/v2/manager/policy/update")
|
||||
async def set_update_policy_api(request):
|
||||
# See set_db_mode_api above for gate rationale.
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
if not is_allowed_security_level('middle'):
|
||||
logging.error(SECURITY_MESSAGE_MIDDLE)
|
||||
return web.Response(status=403)
|
||||
@@ -1800,8 +1864,10 @@ async def set_update_policy_api(request):
|
||||
set_update_policy(data['value'])
|
||||
core.write_config()
|
||||
return web.Response(status=200)
|
||||
except (json.JSONDecodeError, KeyError):
|
||||
except (json.JSONDecodeError, KeyError, TypeError):
|
||||
return web.Response(status=400, text='Invalid request')
|
||||
except ValueError as e:
|
||||
return web.Response(status=400, text=str(e))
|
||||
|
||||
|
||||
@routes.get("/v2/manager/channel_url_list")
|
||||
@@ -1822,7 +1888,10 @@ async def channel_url_list(request):
|
||||
|
||||
@routes.post("/v2/manager/channel_url_list")
|
||||
async def set_channel_url(request):
|
||||
# See set_db_mode_api above for gate rationale.
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
if not is_allowed_security_level('middle'):
|
||||
logging.error(SECURITY_MESSAGE_MIDDLE)
|
||||
return web.Response(status=403)
|
||||
@@ -1901,7 +1970,7 @@ async def get_notice(request):
|
||||
|
||||
@routes.post("/v2/manager/reboot")
|
||||
def restart(request):
|
||||
rejection = manager_security.reject_simple_form_post(request)
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
if not is_allowed_security_level('middle'):
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import mimetypes
|
||||
from ..common import context
|
||||
from ..common import manager_security
|
||||
from . import manager_core as core
|
||||
|
||||
import os
|
||||
@@ -20,17 +21,35 @@ except Exception:
|
||||
matrix_nio_is_available = False
|
||||
|
||||
|
||||
SHARE_OPTIONS = ('all', 'none', 'youml', 'matrix')
|
||||
|
||||
|
||||
@PromptServer.instance.routes.get("/v2/manager/share_option")
|
||||
async def share_option(request):
|
||||
if "value" in request.rel_url.query:
|
||||
core.get_config()['share_option'] = request.rel_url.query['value']
|
||||
core.write_config()
|
||||
else:
|
||||
return web.Response(text=core.get_config()['share_option'], status=200)
|
||||
return web.Response(text=core.get_config()['share_option'], status=200)
|
||||
|
||||
|
||||
@PromptServer.instance.routes.post("/v2/manager/share_option")
|
||||
async def set_share_option(request):
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
try:
|
||||
value = (await request.json())['value']
|
||||
except (json.JSONDecodeError, UnicodeDecodeError, KeyError, TypeError):
|
||||
return web.Response(status=400, text='Invalid request')
|
||||
if value not in SHARE_OPTIONS:
|
||||
return web.Response(status=400, text='Invalid request')
|
||||
core.get_config()['share_option'] = value
|
||||
core.write_config()
|
||||
return web.Response(status=200)
|
||||
|
||||
|
||||
def is_matrix_org(homeserver):
|
||||
return homeserver.replace("http://", "https://").removeprefix("https://") == "matrix.org"
|
||||
|
||||
|
||||
def get_matrix_auth():
|
||||
if not os.path.exists(os.path.join(context.manager_files_path, "matrix_auth")):
|
||||
return None
|
||||
@@ -38,7 +57,7 @@ def get_matrix_auth():
|
||||
with open(os.path.join(context.manager_files_path, "matrix_auth"), "r") as f:
|
||||
matrix_auth = f.read()
|
||||
homeserver, username, password = matrix_auth.strip().split("\n")
|
||||
if not homeserver or not username or not password:
|
||||
if not is_matrix_org(homeserver) or not username or not password:
|
||||
return None
|
||||
return {
|
||||
"homeserver": homeserver,
|
||||
@@ -49,44 +68,12 @@ def get_matrix_auth():
|
||||
return None
|
||||
|
||||
|
||||
def get_youml_settings():
|
||||
if not os.path.exists(os.path.join(context.manager_files_path, ".youml")):
|
||||
return None
|
||||
try:
|
||||
with open(os.path.join(context.manager_files_path, ".youml"), "r") as f:
|
||||
youml_settings = f.read().strip()
|
||||
return youml_settings if youml_settings else None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def set_youml_settings(settings):
|
||||
with open(os.path.join(context.manager_files_path, ".youml"), "w") as f:
|
||||
f.write(settings)
|
||||
|
||||
|
||||
@PromptServer.instance.routes.get("/v2/manager/get_matrix_auth")
|
||||
async def api_get_matrix_auth(request):
|
||||
# print("Getting stored Matrix credentials...")
|
||||
matrix_auth = get_matrix_auth()
|
||||
if not matrix_auth:
|
||||
return web.Response(status=404)
|
||||
return web.json_response(matrix_auth)
|
||||
|
||||
|
||||
@PromptServer.instance.routes.get("/v2/manager/youml/settings")
|
||||
async def api_get_youml_settings(request):
|
||||
youml_settings = get_youml_settings()
|
||||
if not youml_settings:
|
||||
return web.Response(status=404)
|
||||
return web.json_response(json.loads(youml_settings))
|
||||
|
||||
|
||||
@PromptServer.instance.routes.post("/v2/manager/youml/settings")
|
||||
async def api_set_youml_settings(request):
|
||||
json_data = await request.json()
|
||||
set_youml_settings(json.dumps(json_data))
|
||||
return web.Response(status=200)
|
||||
return web.json_response({"homeserver": matrix_auth["homeserver"], "username": matrix_auth["username"]})
|
||||
|
||||
|
||||
@PromptServer.instance.routes.get("/v2/manager/get_matrix_dep_status")
|
||||
@@ -98,11 +85,17 @@ async def get_matrix_dep_status(request):
|
||||
|
||||
|
||||
def set_matrix_auth(json_data):
|
||||
homeserver = json_data['homeserver']
|
||||
username = json_data['username']
|
||||
password = json_data['password']
|
||||
with open(os.path.join(context.manager_files_path, "matrix_auth"), "w") as f:
|
||||
f.write("\n".join([homeserver, username, password]))
|
||||
path = os.path.join(context.manager_files_path, "matrix_auth")
|
||||
# The mode of os.open is for a new file; a file that is there gets the mode before the password is written.
|
||||
with open(os.open(path, os.O_WRONLY | os.O_CREAT, 0o600), "w") as f:
|
||||
try:
|
||||
os.chmod(path, 0o600)
|
||||
except OSError:
|
||||
pass # a file of another owner keeps its mode
|
||||
f.truncate()
|
||||
f.write("\n".join(["matrix.org", username, password]))
|
||||
|
||||
|
||||
def has_provided_matrix_auth(matrix_auth):
|
||||
@@ -112,11 +105,17 @@ def has_provided_matrix_auth(matrix_auth):
|
||||
@PromptServer.instance.routes.post("/v2/manager/share")
|
||||
async def share_art(request):
|
||||
# get json data
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
json_data = await request.json()
|
||||
|
||||
matrix_auth = json_data['matrix_auth']
|
||||
|
||||
set_matrix_auth(matrix_auth)
|
||||
saved = get_matrix_auth()
|
||||
if saved and not matrix_auth['password'] and matrix_auth['username'] == saved['username']:
|
||||
matrix_auth['password'] = saved['password']
|
||||
|
||||
share_destinations = json_data['share_destinations']
|
||||
credits = json_data['credits']
|
||||
@@ -171,14 +170,10 @@ async def share_art(request):
|
||||
content_type = assetFileType
|
||||
|
||||
try:
|
||||
homeserver = 'matrix.org'
|
||||
if matrix_auth:
|
||||
homeserver = matrix_auth.get('homeserver', 'matrix.org')
|
||||
homeserver = homeserver.replace("http://", "https://")
|
||||
if not homeserver.startswith("https://"):
|
||||
homeserver = "https://" + homeserver
|
||||
if not is_matrix_org(matrix_auth.get('homeserver', 'matrix.org')):
|
||||
return web.json_response({"error": "Only an account of matrix.org can share."}, content_type='application/json', status=400)
|
||||
|
||||
client = AsyncClient(homeserver, matrix_auth['username'])
|
||||
client = AsyncClient("https://matrix.org", matrix_auth['username'])
|
||||
|
||||
# Login
|
||||
login_resp = await client.login(matrix_auth['password'])
|
||||
@@ -186,6 +181,8 @@ async def share_art(request):
|
||||
await client.close()
|
||||
return web.json_response({"error": "Invalid Matrix credentials."}, content_type='application/json', status=400)
|
||||
|
||||
set_matrix_auth(matrix_auth)
|
||||
|
||||
# Upload asset
|
||||
with open(asset_filepath, 'rb') as f:
|
||||
upload_resp, _maybe_keys = await client.upload(f, content_type=content_type, filename=filename)
|
||||
|
||||
@@ -80,7 +80,7 @@ def read_config():
|
||||
global default_conf
|
||||
try:
|
||||
import configparser
|
||||
config = configparser.ConfigParser(strict=False)
|
||||
config = configparser.ConfigParser(strict=False, interpolation=None)
|
||||
config.read(manager_config_path)
|
||||
default_conf = config['default']
|
||||
except Exception:
|
||||
@@ -101,7 +101,16 @@ def check_file_logging():
|
||||
enable_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
|
||||
git_exe = default_conf.get('git_exe', '', raw=True) if 'git_exe' in default_conf else ''
|
||||
if git_exe != '':
|
||||
os.environ['GIT_EXE_PATH'] = git_exe
|
||||
|
||||
|
||||
read_config()
|
||||
set_git_executable()
|
||||
from .common import git_compat # noqa: E402,F401
|
||||
read_uv_mode()
|
||||
read_unified_resolver_mode()
|
||||
security_check.security_check()
|
||||
@@ -352,16 +361,18 @@ try:
|
||||
|
||||
def sync_write(self, message, file_only=False):
|
||||
with log_lock:
|
||||
timestamp = current_timestamp()
|
||||
if self.last_char != '\n':
|
||||
log_file.write(message)
|
||||
else:
|
||||
log_file.write(f"[{timestamp}] {message}")
|
||||
# after close_log() the output goes to the console only
|
||||
if not log_file.closed:
|
||||
timestamp = current_timestamp()
|
||||
if self.last_char != '\n':
|
||||
log_file.write(message)
|
||||
else:
|
||||
log_file.write(f"[{timestamp}] {message}")
|
||||
|
||||
try:
|
||||
log_file.flush()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
log_file.flush()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
self.last_char = message if message == '' else message[-1]
|
||||
|
||||
@@ -399,12 +410,15 @@ try:
|
||||
def close_log(self):
|
||||
sys.stderr = original_stderr
|
||||
sys.stdout = original_stdout
|
||||
log_file.close()
|
||||
with log_lock:
|
||||
log_file.close()
|
||||
|
||||
def close_log():
|
||||
sys.stderr = original_stderr
|
||||
sys.stdout = original_stdout
|
||||
log_file.close()
|
||||
# a write that has found the file open finishes first
|
||||
with log_lock:
|
||||
log_file.close()
|
||||
|
||||
|
||||
if enable_file_logging:
|
||||
@@ -583,7 +597,8 @@ if os.path.exists(restore_snapshot_path):
|
||||
allow_flagged or manager_security.is_loopback_listener(args.listen)
|
||||
).lower()
|
||||
new_env['_COMFYUI_MANAGER_CNR_WHITELIST_DIR'] = manager_files_path
|
||||
cmd_str = [sys.executable, '-m', 'cm_cli', 'restore-snapshot', restore_snapshot_path]
|
||||
cmd_str = [sys.executable, '-m', 'cm_cli', 'restore-snapshot', restore_snapshot_path,
|
||||
'--user-directory', manager_files_path, '--restore-to', custom_nodes_base_path]
|
||||
exit_code = process_wrap(cmd_str, custom_nodes_base_path, handler=msg_capture, env=new_env)
|
||||
|
||||
if exit_code != 0:
|
||||
@@ -652,9 +667,10 @@ def execute_lazy_cnr_switch(target, zip_url, from_path, to_path, no_deps, custom
|
||||
download_path = os.path.join(custom_nodes_path, archive_name)
|
||||
manager_downloader.download_url(zip_url, custom_nodes_path, archive_name)
|
||||
|
||||
# 2. extract files into <node_id>@<cur_ver>
|
||||
extracted = manager_util.extract_package_as_zip(download_path, from_path)
|
||||
os.remove(download_path)
|
||||
try:
|
||||
extracted = manager_util.switch_package_files(download_path, from_path)
|
||||
finally:
|
||||
os.remove(download_path)
|
||||
|
||||
if extracted is None:
|
||||
if len(os.listdir(from_path)) == 0:
|
||||
@@ -663,32 +679,10 @@ def execute_lazy_cnr_switch(target, zip_url, from_path, to_path, no_deps, custom
|
||||
print(f'Empty archive file: {target}')
|
||||
return False
|
||||
|
||||
if from_path != to_path:
|
||||
print(f"'{from_path}' is moved to '{to_path}'")
|
||||
shutil.move(from_path, to_path)
|
||||
|
||||
# 3. calculate garbage files (.tracking - extracted)
|
||||
tracking_info_file = os.path.join(from_path, '.tracking')
|
||||
prev_files = set()
|
||||
with open(tracking_info_file, 'r') as f:
|
||||
for line in f:
|
||||
prev_files.add(line.strip())
|
||||
garbage = prev_files.difference(extracted)
|
||||
garbage = [os.path.join(custom_nodes_path, x) for x in garbage]
|
||||
|
||||
# 4-1. remove garbage files
|
||||
for x in garbage:
|
||||
if os.path.isfile(x):
|
||||
os.remove(x)
|
||||
|
||||
# 4-2. remove garbage dir if empty
|
||||
for x in garbage:
|
||||
if os.path.isdir(x):
|
||||
if not os.listdir(x):
|
||||
os.rmdir(x)
|
||||
|
||||
# 5. rename dir name <node_id>@<prev_ver> ==> <node_id>@<cur_ver>
|
||||
print(f"'{from_path}' is moved to '{to_path}'")
|
||||
shutil.move(from_path, to_path)
|
||||
|
||||
# 6. create .tracking file
|
||||
tracking_info_file = os.path.join(to_path, '.tracking')
|
||||
with open(tracking_info_file, "w", encoding='utf-8') as file:
|
||||
file.write('\n'.join(list(extracted)))
|
||||
@@ -751,8 +745,9 @@ def execute_startup_script():
|
||||
|
||||
elif script[1] == "#LAZY-CNR-SWITCH-SCRIPT":
|
||||
status = script[8] if len(script) > 8 else ''
|
||||
if execute_lazy_cnr_switch(script[0], script[2], script[3], script[4], script[5], script[6], status):
|
||||
execute_lazy_install_script(script[3], script[7])
|
||||
to_path = script[4]
|
||||
if execute_lazy_cnr_switch(script[0], script[2], script[3], to_path, script[5], script[6], status):
|
||||
execute_lazy_install_script(to_path, script[7])
|
||||
|
||||
elif script[1] == "#LAZY-DELETE-NODEPACK":
|
||||
execute_lazy_delete(script[2])
|
||||
@@ -855,7 +850,7 @@ if script_executed:
|
||||
def check_windows_event_loop_policy():
|
||||
try:
|
||||
import configparser
|
||||
config = configparser.ConfigParser(strict=False)
|
||||
config = configparser.ConfigParser(strict=False, interpolation=None)
|
||||
config.read(manager_config_path)
|
||||
default_conf = config['default']
|
||||
|
||||
|
||||
+27
-19
@@ -422,8 +422,10 @@ components:
|
||||
description: UI identifier for task tracking
|
||||
stable:
|
||||
type: boolean
|
||||
default: true
|
||||
description: Whether to update to stable version (true) or nightly (false)
|
||||
description: Whether to update to stable version (true) or nightly (false). When neither this nor `is_stable` is given, the update policy decides.
|
||||
is_stable:
|
||||
type: boolean
|
||||
description: Another name for `stable`, the one the task parameters use. Read when `stable` is not given.
|
||||
required: [client_id, ui_id]
|
||||
ComfyUISwitchVersionParams:
|
||||
type: object
|
||||
@@ -1057,12 +1059,14 @@ paths:
|
||||
/v2/manager/queue/start:
|
||||
post:
|
||||
summary: Start queue processing
|
||||
description: Starts processing the operation queue.
|
||||
description: Starts processing the operation queue. The request has no body and needs the Content-Type `application/json`.
|
||||
responses:
|
||||
'200':
|
||||
description: Processing started
|
||||
'201':
|
||||
description: Processing already in progress
|
||||
'400':
|
||||
description: Content-Type is not application/json
|
||||
|
||||
/v2/customnode/import_fail_info_bulk:
|
||||
post:
|
||||
@@ -1092,14 +1096,16 @@ paths:
|
||||
/v2/manager/queue/reset:
|
||||
post:
|
||||
summary: Reset queue
|
||||
description: Resets the operation queue.
|
||||
description: Resets the operation queue. The request has no body and needs the Content-Type `application/json`.
|
||||
responses:
|
||||
'200':
|
||||
description: Queue reset successfully
|
||||
'400':
|
||||
description: Content-Type is not application/json
|
||||
/v2/manager/queue/update_all:
|
||||
post:
|
||||
summary: Update all custom nodes
|
||||
description: Queues update operations for all installed custom nodes. Parameters are read from the query string.
|
||||
description: Queues update operations for all installed custom nodes. Parameters are read from the query string. The request has no body and needs the Content-Type `application/json`.
|
||||
security:
|
||||
- securityLevel: []
|
||||
parameters:
|
||||
@@ -1110,7 +1116,7 @@ paths:
|
||||
'200':
|
||||
description: Update queued successfully
|
||||
'400':
|
||||
description: Missing required parameters
|
||||
description: Content-Type is not application/json, or missing required parameters
|
||||
'401':
|
||||
description: Processing already in progress
|
||||
'403':
|
||||
@@ -1118,7 +1124,7 @@ paths:
|
||||
/v2/manager/queue/update_comfyui:
|
||||
post:
|
||||
summary: Update ComfyUI
|
||||
description: Queues an update operation for ComfyUI itself. Parameters are read from the query string.
|
||||
description: Queues an update operation for ComfyUI itself. Parameters are read from the query string. The request has no body and needs the Content-Type `application/json`.
|
||||
parameters:
|
||||
- $ref: '#/components/parameters/clientIdRequiredParam'
|
||||
- $ref: '#/components/parameters/uiIdRequiredParam'
|
||||
@@ -1126,7 +1132,7 @@ paths:
|
||||
'200':
|
||||
description: Update queued successfully
|
||||
'400':
|
||||
description: Missing required parameters
|
||||
description: Content-Type is not application/json, or missing required parameters
|
||||
/v2/manager/queue/install_model:
|
||||
post:
|
||||
summary: Install model
|
||||
@@ -1232,7 +1238,7 @@ paths:
|
||||
/v2/snapshot/remove:
|
||||
post:
|
||||
summary: Remove snapshot
|
||||
description: Removes a specified snapshot. The `target` parameter is read from the query string.
|
||||
description: Removes a specified snapshot. The `target` parameter is read from the query string. The request has no body and needs the Content-Type `application/json`.
|
||||
security:
|
||||
- securityLevel: []
|
||||
parameters:
|
||||
@@ -1241,13 +1247,13 @@ paths:
|
||||
'200':
|
||||
description: Snapshot removed successfully
|
||||
'400':
|
||||
description: Error removing snapshot
|
||||
description: Content-Type is not application/json, or error removing snapshot
|
||||
'403':
|
||||
description: Security policy violation
|
||||
/v2/snapshot/restore:
|
||||
post:
|
||||
summary: Restore snapshot
|
||||
description: Restores a specified snapshot. The `target` parameter is read from the query string.
|
||||
description: Restores a specified snapshot. The `target` parameter is read from the query string. The request has no body and needs the Content-Type `application/json`.
|
||||
security:
|
||||
- securityLevel: []
|
||||
parameters:
|
||||
@@ -1256,7 +1262,7 @@ paths:
|
||||
'200':
|
||||
description: Snapshot restoration scheduled
|
||||
'400':
|
||||
description: Error restoring snapshot
|
||||
description: Content-Type is not application/json, or error restoring snapshot
|
||||
'403':
|
||||
description: Security policy violation
|
||||
/v2/snapshot/get_current:
|
||||
@@ -1275,12 +1281,12 @@ paths:
|
||||
/v2/snapshot/save:
|
||||
post:
|
||||
summary: Save snapshot
|
||||
description: Saves the current system state as a new snapshot.
|
||||
description: Saves the current system state as a new snapshot. The request has no body and needs the Content-Type `application/json`.
|
||||
responses:
|
||||
'200':
|
||||
description: Snapshot saved successfully
|
||||
'400':
|
||||
description: Error saving snapshot
|
||||
description: Content-Type is not application/json, or error saving snapshot
|
||||
# ComfyUI Management Endpoints (v2)
|
||||
/v2/comfyui_manager/comfyui_versions:
|
||||
get:
|
||||
@@ -1333,7 +1339,7 @@ paths:
|
||||
text/plain:
|
||||
schema:
|
||||
type: string
|
||||
enum: [channel, local, remote]
|
||||
enum: [cache, channel, local, remote]
|
||||
post:
|
||||
summary: Set database mode
|
||||
description: Sets the database mode. Payload is a JSON object with a `value` field.
|
||||
@@ -1347,7 +1353,7 @@ paths:
|
||||
properties:
|
||||
value:
|
||||
type: string
|
||||
enum: [channel, local, remote]
|
||||
enum: [cache, channel, local, remote]
|
||||
description: New database mode
|
||||
responses:
|
||||
'200':
|
||||
@@ -1365,7 +1371,7 @@ paths:
|
||||
text/plain:
|
||||
schema:
|
||||
type: string
|
||||
enum: [stable, nightly, nightly-comfyui]
|
||||
enum: [stable, stable-comfyui, nightly, nightly-comfyui]
|
||||
post:
|
||||
summary: Set update policy
|
||||
description: Sets the update policy. Payload is a JSON object with a `value` field.
|
||||
@@ -1379,7 +1385,7 @@ paths:
|
||||
properties:
|
||||
value:
|
||||
type: string
|
||||
enum: [stable, nightly, nightly-comfyui]
|
||||
enum: [stable, stable-comfyui, nightly, nightly-comfyui]
|
||||
description: New update policy
|
||||
responses:
|
||||
'200':
|
||||
@@ -1431,12 +1437,14 @@ paths:
|
||||
/v2/manager/reboot:
|
||||
post:
|
||||
summary: Reboot ComfyUI
|
||||
description: Restarts the ComfyUI server.
|
||||
description: Restarts the ComfyUI server. The request has no body and needs the Content-Type `application/json`.
|
||||
security:
|
||||
- securityLevel: []
|
||||
responses:
|
||||
'200':
|
||||
description: Reboot initiated
|
||||
'400':
|
||||
description: Content-Type is not application/json
|
||||
'403':
|
||||
description: Security policy violation
|
||||
/v2/manager/version:
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta"
|
||||
[project]
|
||||
name = "comfyui-manager"
|
||||
license = { text = "GPL-3.0-only" }
|
||||
version = "4.4"
|
||||
version = "4.4.2"
|
||||
requires-python = ">=3.10"
|
||||
description = "ComfyUI-Manager provides features to install and manage custom nodes for ComfyUI, as well as various functionalities to assist with ComfyUI."
|
||||
readme = "README.md"
|
||||
|
||||
@@ -16,8 +16,8 @@
|
||||
|
||||
Security-gated endpoints:
|
||||
- `middle`: reboot, snapshot/remove, _uninstall_custom_node, _update_custom_node
|
||||
- `middle+`: update_all, snapshot/restore, _install_custom_node, _install_model
|
||||
- `high+`: comfyui_switch_version, install/git_url, install/pip, non-safetensors model install, _fix_custom_node (raised from `high` to align the gate with the `SECURITY_MESSAGE_HIGH_P` log text — WI-#235; prior `middle` → `high` upgrade was commit `c8992e5d`)
|
||||
- `middle+`: update_all, _install_custom_node, _install_model
|
||||
- `high+`: comfyui_switch_version, snapshot/restore, `update-comfyui` task with an older `target_version` (glob worker step), install/git_url, install/pip, non-safetensors model install, _fix_custom_node (raised from `high` to align the gate with the `SECURITY_MESSAGE_HIGH_P` log text — WI-#235; prior `middle` → `high` upgrade was commit `c8992e5d`)
|
||||
|
||||
---
|
||||
|
||||
@@ -188,7 +188,7 @@ Security-gated endpoints:
|
||||
|
||||
### POST /v2/snapshot/restore
|
||||
- **Handler**: `restore_snapshot` (L1543)
|
||||
- **Security gate**: `middle+` → 403
|
||||
- **Security gate**: `high+` → 403
|
||||
- **Query**: `target`
|
||||
- **Scenarios**:
|
||||
1. Success — copies snapshot to startup script path (applied on next reboot) → 200
|
||||
@@ -331,7 +331,7 @@ Endpoints in this section exist **only in the legacy server** (not registered in
|
||||
### POST /v2/customnode/install/git_url
|
||||
- **Handler**: `install_custom_node_git_url` (L1502)
|
||||
- **Security gate**: `high+` → 403
|
||||
- **Body**: plain text URL
|
||||
- **Body**: JSON `{"url": ...}`, sent as `application/json`
|
||||
- **Scenarios**:
|
||||
1. Success install → 200
|
||||
2. Already installed (skip action) → 200
|
||||
@@ -341,7 +341,7 @@ Endpoints in this section exist **only in the legacy server** (not registered in
|
||||
### POST /v2/customnode/install/pip
|
||||
- **Handler**: `install_custom_node_pip` (L1522)
|
||||
- **Security gate**: `high+` → 403
|
||||
- **Body**: plain text space-separated packages
|
||||
- **Body**: JSON `{"packages": ...}` (space-separated), sent as `application/json`
|
||||
- **Scenarios**:
|
||||
1. Success — pip install completes → 200
|
||||
2. Security blocked → 403
|
||||
@@ -378,8 +378,8 @@ These paths exist in BOTH glob and legacy files (29 endpoints). Semantics are ty
|
||||
| Level | Glob endpoints | Legacy endpoints |
|
||||
|---|---|---|
|
||||
| **middle** | snapshot/remove, reboot | snapshot/remove, reboot, _uninstall, _update |
|
||||
| **middle+** | update_all, snapshot/restore, install_model | update_all, snapshot/restore, _install_custom_node, _install_model |
|
||||
| **high+** | comfyui_switch_version, _fix_custom_node | comfyui_switch_version, install/git_url, install/pip, non-safetensors model install, _fix |
|
||||
| **middle+** | update_all, install_model | update_all, _install_custom_node, _install_model |
|
||||
| **high+** | comfyui_switch_version, snapshot/restore, `update-comfyui` task with an older `target_version`, _fix_custom_node | comfyui_switch_version, snapshot/restore, install/git_url, install/pip, non-safetensors model install, _fix |
|
||||
|
||||
> Note: `_fix` / `_fix_custom_node` security-level history: `middle` → `high` in commit `c8992e5d` (2026-04-04, which also added a previously-missing gate to the legacy handler); subsequent `high` → `high+` in WI-#235 to align the enforcement gate with the `SECURITY_MESSAGE_HIGH_P` log text (and tighten the gate for a state-mutating fix path). README 'Risky Level Table' has been updated in lockstep.
|
||||
|
||||
@@ -407,7 +407,7 @@ These paths exist in BOTH glob and legacy files (29 endpoints). Semantics are ty
|
||||
| 6 | `/v2/manager/queue/task` | POST | POST (pre-existing) | default | `TestStateChangingEndpointsRejectGet::test_get_is_rejected[/v2/manager/queue/task]` |
|
||||
| 7 | `/v2/snapshot/save` | GET | POST | default | `TestStateChangingEndpointsRejectGet::test_get_is_rejected[/v2/snapshot/save]` |
|
||||
| 8 | `/v2/snapshot/remove` | GET | POST | middle | `TestStateChangingEndpointsRejectGet::test_get_is_rejected[/v2/snapshot/remove]` |
|
||||
| 9 | `/v2/snapshot/restore` | GET | POST | middle+ | `TestStateChangingEndpointsRejectGet::test_get_is_rejected[/v2/snapshot/restore]` |
|
||||
| 9 | `/v2/snapshot/restore` | GET | POST | high+ | `TestStateChangingEndpointsRejectGet::test_get_is_rejected[/v2/snapshot/restore]` |
|
||||
| 10 | `/v2/manager/reboot` | GET | POST | middle | `TestStateChangingEndpointsRejectGet::test_get_is_rejected[/v2/manager/reboot]` |
|
||||
| 11 | `/v2/comfyui_manager/comfyui_switch_version` | GET | POST | high+ | `TestStateChangingEndpointsRejectGet::test_get_is_rejected[/v2/comfyui_manager/comfyui_switch_version]` |
|
||||
| 12 | `/v2/manager/db_mode` | GET (dual) | POST (write); GET preserved for read | default | `TestStateChangingEndpointsRejectGet::test_get_is_rejected[/v2/manager/db_mode]` |
|
||||
|
||||
@@ -219,7 +219,7 @@ Intent categories used:
|
||||
| Success | Recovery: rollback to a known-good state after bad update |
|
||||
| Nonexistent | Input resilience |
|
||||
| Path traversal | Security boundary |
|
||||
| Security denied | Security boundary: middle+ required (restore is destructive) |
|
||||
| Security denied | Security boundary: high+ required (restore is destructive) |
|
||||
|
||||
## 1.4 Configuration
|
||||
|
||||
|
||||
@@ -359,7 +359,7 @@ Negative check: <what must NOT happen>
|
||||
- **Observable**: manager_startup_script_path for `restore-snapshot.json`
|
||||
- **Assertion**: restore-snapshot.json exists; content == target snapshot; (downstream: reboot → state reverts)
|
||||
|
||||
### Goal SR6 — Security gate (<middle+)
|
||||
### Goal SR6 — Security gate (<high+)
|
||||
- **Assertion**: 403; no marker file
|
||||
|
||||
---
|
||||
@@ -666,7 +666,7 @@ Reusable verification templates organized by intent category. Apply the template
|
||||
|
||||
**Security tiers to cover**:
|
||||
- `middle` — reboot, snapshot/remove, _uninstall, _update
|
||||
- `middle+` — update_all, snapshot/restore, _install_custom_node, _install_model
|
||||
- `middle+` — update_all, _install_custom_node, _install_model
|
||||
- `high+` — comfyui_switch_version, install/git_url, install/pip, non-safetensors model, _fix (`middle` → `high` in commit `c8992e5d`; subsequent `high` → `high+` in WI-#235 to align the gate with the `SECURITY_MESSAGE_HIGH_P` log text)
|
||||
|
||||
**Path-traversal sub-template** (within security boundary):
|
||||
|
||||
@@ -175,3 +175,9 @@ def import_glob_security_utils():
|
||||
(the glob copy of the security_level gate matrix — guard rows
|
||||
SC-25C / SC-28)."""
|
||||
return _import_real("comfyui_manager.glob.utils.security_utils")
|
||||
|
||||
|
||||
# what `git rev-parse --local-env-vars` lists: with one of them, git does not work on the repository of its directory
|
||||
GIT_LOCATION = ('GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_CONFIG', 'GIT_CONFIG_PARAMETERS', 'GIT_CONFIG_COUNT', 'GIT_OBJECT_DIRECTORY',
|
||||
'GIT_DIR', 'GIT_WORK_TREE', 'GIT_IMPLICIT_WORK_TREE', 'GIT_GRAFT_FILE', 'GIT_INDEX_FILE', 'GIT_NO_REPLACE_OBJECTS',
|
||||
'GIT_REPLACE_REF_BASE', 'GIT_PREFIX', 'GIT_SHALLOW_FILE', 'GIT_COMMON_DIR')
|
||||
|
||||
@@ -122,7 +122,7 @@ def _assert_config_ini_persists_across_reboot(
|
||||
to work.
|
||||
"""
|
||||
try:
|
||||
resp = requests.post(f"{BASE_URL}/v2/manager/reboot", timeout=10)
|
||||
resp = requests.post(f"{BASE_URL}/v2/manager/reboot", headers={"Content-Type": "application/json"}, timeout=10)
|
||||
if resp.status_code == 403:
|
||||
pytest.skip(
|
||||
"reboot denied by security policy "
|
||||
|
||||
+23
-51
@@ -149,14 +149,14 @@ class TestCsrfPostWorks:
|
||||
|
||||
def test_queue_reset_post_works(self, comfyui):
|
||||
"""POST queue/reset should succeed (the same path rejects GET)."""
|
||||
resp = requests.post(f"{BASE_URL}/v2/manager/queue/reset", timeout=10)
|
||||
resp = requests.post(f"{BASE_URL}/v2/manager/queue/reset", headers={"Content-Type": "application/json"}, timeout=10)
|
||||
assert resp.status_code == 200, (
|
||||
f"POST queue/reset should succeed, got {resp.status_code}: {resp.text[:200]}"
|
||||
)
|
||||
|
||||
def test_snapshot_save_post_works(self, comfyui):
|
||||
"""POST snapshot/save should succeed."""
|
||||
resp = requests.post(f"{BASE_URL}/v2/snapshot/save", timeout=30)
|
||||
resp = requests.post(f"{BASE_URL}/v2/snapshot/save", headers={"Content-Type": "application/json"}, timeout=30)
|
||||
assert resp.status_code == 200, (
|
||||
f"POST snapshot/save should succeed, got {resp.status_code}: {resp.text[:200]}"
|
||||
)
|
||||
@@ -168,6 +168,7 @@ class TestCsrfPostWorks:
|
||||
requests.post(
|
||||
f"{BASE_URL}/v2/snapshot/remove",
|
||||
params={"target": items[0]},
|
||||
headers={"Content-Type": "application/json"},
|
||||
timeout=10,
|
||||
)
|
||||
|
||||
@@ -207,18 +208,10 @@ class TestCsrfReadEndpointsStillAllowGet:
|
||||
# Content-Type gate — second CSRF mitigation layer
|
||||
# ---------------------------------------------------------------------------
|
||||
#
|
||||
# GET→POST conversion alone does NOT block <form method=POST> from a malicious
|
||||
# cross-origin page, because browsers mark form submissions with one of three
|
||||
# CORS "simple request" Content-Types (Fetch spec §3.2.3) and do NOT preflight
|
||||
# them. These 9 high-risk state mutation endpoints therefore additionally
|
||||
# reject those three MIME types at the handler entry. Bare POST (no body) and
|
||||
# application/json remain accepted — same-origin fetch() and existing
|
||||
# manager-core JS callers are unaffected.
|
||||
#
|
||||
# Source of truth for the gated handler list:
|
||||
# comfyui_manager/common/manager_security.py :: reject_simple_form_post
|
||||
# comfyui_manager/glob/manager_server.py :: 9 handlers call it
|
||||
FORM_REJECTED_POST_ENDPOINTS = [
|
||||
# A page of another origin can make a browser send a POST without a CORS
|
||||
# preflight: as a form, or with no Content-Type at all, with or without a body.
|
||||
# It cannot send application/json without a preflight.
|
||||
BODYLESS_POST_ENDPOINTS = [
|
||||
"/v2/manager/queue/update_all",
|
||||
"/v2/snapshot/remove",
|
||||
"/v2/snapshot/restore",
|
||||
@@ -228,65 +221,47 @@ FORM_REJECTED_POST_ENDPOINTS = [
|
||||
"/v2/manager/queue/update_comfyui",
|
||||
# "/v2/comfyui_manager/comfyui_switch_version" — removed in WI #258:
|
||||
# migrated from query-string to JSON body, now a body-reading handler.
|
||||
# Per the module policy in common/manager_security.py, body-reading
|
||||
# handlers are NOT gated (CORS preflight on application/json already
|
||||
# blocks cross-origin form POST forgery).
|
||||
"/v2/manager/reboot",
|
||||
]
|
||||
|
||||
SIMPLE_FORM_CONTENT_TYPES = [
|
||||
NOT_JSON_CONTENT_TYPES = [
|
||||
None,
|
||||
"application/x-www-form-urlencoded",
|
||||
"multipart/form-data; boundary=----WebKitFormBoundaryTest",
|
||||
"text/plain",
|
||||
]
|
||||
|
||||
|
||||
class TestFormContentTypeRejected:
|
||||
"""Every gated state-changing endpoint MUST reject CORS simple-request
|
||||
Content-Types to block preflight-less <form method=POST> CSRF.
|
||||
|
||||
Matrix: 9 endpoints × 3 Content-Types = 27 assertions.
|
||||
"""
|
||||
|
||||
class TestContentTypeThatIsNotJsonRejected:
|
||||
@pytest.mark.parametrize(
|
||||
"content_type",
|
||||
SIMPLE_FORM_CONTENT_TYPES,
|
||||
ids=["urlencoded", "multipart", "textplain"],
|
||||
NOT_JSON_CONTENT_TYPES,
|
||||
ids=["none", "urlencoded", "multipart", "textplain"],
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
"path",
|
||||
FORM_REJECTED_POST_ENDPOINTS,
|
||||
ids=FORM_REJECTED_POST_ENDPOINTS,
|
||||
BODYLESS_POST_ENDPOINTS,
|
||||
ids=BODYLESS_POST_ENDPOINTS,
|
||||
)
|
||||
def test_form_content_type_rejected(self, comfyui, path, content_type):
|
||||
"""POST with a simple-form Content-Type must be rejected with 400.
|
||||
|
||||
The handler's Content-Type gate runs BEFORE the security_level check,
|
||||
def test_content_type_that_is_not_json_rejected(self, comfyui, path, content_type):
|
||||
"""The handler's Content-Type gate runs BEFORE the security_level check,
|
||||
so the expected status is 400 even under security levels that would
|
||||
otherwise return 403.
|
||||
"""
|
||||
resp = requests.post(
|
||||
f"{BASE_URL}{path}",
|
||||
headers={"Content-Type": content_type},
|
||||
data="", # empty body still counts: browsers would not preflight
|
||||
headers={} if content_type is None else {"Content-Type": content_type},
|
||||
data="",
|
||||
timeout=10,
|
||||
)
|
||||
assert resp.status_code == 400, (
|
||||
f"CSRF FORM-POST GATE BYPASS: POST {path} with "
|
||||
f"CSRF GATE BYPASS: POST {path} with "
|
||||
f"Content-Type={content_type!r} returned {resp.status_code} "
|
||||
f"(expected 400): {resp.text[:200]}"
|
||||
)
|
||||
|
||||
|
||||
class TestNoBodyPostStillAccepted:
|
||||
"""Positive control: bare POST (no body, no Content-Type) must still pass
|
||||
the form-content-type gate.
|
||||
|
||||
The existing frontend (snapshot.js, comfyui-manager.js, etc.) issues
|
||||
fetch()/XHR POSTs without an explicit body for these idempotent-ish
|
||||
operations; a regression here would break those callers.
|
||||
"""
|
||||
|
||||
class TestJsonPostWithoutBodyAccepted:
|
||||
@pytest.mark.parametrize(
|
||||
"path",
|
||||
# Subset — pick endpoints whose happy path is deterministic under the
|
||||
@@ -300,16 +275,13 @@ class TestNoBodyPostStillAccepted:
|
||||
],
|
||||
ids=["queue-reset", "queue-start", "snapshot-save"],
|
||||
)
|
||||
def test_no_body_post_still_accepted(self, comfyui, path):
|
||||
"""Bare POST (no Content-Type, no body) must NOT be rejected by the
|
||||
form-content-type gate. Any response other than 400-with-form-text
|
||||
proves the gate did not fire."""
|
||||
resp = requests.post(f"{BASE_URL}{path}", timeout=30)
|
||||
def test_json_post_without_body_accepted(self, comfyui, path):
|
||||
resp = requests.post(f"{BASE_URL}{path}", headers={"Content-Type": "application/json"}, timeout=30)
|
||||
# The gate returns 400 with a very specific text. Non-gate 400s
|
||||
# (validation errors, etc.) are allowed — we only assert the gate
|
||||
# itself didn't trigger.
|
||||
if resp.status_code == 400:
|
||||
assert "Invalid Content-Type for this endpoint" not in resp.text, (
|
||||
f"POST {path} (bare) hit the form-content-type gate: "
|
||||
f"POST {path} (application/json) hit the content-type gate: "
|
||||
f"{resp.text[:200]}"
|
||||
)
|
||||
|
||||
@@ -182,14 +182,14 @@ class TestLegacyCsrfPostWorks:
|
||||
|
||||
def test_queue_reset_post_works(self, comfyui_legacy):
|
||||
"""POST queue/reset should succeed (the same path rejects GET)."""
|
||||
resp = requests.post(f"{BASE_URL}/v2/manager/queue/reset", timeout=10)
|
||||
resp = requests.post(f"{BASE_URL}/v2/manager/queue/reset", headers={"Content-Type": "application/json"}, timeout=10)
|
||||
assert resp.status_code == 200, (
|
||||
f"POST queue/reset should succeed, got {resp.status_code}: {resp.text[:200]}"
|
||||
)
|
||||
|
||||
def test_snapshot_save_post_works(self, comfyui_legacy):
|
||||
"""POST snapshot/save should succeed on legacy."""
|
||||
resp = requests.post(f"{BASE_URL}/v2/snapshot/save", timeout=30)
|
||||
resp = requests.post(f"{BASE_URL}/v2/snapshot/save", headers={"Content-Type": "application/json"}, timeout=30)
|
||||
assert resp.status_code == 200, (
|
||||
f"POST snapshot/save should succeed, got {resp.status_code}: {resp.text[:200]}"
|
||||
)
|
||||
@@ -201,6 +201,7 @@ class TestLegacyCsrfPostWorks:
|
||||
requests.post(
|
||||
f"{BASE_URL}/v2/snapshot/remove",
|
||||
params={"target": items[0]},
|
||||
headers={"Content-Type": "application/json"},
|
||||
timeout=10,
|
||||
)
|
||||
|
||||
@@ -280,11 +281,10 @@ class TestLegacyIsLegacyManagerUIReturnsTrue:
|
||||
# Content-Type gate — legacy-side parity with test_e2e_csrf.py
|
||||
# ---------------------------------------------------------------------------
|
||||
#
|
||||
# The 9 legacy handlers mirrored from glob each call
|
||||
# manager_security.reject_simple_form_post() before their security-level
|
||||
# check. This suite verifies the legacy route table enforces the same
|
||||
# CORS-simple-request Content-Type rejection contract.
|
||||
LEGACY_FORM_REJECTED_POST_ENDPOINTS = [
|
||||
# A page of another origin can make a browser send a POST without a CORS
|
||||
# preflight: as a form, or with no Content-Type at all, with or without a body.
|
||||
# It cannot send application/json without a preflight.
|
||||
LEGACY_BODYLESS_POST_ENDPOINTS = [
|
||||
"/v2/manager/queue/update_all",
|
||||
"/v2/snapshot/remove",
|
||||
"/v2/snapshot/restore",
|
||||
@@ -293,57 +293,46 @@ LEGACY_FORM_REJECTED_POST_ENDPOINTS = [
|
||||
"/v2/manager/queue/start",
|
||||
"/v2/manager/queue/update_comfyui",
|
||||
# "/v2/comfyui_manager/comfyui_switch_version" — removed in WI #258:
|
||||
# migrated from query-string to JSON body on legacy + glob in parallel,
|
||||
# body-reading handler is not Content-Type-gated (see module policy in
|
||||
# common/manager_security.py).
|
||||
# migrated from query-string to JSON body on legacy + glob in parallel.
|
||||
"/v2/manager/reboot",
|
||||
]
|
||||
|
||||
LEGACY_SIMPLE_FORM_CONTENT_TYPES = [
|
||||
LEGACY_NOT_JSON_CONTENT_TYPES = [
|
||||
None,
|
||||
"application/x-www-form-urlencoded",
|
||||
"multipart/form-data; boundary=----WebKitFormBoundaryTest",
|
||||
"text/plain",
|
||||
]
|
||||
|
||||
|
||||
class TestLegacyFormContentTypeRejected:
|
||||
"""Legacy counterpart to TestFormContentTypeRejected in test_e2e_csrf.py.
|
||||
|
||||
Matrix: 9 endpoints × 3 Content-Types = 27 assertions against the legacy
|
||||
route table.
|
||||
"""
|
||||
|
||||
class TestLegacyContentTypeThatIsNotJsonRejected:
|
||||
@pytest.mark.parametrize(
|
||||
"content_type",
|
||||
LEGACY_SIMPLE_FORM_CONTENT_TYPES,
|
||||
ids=["urlencoded", "multipart", "textplain"],
|
||||
LEGACY_NOT_JSON_CONTENT_TYPES,
|
||||
ids=["none", "urlencoded", "multipart", "textplain"],
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
"path",
|
||||
LEGACY_FORM_REJECTED_POST_ENDPOINTS,
|
||||
ids=LEGACY_FORM_REJECTED_POST_ENDPOINTS,
|
||||
LEGACY_BODYLESS_POST_ENDPOINTS,
|
||||
ids=LEGACY_BODYLESS_POST_ENDPOINTS,
|
||||
)
|
||||
def test_form_content_type_rejected(
|
||||
def test_content_type_that_is_not_json_rejected(
|
||||
self, comfyui_legacy, path, content_type
|
||||
):
|
||||
"""POST with a simple-form Content-Type must be rejected with 400
|
||||
on the legacy route table as well."""
|
||||
resp = requests.post(
|
||||
f"{BASE_URL}{path}",
|
||||
headers={"Content-Type": content_type},
|
||||
headers={} if content_type is None else {"Content-Type": content_type},
|
||||
data="",
|
||||
timeout=10,
|
||||
)
|
||||
assert resp.status_code == 400, (
|
||||
f"CSRF FORM-POST GATE BYPASS (legacy): POST {path} with "
|
||||
f"CSRF GATE BYPASS (legacy): POST {path} with "
|
||||
f"Content-Type={content_type!r} returned {resp.status_code} "
|
||||
f"(expected 400): {resp.text[:200]}"
|
||||
)
|
||||
|
||||
|
||||
class TestLegacyNoBodyPostStillAccepted:
|
||||
"""Positive control for the legacy route table: bare POST still works."""
|
||||
|
||||
class TestLegacyJsonPostWithoutBodyAccepted:
|
||||
@pytest.mark.parametrize(
|
||||
"path",
|
||||
[
|
||||
@@ -353,13 +342,11 @@ class TestLegacyNoBodyPostStillAccepted:
|
||||
],
|
||||
ids=["queue-reset", "queue-start", "snapshot-save"],
|
||||
)
|
||||
def test_no_body_post_still_accepted(self, comfyui_legacy, path):
|
||||
"""Bare POST (no Content-Type, no body) must not hit the gate on
|
||||
legacy either."""
|
||||
resp = requests.post(f"{BASE_URL}{path}", timeout=30)
|
||||
def test_json_post_without_body_accepted(self, comfyui_legacy, path):
|
||||
resp = requests.post(f"{BASE_URL}{path}", headers={"Content-Type": "application/json"}, timeout=30)
|
||||
if resp.status_code == 400:
|
||||
assert "Invalid Content-Type for this endpoint" not in resp.text, (
|
||||
f"POST {path} (bare, legacy) hit the form-content-type gate: "
|
||||
f"POST {path} (application/json, legacy) hit the content-type gate: "
|
||||
f"{resp.text[:200]}"
|
||||
)
|
||||
|
||||
|
||||
@@ -49,6 +49,10 @@ PACK_VERSION = "1.0.1"
|
||||
POLL_TIMEOUT = 30 # max seconds to wait for an operation
|
||||
POLL_INTERVAL = 0.5 # seconds between polls
|
||||
|
||||
# A fresh environment has no cache of the Registry list. Manager fetches the
|
||||
# list when the server starts, and an install is refused until it is cached.
|
||||
REGISTRY_TIMEOUT = 300
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not E2E_ROOT
|
||||
or not os.path.isfile(os.path.join(E2E_ROOT, ".e2e_setup_complete")),
|
||||
@@ -98,7 +102,7 @@ def _queue_task(task: dict) -> None:
|
||||
timeout=10,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
requests.post(f"{BASE_URL}/v2/manager/queue/start", timeout=10)
|
||||
requests.post(f"{BASE_URL}/v2/manager/queue/start", headers={"Content-Type": "application/json"}, timeout=10)
|
||||
|
||||
|
||||
def _remove_pack(name: str) -> None:
|
||||
@@ -143,6 +147,11 @@ def _wait_for(predicate, timeout=POLL_TIMEOUT, interval=POLL_INTERVAL):
|
||||
return False
|
||||
|
||||
|
||||
def _registry_list_is_cached() -> bool:
|
||||
cache = os.path.join(COMFYUI_PATH, "user", "__manager", "cache")
|
||||
return os.path.isdir(cache) and any(name.endswith("_nodes.json") for name in os.listdir(cache))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Fixtures
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -152,9 +161,14 @@ def comfyui():
|
||||
"""Start ComfyUI once for the module, stop after all tests."""
|
||||
_remove_pack(PACK_DIR_NAME)
|
||||
pid = _start_comfyui()
|
||||
yield pid
|
||||
_stop_comfyui()
|
||||
_remove_pack(PACK_DIR_NAME)
|
||||
try:
|
||||
assert _wait_for(_registry_list_is_cached, timeout=REGISTRY_TIMEOUT), (
|
||||
f"Manager did not cache the Registry list within {REGISTRY_TIMEOUT}s; an install fails without it"
|
||||
)
|
||||
yield pid
|
||||
finally:
|
||||
_stop_comfyui()
|
||||
_remove_pack(PACK_DIR_NAME)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -217,7 +217,7 @@ def install(server, node, version, operation='install', *, repository='https://e
|
||||
'ui_id': ui_id, 'client_id': 'flagged-e2e', 'kind': operation, 'params': params,
|
||||
}, timeout=10)
|
||||
response.raise_for_status()
|
||||
requests.post(server.base + '/v2/manager/queue/start', timeout=10).raise_for_status()
|
||||
requests.post(server.base + '/v2/manager/queue/start', headers={'Content-Type': 'application/json'}, timeout=10).raise_for_status()
|
||||
query = {'ui_id': ui_id}
|
||||
deadline = time.monotonic() + 30
|
||||
while time.monotonic() < deadline:
|
||||
@@ -625,7 +625,7 @@ def test_scheduled_snapshot_restores_through_server_restart(
|
||||
installed = tmp_path / 'custom_nodes/fixture-snapshot'
|
||||
marker = installed / 'installed.txt'
|
||||
reservation = tmp_path / 'user/__manager/startup-scripts/restore-snapshot.json'
|
||||
with running_server(tmp_path, tree, '127.0.0.1', False, 'normal', registry) as server:
|
||||
with running_server(tmp_path, tree, '127.0.0.1', False, 'normal-', registry) as server:
|
||||
if existing:
|
||||
install(server, 'fixture-snapshot', '1.0.0')
|
||||
assert marker.read_text() == '1.0.0'
|
||||
|
||||
@@ -153,7 +153,7 @@ def _queue_task(task: dict) -> None:
|
||||
"""Queue a Manager task and start the worker."""
|
||||
resp = requests.post(f"{BASE_URL}/v2/manager/queue/task", json=task, timeout=10)
|
||||
resp.raise_for_status()
|
||||
requests.post(f"{BASE_URL}/v2/manager/queue/start", timeout=10)
|
||||
requests.post(f"{BASE_URL}/v2/manager/queue/start", headers={"Content-Type": "application/json"}, timeout=10)
|
||||
|
||||
|
||||
def _remove_pack(name: str) -> None:
|
||||
|
||||
@@ -320,7 +320,7 @@ class TestUpdateComfyuiQueued:
|
||||
|
||||
def test_direct_endpoint_returns_200(self, comfyui_legacy):
|
||||
resp = requests.post(
|
||||
f"{BASE_URL}/v2/manager/queue/update_comfyui", timeout=15
|
||||
f"{BASE_URL}/v2/manager/queue/update_comfyui", headers={"Content-Type": "application/json"}, timeout=15
|
||||
)
|
||||
assert resp.status_code == 200, (
|
||||
f"update_comfyui should return 200 at default security_level, "
|
||||
@@ -468,7 +468,7 @@ class TestSwitchComfyuiSelfSwitch:
|
||||
class TestInstallViaGitUrlRealClone:
|
||||
"""Real E2E for wi-037 POST /v2/customnode/install/git_url.
|
||||
|
||||
Strategy: POST with body=TRUSTED_GIT_URL (plain text). Handler
|
||||
Handler
|
||||
(legacy/manager_server.py:1502-1519) runs core.gitclone_install(url)
|
||||
synchronously; 200 on success + 'After restarting ComfyUI' log;
|
||||
'skip' action on already-installed → also 200.
|
||||
@@ -492,8 +492,7 @@ class TestInstallViaGitUrlRealClone:
|
||||
try:
|
||||
resp = requests.post(
|
||||
f"{BASE_URL}/v2/customnode/install/git_url",
|
||||
data=TRUSTED_GIT_URL,
|
||||
headers={"Content-Type": "text/plain"},
|
||||
json={"url": TRUSTED_GIT_URL},
|
||||
timeout=180,
|
||||
)
|
||||
assert resp.status_code == 200, (
|
||||
@@ -558,8 +557,7 @@ class TestInstallPipRealExecute:
|
||||
try:
|
||||
resp = requests.post(
|
||||
f"{BASE_URL}/v2/customnode/install/pip",
|
||||
data=TRUSTED_PIP_PKG,
|
||||
headers={"Content-Type": "text/plain"},
|
||||
json={"packages": TRUSTED_PIP_PKG},
|
||||
timeout=30,
|
||||
)
|
||||
assert resp.status_code == 200, (
|
||||
|
||||
@@ -127,7 +127,7 @@ class TestQueueLifecycle:
|
||||
must be 0/False. Any non-zero count here would indicate a leak from an
|
||||
earlier test module or a reset-handler regression.
|
||||
"""
|
||||
resp = requests.post(f"{BASE_URL}/v2/manager/queue/reset", timeout=10)
|
||||
resp = requests.post(f"{BASE_URL}/v2/manager/queue/reset", headers={"Content-Type": "application/json"}, timeout=10)
|
||||
assert resp.status_code == 200, (
|
||||
f"Queue reset failed with status {resp.status_code}"
|
||||
)
|
||||
@@ -179,13 +179,13 @@ class TestQueueLifecycle:
|
||||
`start_worker()` accidentally spawns a hot-loop that never exits.
|
||||
"""
|
||||
# Ensure idle baseline (pending empty before start).
|
||||
requests.post(f"{BASE_URL}/v2/manager/queue/reset", timeout=10)
|
||||
requests.post(f"{BASE_URL}/v2/manager/queue/reset", headers={"Content-Type": "application/json"}, timeout=10)
|
||||
pre = requests.get(f"{BASE_URL}/v2/manager/queue/status", timeout=10).json()
|
||||
assert pre["pending_count"] == 0, (
|
||||
f"Pre-condition: pending_count must be 0 before idle-start test, got {pre['pending_count']}"
|
||||
)
|
||||
|
||||
resp = requests.post(f"{BASE_URL}/v2/manager/queue/start", timeout=10)
|
||||
resp = requests.post(f"{BASE_URL}/v2/manager/queue/start", headers={"Content-Type": "application/json"}, timeout=10)
|
||||
assert resp.status_code in (200, 201), (
|
||||
f"Queue start returned unexpected status {resp.status_code}"
|
||||
)
|
||||
@@ -223,7 +223,7 @@ class TestQueueLifecycle:
|
||||
# Reset to clean slate. Note: reset wipes pending/running but not
|
||||
# file-based batch history, so we track completion by our OWN ui_id
|
||||
# rather than a global done_count which can reflect unrelated tasks.
|
||||
requests.post(f"{BASE_URL}/v2/manager/queue/reset", timeout=10)
|
||||
requests.post(f"{BASE_URL}/v2/manager/queue/reset", headers={"Content-Type": "application/json"}, timeout=10)
|
||||
|
||||
UI_ID = "e2e-queue-lifecycle"
|
||||
# Queue a lightweight task (install a small CNR package)
|
||||
@@ -249,7 +249,7 @@ class TestQueueLifecycle:
|
||||
)
|
||||
|
||||
# Start processing
|
||||
resp = requests.post(f"{BASE_URL}/v2/manager/queue/start", timeout=10)
|
||||
resp = requests.post(f"{BASE_URL}/v2/manager/queue/start", headers={"Content-Type": "application/json"}, timeout=10)
|
||||
assert resp.status_code in (200, 201), (
|
||||
f"Queue start failed with status {resp.status_code}"
|
||||
)
|
||||
@@ -342,7 +342,7 @@ class TestQueueLifecycle:
|
||||
}
|
||||
r = requests.post(f"{BASE_URL}/v2/manager/queue/task", json=seed_payload, timeout=10)
|
||||
assert r.status_code == 200, f"seed queue/task failed: {r.status_code} {r.text[:200]}"
|
||||
r = requests.post(f"{BASE_URL}/v2/manager/queue/start", timeout=10)
|
||||
r = requests.post(f"{BASE_URL}/v2/manager/queue/start", headers={"Content-Type": "application/json"}, timeout=10)
|
||||
assert r.status_code in (200, 201), f"seed queue/start failed: {r.status_code}"
|
||||
|
||||
def _seed_done():
|
||||
|
||||
@@ -204,13 +204,13 @@ comfyui_flags_h = _make_flags_server_fixture(
|
||||
|
||||
def _post_git_url(url: str) -> requests.Response:
|
||||
return requests.post(
|
||||
f"{BASE_URL}/v2/customnode/install/git_url", data=url, timeout=120,
|
||||
f"{BASE_URL}/v2/customnode/install/git_url", json={"url": url}, timeout=120,
|
||||
)
|
||||
|
||||
|
||||
def _post_pip(packages: str) -> requests.Response:
|
||||
return requests.post(
|
||||
f"{BASE_URL}/v2/customnode/install/pip", data=packages, timeout=60,
|
||||
f"{BASE_URL}/v2/customnode/install/pip", json={"packages": packages}, timeout=60,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ without elevating the security_level to STRONG.
|
||||
|
||||
The 4 T2 SECGATE-PENDING Goals at middle/middle+ that depend on this harness:
|
||||
- SR4 (snapshot/remove, gate=middle) ← THIS PoC
|
||||
- SR6 (snapshot/restore, gate=middle+) ← follow-up
|
||||
- SR6 (snapshot/restore, gate=high+) ← follow-up
|
||||
- V5 (manager/reboot, gate=middle) ← follow-up
|
||||
- UA2 (manager/queue/update_all, gate=middle+) ← follow-up
|
||||
|
||||
@@ -156,6 +156,7 @@ class TestSecurityGate403_SR4:
|
||||
resp = requests.post(
|
||||
f"{BASE_URL}/v2/snapshot/remove",
|
||||
params={"target": seed_name},
|
||||
headers={"Content-Type": "application/json"},
|
||||
timeout=10,
|
||||
)
|
||||
|
||||
|
||||
@@ -181,7 +181,7 @@ class TestSnapshotLifecycle:
|
||||
if os.path.isdir(SNAPSHOT_DIR):
|
||||
files_before = {f for f in os.listdir(SNAPSHOT_DIR) if f.endswith(".json")}
|
||||
|
||||
resp = requests.post(f"{BASE_URL}/v2/snapshot/save", timeout=30)
|
||||
resp = requests.post(f"{BASE_URL}/v2/snapshot/save", headers={"Content-Type": "application/json"}, timeout=30)
|
||||
assert resp.status_code == 200, (
|
||||
f"Snapshot save failed with status {resp.status_code}"
|
||||
)
|
||||
@@ -251,7 +251,7 @@ class TestSnapshotLifecycle:
|
||||
asserts. Does not depend on prior tests in this module.
|
||||
"""
|
||||
# SETUP: create a snapshot so we have a deterministic target
|
||||
save_resp = requests.post(f"{BASE_URL}/v2/snapshot/save", timeout=30)
|
||||
save_resp = requests.post(f"{BASE_URL}/v2/snapshot/save", headers={"Content-Type": "application/json"}, timeout=30)
|
||||
assert save_resp.status_code == 200, "setup save failed"
|
||||
|
||||
# Find the newly created snapshot by diffing against pre-save list
|
||||
@@ -267,6 +267,7 @@ class TestSnapshotLifecycle:
|
||||
resp = requests.post(
|
||||
f"{BASE_URL}/v2/snapshot/remove",
|
||||
params={"target": target},
|
||||
headers={"Content-Type": "application/json"},
|
||||
timeout=10,
|
||||
)
|
||||
assert resp.status_code == 200, (
|
||||
@@ -290,6 +291,7 @@ class TestSnapshotLifecycle:
|
||||
resp = requests.post(
|
||||
f"{BASE_URL}/v2/snapshot/remove",
|
||||
params={"target": "nonexistent_snapshot_99999"},
|
||||
headers={"Content-Type": "application/json"},
|
||||
timeout=10,
|
||||
)
|
||||
# Server returns 200 even when file doesn't exist (no-op behavior)
|
||||
@@ -317,6 +319,7 @@ class TestSnapshotLifecycle:
|
||||
resp = requests.post(
|
||||
f"{BASE_URL}/v2/snapshot/remove",
|
||||
params={"target": target},
|
||||
headers={"Content-Type": "application/json"},
|
||||
timeout=10,
|
||||
)
|
||||
assert resp.status_code == 400, (
|
||||
|
||||
@@ -204,7 +204,7 @@ class TestReboot:
|
||||
|
||||
# Trigger reboot — server may drop connection mid-response
|
||||
try:
|
||||
resp = requests.post(f"{BASE_URL}/v2/manager/reboot", timeout=10)
|
||||
resp = requests.post(f"{BASE_URL}/v2/manager/reboot", headers={"Content-Type": "application/json"}, timeout=10)
|
||||
if resp.status_code == 403:
|
||||
pytest.skip(
|
||||
"Reboot denied by security policy "
|
||||
|
||||
@@ -93,7 +93,7 @@ def _queue_task(task: dict) -> None:
|
||||
timeout=10,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
requests.post(f"{BASE_URL}/v2/manager/queue/start", timeout=10)
|
||||
requests.post(f"{BASE_URL}/v2/manager/queue/start", headers={"Content-Type": "application/json"}, timeout=10)
|
||||
|
||||
|
||||
def _remove_pack(name: str) -> None:
|
||||
@@ -241,7 +241,7 @@ def _ensure_pack_installed_with_tracking():
|
||||
|
||||
def _reset_queue():
|
||||
"""Reset the queue to clean state."""
|
||||
requests.post(f"{BASE_URL}/v2/manager/queue/reset", timeout=10)
|
||||
requests.post(f"{BASE_URL}/v2/manager/queue/reset", headers={"Content-Type": "application/json"}, timeout=10)
|
||||
|
||||
|
||||
def _wait_queue_idle(timeout=POLL_TIMEOUT):
|
||||
@@ -696,7 +696,7 @@ class TestInstallModel:
|
||||
# - done_count advanced → task already ran to history
|
||||
# Either proves the enqueued task left the pending state under
|
||||
# worker control. This does NOT assert download success.
|
||||
requests.post(f"{BASE_URL}/v2/manager/queue/start", timeout=10)
|
||||
requests.post(f"{BASE_URL}/v2/manager/queue/start", headers={"Content-Type": "application/json"}, timeout=10)
|
||||
|
||||
def _worker_observed_task() -> bool:
|
||||
try:
|
||||
@@ -827,10 +827,10 @@ class TestUpdateAll:
|
||||
if isinstance(pkg, dict) and pkg.get("enabled", True):
|
||||
active_packs += 1
|
||||
|
||||
# The handler runs reload + get_custom_nodes synchronously, which can
|
||||
# be slow (up to ~2 min on cache-cold runs). Use an explicit long
|
||||
# timeout; a timeout here is a real server-perf regression, NOT
|
||||
# something to hide as a pass.
|
||||
# The handler fetches the whole Registry list before it answers. The
|
||||
# list is fetched 30 nodepacks per page with a pause after each page,
|
||||
# to keep the load on the Registry low: about three minutes for 6,500
|
||||
# nodepacks, and longer as the list grows.
|
||||
resp = requests.post(
|
||||
f"{BASE_URL}/v2/manager/queue/update_all",
|
||||
params={
|
||||
@@ -838,7 +838,8 @@ class TestUpdateAll:
|
||||
"client_id": "e2e-update-all",
|
||||
"ui_id": "e2e-update-all",
|
||||
},
|
||||
timeout=180,
|
||||
headers={"Content-Type": "application/json"},
|
||||
timeout=600,
|
||||
)
|
||||
|
||||
# Detect expected outcome based on server security configuration.
|
||||
@@ -875,6 +876,7 @@ class TestUpdateAll:
|
||||
"""POST /v2/manager/queue/update_all without required params -> 400."""
|
||||
resp = requests.post(
|
||||
f"{BASE_URL}/v2/manager/queue/update_all",
|
||||
headers={"Content-Type": "application/json"},
|
||||
timeout=10,
|
||||
)
|
||||
assert resp.status_code == 400, (
|
||||
@@ -903,6 +905,7 @@ class TestUpdateComfyUI:
|
||||
"client_id": "e2e-update-comfyui",
|
||||
"ui_id": "e2e-update-comfyui",
|
||||
},
|
||||
headers={"Content-Type": "application/json"},
|
||||
timeout=10,
|
||||
)
|
||||
assert resp.status_code == 200, (
|
||||
@@ -927,6 +930,7 @@ class TestUpdateComfyUI:
|
||||
"""POST /v2/manager/queue/update_comfyui without required params -> 400."""
|
||||
resp = requests.post(
|
||||
f"{BASE_URL}/v2/manager/queue/update_comfyui",
|
||||
headers={"Content-Type": "application/json"},
|
||||
timeout=10,
|
||||
)
|
||||
assert resp.status_code == 400, (
|
||||
@@ -944,6 +948,7 @@ class TestUpdateComfyUI:
|
||||
"ui_id": "e2e-update-comfyui-stable",
|
||||
"stable": "true",
|
||||
},
|
||||
headers={"Content-Type": "application/json"},
|
||||
timeout=10,
|
||||
)
|
||||
assert resp.status_code == 200, (
|
||||
@@ -961,7 +966,7 @@ class TestUpdateComfyUI:
|
||||
# never reaches history (silent empty-history regression). The
|
||||
# actual update work will fail fast in E2E (no real git remote),
|
||||
# but the task completes and moves to history regardless.
|
||||
requests.post(f"{BASE_URL}/v2/manager/queue/start", timeout=10)
|
||||
requests.post(f"{BASE_URL}/v2/manager/queue/start", headers={"Content-Type": "application/json"}, timeout=10)
|
||||
_wait_queue_idle(timeout=POLL_TIMEOUT)
|
||||
|
||||
# Try to inspect queued task params via JSON path.
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
"""Lift real production JS out of the shipped files and execute it in node.
|
||||
|
||||
WHY LIFT RATHER THAN IMPORT: the manager's front-end modules pull in
|
||||
``../../scripts/app.js`` and touch ``document`` at module scope, so node cannot
|
||||
import them. WHY LIFT RATHER THAN RETYPE: a retyped copy of a formatter stops
|
||||
tracking the formatter the moment someone edits it, and then the guard passes
|
||||
while the shipped code regresses. Lifting keeps the executed bytes the shipped
|
||||
bytes — if the production function changes, so does the text under test.
|
||||
|
||||
This mirrors tests/test_manager_markdown_escaping.py, which AST-extracts
|
||||
``convert_markdown_to_html`` rather than importing manager_server.
|
||||
|
||||
Consumers point ``JsSource`` at a directory of .js files; an override directory
|
||||
(e.g. one populated with ``git show <base>:js/foo.js``) makes the RED half of a
|
||||
fix reproducible in one command.
|
||||
"""
|
||||
import json
|
||||
import shutil
|
||||
import subprocess
|
||||
from html.parser import HTMLParser
|
||||
from pathlib import Path
|
||||
|
||||
NODE = shutil.which("node")
|
||||
|
||||
|
||||
def _skip_literal(source: str, pos: int) -> int:
|
||||
"""If a literal or comment starts at pos, return the index just past it.
|
||||
|
||||
Returns pos unchanged when nothing starts there. Template literals are
|
||||
consumed whole, which is safe for brace counting because a `${...}`
|
||||
substitution is itself balanced. A lone `/` is read as a regex literal —
|
||||
sanitizeHTML's own `.replace(/'/g, ...)` hides an apostrophe inside one, and
|
||||
no scanned range uses `/` as division. Were that to change, the assertion
|
||||
below fails loudly rather than returning a wrong slice.
|
||||
"""
|
||||
ch = source[pos]
|
||||
nxt = source[pos + 1] if pos + 1 < len(source) else ""
|
||||
if ch == "/" and nxt == "/":
|
||||
return source.index("\n", pos)
|
||||
if ch == "/" and nxt == "*":
|
||||
return source.index("*/", pos) + 2
|
||||
if ch not in "\"'`/":
|
||||
return pos
|
||||
cursor = pos + 1
|
||||
while cursor < len(source):
|
||||
if source[cursor] == "\\":
|
||||
cursor += 2
|
||||
continue
|
||||
if source[cursor] == ch:
|
||||
return cursor + 1
|
||||
cursor += 1
|
||||
raise AssertionError("unterminated literal at offset %d" % (pos,))
|
||||
|
||||
|
||||
def slice_braced(source: str, start_marker: str) -> str:
|
||||
"""Return start_marker plus the balanced {...} block that follows it."""
|
||||
start = source.index(start_marker)
|
||||
pos = source.index("{", start + len(start_marker))
|
||||
depth = 0
|
||||
while pos < len(source):
|
||||
skipped = _skip_literal(source, pos)
|
||||
if skipped != pos:
|
||||
pos = skipped
|
||||
continue
|
||||
if source[pos] == "{":
|
||||
depth += 1
|
||||
elif source[pos] == "}":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return source[start:pos + 1]
|
||||
pos += 1
|
||||
raise AssertionError("unbalanced braces after %r" % (start_marker,))
|
||||
|
||||
|
||||
def slice_object_entry(source: str, marker: str, indent: str = "\t\t") -> str:
|
||||
"""Return one object literal out of a `}, {`-chained array, by id marker.
|
||||
|
||||
These objects are literals inside an array, so the first `{` after the
|
||||
marker belongs to the NEXT entry — brace matching cannot be used. The entry
|
||||
instead ends at the first `}` sitting at the array's own indent.
|
||||
"""
|
||||
start = source.index(marker)
|
||||
end = source.index("\n%s}" % indent, start)
|
||||
return source[start:end]
|
||||
|
||||
|
||||
def line_containing(source: str, marker: str) -> str:
|
||||
"""Return the single source line that holds `marker` (fails if absent)."""
|
||||
start = source.index(marker)
|
||||
line_start = source.rfind("\n", 0, start) + 1
|
||||
return source[line_start:source.index("\n", start)]
|
||||
|
||||
|
||||
class JsSource:
|
||||
"""The shipped .js files under test, read from `js_dir`."""
|
||||
|
||||
def __init__(self, js_dir):
|
||||
self.js_dir = Path(js_dir)
|
||||
self._cache = {}
|
||||
|
||||
def text(self, filename: str) -> str:
|
||||
if filename not in self._cache:
|
||||
self._cache[filename] = (self.js_dir / filename).read_text(encoding="utf-8")
|
||||
return self._cache[filename]
|
||||
|
||||
def lift_declaration(self, filename: str, marker: str) -> str:
|
||||
"""Lift an `export function`/`export const` declaration, minus `export`."""
|
||||
return slice_braced(self.text(filename), marker).replace("export ", "", 1)
|
||||
|
||||
def lift_formatter(self, filename: str, anchor: str) -> str:
|
||||
"""Lift the `formatter: ...` at `anchor` as a bare function expression."""
|
||||
block = slice_braced(self.text(filename), anchor)
|
||||
marker = "formatter:"
|
||||
return block[block.index(marker) + len(marker):].strip()
|
||||
|
||||
def lift_span(self, filename: str, start_marker: str, end_marker: str) -> str:
|
||||
"""Lift the source between two markers, end_marker included."""
|
||||
source = self.text(filename)
|
||||
start = source.index(start_marker)
|
||||
end = source.index(end_marker, start) + len(end_marker)
|
||||
return source[start:end]
|
||||
|
||||
|
||||
def run_node(script: str) -> dict:
|
||||
"""Execute an ES-module script and parse the single JSON object it prints."""
|
||||
assert NODE is not None, "node is required to execute the lifted production JS"
|
||||
result = subprocess.run(
|
||||
[NODE, "--input-type=module", "-e", script],
|
||||
capture_output=True, text=True, timeout=60,
|
||||
)
|
||||
assert result.returncode == 0, "node failed:\n%s" % (result.stderr,)
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
class Collector(HTMLParser):
|
||||
"""Collects the tags and attributes a browser would actually build."""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.tags = []
|
||||
self.attrs = []
|
||||
|
||||
def handle_starttag(self, tag, attrs):
|
||||
self.tags.append(tag)
|
||||
self.attrs.extend(attrs)
|
||||
|
||||
handle_startendtag = handle_starttag
|
||||
|
||||
|
||||
def parse(markup: str) -> Collector:
|
||||
collector = Collector()
|
||||
collector.feed(markup)
|
||||
collector.close()
|
||||
return collector
|
||||
|
||||
|
||||
def event_handlers(markup: str):
|
||||
"""Every on* attribute a browser would attach for this markup."""
|
||||
return [name for name, _ in parse(markup).attrs if name.lower().startswith("on")]
|
||||
@@ -639,8 +639,8 @@ test.describe('batch error dialog', () => {
|
||||
// ===========================================================================
|
||||
|
||||
// The selectors below are load-bearing and were arrived at the hard way.
|
||||
// `.p-dialog input` matches the Custom Nodes SEARCH box
|
||||
// (`.cn-manager-keywords`, in `.p-dialog-header`) before it matches the prompt
|
||||
// `.cm-ui-dialog input` matches the Custom Nodes SEARCH box
|
||||
// (`.cn-manager-keywords`, in `.cm-ui-header`) before it matches the prompt
|
||||
// field, so a `.first()` on it silently types the URL into the search box:
|
||||
// install_via_git_url is never called, the denial modal never renders, and the
|
||||
// row fails as though the client produced nothing. Targeting
|
||||
@@ -665,7 +665,7 @@ test.describe('403 denial text', () => {
|
||||
// install_via_git_url -> the 403 arm at common.js:254.
|
||||
//
|
||||
// `.prompt-dialog-content input` is the load-bearing selector. A broader
|
||||
// `.p-dialog input` matches the Custom Nodes SEARCH box first, which is
|
||||
// `.cm-ui-dialog input` matches the Custom Nodes SEARCH box first, which is
|
||||
// silent: the URL lands in the search field, no request is made, and the
|
||||
// row fails at the denial assertion as though the client rendered nothing.
|
||||
await page.locator('.cn-manager-install-url').first().click();
|
||||
|
||||
+24
-10
@@ -101,19 +101,33 @@ export async function clickMenuButton(page: Page, text: string) {
|
||||
await dialog.locator(`button:has-text("${text}")`).click();
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the toasts of the ComfyUI frontend. One of them, such as the error
|
||||
* `getCanvas: canvas is null` that the frontend can raise while several pages
|
||||
* load at once, can lie over a button of a Manager dialog, and a click on
|
||||
* that button then never arrives.
|
||||
*/
|
||||
export async function closeToasts(page: Page) {
|
||||
const closeButtons = page.locator('[data-testid="toast"]').getByRole('button', { name: 'Close' });
|
||||
// A closed toast leaves the page and the others move up, so each click is
|
||||
// on the one that is first by then.
|
||||
for (let left = await closeButtons.count(); left > 0; left--) {
|
||||
await closeButtons.first().click({ timeout: 2_000 }).catch(() => {});
|
||||
await expect(closeButtons).toHaveCount(left - 1, { timeout: 2_000 }).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
/** Close the topmost dialog via its X (close) button or Escape. */
|
||||
export async function closeDialog(page: Page) {
|
||||
// Try clicking close buttons on visible dialogs. The manager-menu dialog
|
||||
// (`#cm-manager-dialog`) is a ComfyDialog with `.p-dialog-close-button` (X),
|
||||
// while sub-dialogs use `.cm-close-btn`. Try both.
|
||||
// Every Manager dialog has a `.cm-ui-close` (X). A sub-dialog lies
|
||||
// over the manager-menu dialog (`#cm-manager-dialog`), whose X stays visible
|
||||
// but cannot be clicked then, so the sub-dialogs are tried first.
|
||||
for (const sel of [
|
||||
'#cn-manager-dialog button.cm-close-btn',
|
||||
'#cmm-manager-dialog button.cm-close-btn',
|
||||
'#snapshot-manager-dialog button.cm-close-btn',
|
||||
'#cm-manager-dialog button.cm-close-btn',
|
||||
'#cm-manager-dialog .p-dialog-close-button',
|
||||
'.cm-close-btn',
|
||||
'.p-dialog-close-button',
|
||||
'#cn-manager-dialog .cm-ui-close',
|
||||
'#cmm-manager-dialog .cm-ui-close',
|
||||
'#snapshot-manager-dialog .cm-ui-close',
|
||||
'#cm-manager-dialog .cm-ui-close',
|
||||
'.cm-ui-close',
|
||||
]) {
|
||||
const btn = page.locator(sel).last();
|
||||
if (await btn.isVisible({ timeout: 500 }).catch(() => false)) {
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* E2E tests: the Manager dialogs bring their own styles.
|
||||
*
|
||||
* The ComfyUI frontend no longer ships the PrimeVue dialog styles. A dialog
|
||||
* that relies on them has no background, and its buttons lie over the canvas.
|
||||
*
|
||||
* Requires ComfyUI running with --enable-manager-legacy-ui on PORT.
|
||||
*/
|
||||
|
||||
import { test, expect, type Page } from '@playwright/test';
|
||||
import { waitForComfyUI, openManagerMenu, clickMenuButton } from './helpers';
|
||||
|
||||
const TRANSPARENT = 'rgba(0, 0, 0, 0)';
|
||||
const DIALOGS: [string, string | null, string][] = [
|
||||
['Manager menu', null, '#cm-manager-dialog'],
|
||||
['Custom Nodes Manager', 'Custom Nodes Manager', '#cn-manager-dialog'],
|
||||
['Model Manager', 'Model Manager', '#cmm-manager-dialog'],
|
||||
['Snapshot Manager', 'Snapshot Manager', '#snapshot-manager-dialog'],
|
||||
];
|
||||
|
||||
async function open(page: Page, button: string | null, selector: string) {
|
||||
await openManagerMenu(page);
|
||||
if (button) await clickMenuButton(page, button);
|
||||
await page.waitForSelector(selector, { timeout: 15_000 });
|
||||
return page.locator(selector).last();
|
||||
}
|
||||
|
||||
function background(locator: ReturnType<Page['locator']>) {
|
||||
return locator.evaluate((element) => getComputedStyle(element).backgroundColor);
|
||||
}
|
||||
|
||||
test.describe('Dialog styles', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.goto('/');
|
||||
await waitForComfyUI(page);
|
||||
});
|
||||
|
||||
for (const [name, button, selector] of DIALOGS) {
|
||||
test(`${name} has a background and dims the page behind it`, async ({ page }) => {
|
||||
const dialog = await open(page, button, selector);
|
||||
|
||||
expect(await background(dialog)).not.toBe(TRANSPARENT);
|
||||
expect(await background(dialog.locator('xpath=..'))).not.toBe(TRANSPARENT);
|
||||
});
|
||||
|
||||
test(`${name} is closed by its close button`, async ({ page }) => {
|
||||
const dialog = await open(page, button, selector);
|
||||
|
||||
await dialog.getByRole('button', { name: 'Close' }).click();
|
||||
|
||||
await expect(dialog).toBeHidden();
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -100,7 +100,7 @@ test.describe('UI-driven install/uninstall', () => {
|
||||
|
||||
test('LB1 Install button triggers install effect', async ({ page }) => {
|
||||
// Reset queue at start for deterministic done_count baseline in waitForAllDone
|
||||
await page.request.post('/v2/manager/queue/reset');
|
||||
await page.request.post('/v2/manager/queue/reset', { headers: { 'Content-Type': 'application/json' } });
|
||||
|
||||
// Precondition: pack must NOT be installed. If the seed pack is already
|
||||
// installed (prior pytest runs, pre-seeded E2E environment), the
|
||||
@@ -128,7 +128,7 @@ test.describe('UI-driven install/uninstall', () => {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
expect(queueResp.ok()).toBe(true);
|
||||
await page.request.post('/v2/manager/queue/start');
|
||||
await page.request.post('/v2/manager/queue/start', { headers: { 'Content-Type': 'application/json' } });
|
||||
await waitForAllDone(page, 60_000);
|
||||
// Hard fail if setup itself couldn't uninstall the pack
|
||||
expect(await isPackInstalled(page)).toBe(false);
|
||||
@@ -141,16 +141,13 @@ test.describe('UI-driven install/uninstall', () => {
|
||||
|
||||
// Wait for grid to populate before applying filter (avoids race on empty grid)
|
||||
await expect(page.locator('.tg-body .tg-row').first()).toBeVisible({ timeout: 30_000 });
|
||||
const initialRowCount = await page.locator('.tg-body .tg-row').count();
|
||||
|
||||
// Filter to Not Installed to make install buttons visible. Wait for
|
||||
// filtered row count to actually change (DOM state, not wall-clock).
|
||||
// Filter to Not Installed to make install buttons visible. The grid
|
||||
// renders only the rows in view, so their number does not tell whether
|
||||
// the filter was applied; the search below waits for its own result.
|
||||
const filterSelect = page.locator('select.cn-manager-filter').first();
|
||||
if (await filterSelect.isVisible().catch(() => false)) {
|
||||
await filterSelect.selectOption({ value: 'not-installed' });
|
||||
await expect
|
||||
.poll(async () => page.locator('.tg-body .tg-row').count(), { timeout: 10_000 })
|
||||
.not.toBe(initialRowCount);
|
||||
}
|
||||
|
||||
// Search for the specific test pack. Wait for search to narrow results.
|
||||
@@ -198,7 +195,7 @@ test.describe('UI-driven install/uninstall', () => {
|
||||
|
||||
test('LB2 Uninstall button triggers uninstall effect', async ({ page }) => {
|
||||
// Reset queue at start for deterministic done_count baseline in waitForAllDone
|
||||
await page.request.post('/v2/manager/queue/reset');
|
||||
await page.request.post('/v2/manager/queue/reset', { headers: { 'Content-Type': 'application/json' } });
|
||||
|
||||
// Precondition: pack must be installed. Install via API as test SETUP
|
||||
// (not verification). This makes LB2 independent of LB1 — hard-failing
|
||||
@@ -207,7 +204,7 @@ test.describe('UI-driven install/uninstall', () => {
|
||||
// is async, so waitForAllDone is still required after queue/start.
|
||||
const preinstalled = await isPackInstalled(page);
|
||||
if (!preinstalled) {
|
||||
await page.request.post('/v2/manager/queue/reset');
|
||||
await page.request.post('/v2/manager/queue/reset', { headers: { 'Content-Type': 'application/json' } });
|
||||
const queueResp = await page.request.post('/v2/manager/queue/batch', {
|
||||
data: JSON.stringify({
|
||||
batch_id: 'lb2-setup-install',
|
||||
@@ -225,7 +222,7 @@ test.describe('UI-driven install/uninstall', () => {
|
||||
expect(queueResp.ok()).toBe(true);
|
||||
const queueBody = await queueResp.json();
|
||||
expect(queueBody.failed ?? []).toEqual([]);
|
||||
await page.request.post('/v2/manager/queue/start');
|
||||
await page.request.post('/v2/manager/queue/start', { headers: { 'Content-Type': 'application/json' } });
|
||||
// Poll the terminal state directly: isPackInstalled returning true is
|
||||
// the unambiguous success signal. Using waitForAllDone here is racy —
|
||||
// fast-path installs (pack already on disk / cached CNR artifacts) can
|
||||
|
||||
@@ -56,7 +56,7 @@ test.describe('Manager Menu Dialog', () => {
|
||||
// No page.request / page.waitForResponse — pure UI interaction + dialog
|
||||
// close-reopen as the persistence proof. networkidle is used only as a
|
||||
// settle barrier (wait), never as assertion input. Close via the dialog's
|
||||
// own `.p-dialog-close-button` (X button) because Escape doesn't close
|
||||
// own `.cm-ui-close` (X button) because Escape doesn't close
|
||||
// ComfyDialog reliably.
|
||||
await openManagerMenu(page);
|
||||
const dialog = page.locator('#cm-manager-dialog').first();
|
||||
@@ -72,7 +72,7 @@ test.describe('Manager Menu Dialog', () => {
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Close + reopen (UI-only persistence proof)
|
||||
await dialog.locator('.p-dialog-close-button').first().click();
|
||||
await dialog.locator('.cm-ui-close').first().click();
|
||||
// ComfyDialog.close() sets display:none but keeps the element in DOM,
|
||||
// so check visibility (toBeHidden), not presence (toHaveCount 0).
|
||||
await expect(page.locator('#cm-manager-dialog').first()).toBeHidden({ timeout: 5_000 });
|
||||
@@ -106,6 +106,63 @@ test.describe('Manager Menu Dialog', () => {
|
||||
}
|
||||
});
|
||||
|
||||
for (const setting of [
|
||||
{ name: 'DB mode', route: '/v2/manager/db_mode', options: /Cache|Local|Channel/, values: ['local', 'remote'] },
|
||||
{ name: 'Update Policy', route: '/v2/manager/policy/update', options: /Stable|Nightly/, values: ['nightly-comfyui', 'stable-comfyui'] },
|
||||
{ name: 'Share', route: '/v2/manager/share_option', options: /YouML|Matrix/, values: ['youml', 'matrix'] },
|
||||
]) {
|
||||
test(`${setting.name}: a choice made while the setting is still loading is kept`, async ({ page }) => {
|
||||
// The dialog asks the server for the setting when it is first opened.
|
||||
// Hold the answer back after the server has given it, choose another
|
||||
// value, then let the answer through. The value that is chosen is not
|
||||
// the first option, which the select shows before the answer and which
|
||||
// a user therefore cannot choose.
|
||||
const reads = (request: { method(): string; url(): string }) =>
|
||||
request.method() === 'GET' && request.url().includes(setting.route);
|
||||
const saves = (request: { method(): string; url(): string }) => request.url().includes(setting.route) && !reads(request);
|
||||
const save = (value: string) =>
|
||||
page.request.post(setting.route, { data: JSON.stringify({ value }), headers: { 'Content-Type': 'application/json' } });
|
||||
const stored = await (await page.request.get(setting.route)).text();
|
||||
const chosen = setting.values.find((value) => value !== stored)!;
|
||||
let release!: () => void;
|
||||
const held = new Promise<void>((resolve) => { release = resolve; });
|
||||
let answered!: () => void;
|
||||
const answer = new Promise<void>((resolve) => { answered = resolve; });
|
||||
await page.route(`**${setting.route}*`, async (route) => {
|
||||
if (!reads(route.request())) {
|
||||
await route.continue();
|
||||
return;
|
||||
}
|
||||
const response = await route.fetch();
|
||||
answered();
|
||||
await held;
|
||||
await route.fulfill({ response });
|
||||
});
|
||||
|
||||
try {
|
||||
await openManagerMenu(page);
|
||||
const combo = page.locator('#cm-manager-dialog').first().locator('select').filter({ hasText: setting.options }).first();
|
||||
// The answer that is held back is one the server gave before the choice.
|
||||
await answer;
|
||||
const saved = page.waitForResponse((response) => saves(response.request()));
|
||||
await combo.selectOption(chosen);
|
||||
await saved;
|
||||
|
||||
const loaded = page.waitForResponse((response) => reads(response.request()));
|
||||
release();
|
||||
await loaded;
|
||||
await page.waitForTimeout(300);
|
||||
|
||||
await expect(combo).toHaveValue(chosen);
|
||||
expect(await (await page.request.get(setting.route)).text()).toBe(chosen);
|
||||
} finally {
|
||||
release();
|
||||
await page.unroute(`**${setting.route}*`);
|
||||
await save(stored);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test('Update Policy dropdown persists via UI (close-reopen verification)', async ({ page }) => {
|
||||
// Wave3 WI-U Cluster H target 2: same UI-only pattern as the DB mode test.
|
||||
await openManagerMenu(page);
|
||||
@@ -119,7 +176,7 @@ test.describe('Manager Menu Dialog', () => {
|
||||
await policyCombo.selectOption(newValue);
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
await dialog.locator('.p-dialog-close-button').first().click();
|
||||
await dialog.locator('.cm-ui-close').first().click();
|
||||
// ComfyDialog.close() sets display:none but keeps the element in DOM,
|
||||
// so check visibility (toBeHidden), not presence (toHaveCount 0).
|
||||
await expect(page.locator('#cm-manager-dialog').first()).toBeHidden({ timeout: 5_000 });
|
||||
@@ -316,7 +373,7 @@ test.describe('Manager Menu Dialog', () => {
|
||||
expect(statusBefore.status()).toBe(200);
|
||||
const statusJson = await statusBefore.json();
|
||||
|
||||
const resetResp = await request.post('/v2/manager/queue/reset');
|
||||
const resetResp = await request.post('/v2/manager/queue/reset', { headers: { 'Content-Type': 'application/json' } });
|
||||
expect(resetResp.status()).toBe(200);
|
||||
|
||||
// Post-check: queue/status still callable (handler released locks
|
||||
|
||||
@@ -42,9 +42,9 @@ test.describe('Dialog Navigation', () => {
|
||||
timeout: 15_000,
|
||||
});
|
||||
|
||||
// Close the Model Manager dialog via its close button (p-dialog-close-button)
|
||||
const mmMask = page.locator('.p-dialog-mask:has(#cmm-manager-dialog)');
|
||||
const mmCloseBtn = mmMask.locator('button[aria-label="Close"], .p-dialog-close-button').first();
|
||||
// Close the Model Manager dialog via its close button
|
||||
const mmMask = page.locator('.cm-ui-overlay:has(#cmm-manager-dialog)');
|
||||
const mmCloseBtn = mmMask.locator('button[aria-label="Close"], .cm-ui-close').first();
|
||||
if (await mmCloseBtn.isVisible({ timeout: 2_000 }).catch(() => false)) {
|
||||
await mmCloseBtn.click();
|
||||
} else {
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
*/
|
||||
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { waitForComfyUI, openManagerMenu, clickMenuButton } from './helpers';
|
||||
import { waitForComfyUI, openManagerMenu, clickMenuButton, closeToasts } from './helpers';
|
||||
|
||||
const SNAPSHOT_ROW_SELECTOR = '#snapshot-manager-dialog tr, #snapshot-manager-dialog li';
|
||||
|
||||
@@ -32,7 +32,7 @@ test.describe('Snapshot Manager', () => {
|
||||
test.afterEach(async ({ page }) => {
|
||||
// Cleanup snapshots newly created during the test to avoid state leak.
|
||||
for (const name of createdDuringTest) {
|
||||
await page.request.post(`/v2/snapshot/remove?target=${encodeURIComponent(name)}`);
|
||||
await page.request.post(`/v2/snapshot/remove?target=${encodeURIComponent(name)}`, { headers: { 'Content-Type': 'application/json' } });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -78,7 +78,7 @@ test.describe('Snapshot Manager', () => {
|
||||
|
||||
test('UI Remove button deletes a snapshot row', async ({ page }) => {
|
||||
// SETUP: create a snapshot via API so we have a deterministic target
|
||||
const saveResp = await page.request.post('/v2/snapshot/save');
|
||||
const saveResp = await page.request.post('/v2/snapshot/save', { headers: { 'Content-Type': 'application/json' } });
|
||||
expect(saveResp.ok()).toBe(true);
|
||||
const namesAfterSave = await getSnapshotNames(page);
|
||||
expect(namesAfterSave.length).toBeGreaterThan(0);
|
||||
@@ -113,6 +113,7 @@ test.describe('Snapshot Manager', () => {
|
||||
page.once('dialog', async (d) => {
|
||||
await d.accept();
|
||||
});
|
||||
await closeToasts(page);
|
||||
await removeBtn.first().click();
|
||||
|
||||
// Effect verification: snapshot disappears from backend AND from UI
|
||||
@@ -146,6 +147,7 @@ test.describe('Snapshot Manager', () => {
|
||||
};
|
||||
});
|
||||
});
|
||||
await closeToasts(page);
|
||||
await page.locator(SNAPSHOT_ROW_SELECTOR, { hasText: name }).first()
|
||||
.locator(`button:has-text("${action}")`).click();
|
||||
await page.evaluate(() => (window as any).__handled);
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
import ast
|
||||
import asyncio
|
||||
import importlib.util
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import traceback
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from legacy_html_testutil import PACKAGE, load_functions
|
||||
|
||||
LEVELS = ["strong", "normal", "normal-", "weak"]
|
||||
LISTENERS = ["loopback", "personal_cloud", "public"]
|
||||
|
||||
|
||||
def switch_allowed(security_level, listener):
|
||||
return security_level == "weak" and listener != "public" or security_level == "normal-" and listener == "loopback"
|
||||
|
||||
|
||||
class Repo:
|
||||
def __init__(self, described):
|
||||
self.described = described
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *args):
|
||||
return False
|
||||
|
||||
def describe_tags(self):
|
||||
return self.described
|
||||
|
||||
|
||||
def load(monkeypatch, security_level, listener, described="v0.3.60"):
|
||||
spec = importlib.util.spec_from_file_location("_generated_models", PACKAGE / "data_models/generated_models.py")
|
||||
models = importlib.util.module_from_spec(spec)
|
||||
monkeypatch.setitem(sys.modules, spec.name, models)
|
||||
spec.loader.exec_module(models)
|
||||
|
||||
switched, updated = [], []
|
||||
downgrade = load_functions(PACKAGE / "glob/manager_core.py", {"parse_semver", "is_comfyui_downgrade"}, {
|
||||
"re": re, "context": SimpleNamespace(comfy_path="comfyui"), "open_repo": lambda path: Repo(described),
|
||||
})
|
||||
core = SimpleNamespace(
|
||||
get_config=lambda: {"security_level": security_level,
|
||||
"network_mode": "personal_cloud" if listener == "personal_cloud" else "public"},
|
||||
is_comfyui_downgrade=downgrade["is_comfyui_downgrade"], switch_comfyui=switched.append,
|
||||
update_to_stable_comfyui=lambda path: updated.append(path) or ("skipped", None),
|
||||
)
|
||||
security = load_functions(PACKAGE / "glob/utils/security_utils.py", {"is_allowed_security_level"}, {
|
||||
"core": core, "args": SimpleNamespace(listen="127.0.0.1" if listener == "loopback" else "0.0.0.0"),
|
||||
"is_loopback": load_functions(PACKAGE / "common/manager_security.py", {"is_loopback"})["is_loopback"],
|
||||
"SecurityLevel": models.SecurityLevel, "RiskLevel": models.RiskLevel,
|
||||
})
|
||||
namespace = {
|
||||
"logging": logging, "traceback": traceback, "os": os,
|
||||
"folder_paths": SimpleNamespace(__file__="comfyui/folder_paths.py"), "core": core,
|
||||
"security_utils": SimpleNamespace(**security), "OperationResult": models.OperationResult,
|
||||
"UpdateComfyUIParams": models.UpdateComfyUIParams, "SECURITY_MESSAGE_HIGH_P": "",
|
||||
}
|
||||
path = PACKAGE / "glob/manager_server.py"
|
||||
nodes = [node for node in ast.walk(ast.parse(path.read_text(encoding="utf-8")))
|
||||
if isinstance(node, ast.AsyncFunctionDef) and node.name == "do_update_comfyui"]
|
||||
assert len(nodes) == 1
|
||||
exec(compile(ast.Module(nodes, []), str(path), "exec"), namespace)
|
||||
|
||||
def task(target_version):
|
||||
return asyncio.run(namespace["do_update_comfyui"](models.UpdateComfyUIParams(target_version=target_version)))
|
||||
|
||||
return SimpleNamespace(task=task, switched=switched, updated=updated)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("listener", LISTENERS)
|
||||
@pytest.mark.parametrize("security_level", LEVELS)
|
||||
def test_a_task_for_an_older_release_needs_the_level_of_the_switch_route(monkeypatch, security_level, listener):
|
||||
glob = load(monkeypatch, security_level, listener)
|
||||
|
||||
result = glob.task("v0.3.59")
|
||||
|
||||
if switch_allowed(security_level, listener):
|
||||
assert result == "success-switched-v0.3.59"
|
||||
assert glob.switched == ["v0.3.59"]
|
||||
else:
|
||||
assert result == "failed"
|
||||
assert glob.switched == []
|
||||
assert glob.updated == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("listener", LISTENERS)
|
||||
@pytest.mark.parametrize("security_level", LEVELS)
|
||||
@pytest.mark.parametrize("version", ["nightly", "v0.3.60", "v0.3.61", "v0.4.0", "v1.0.0"],
|
||||
ids=["nightly", "the same release", "a newer patch", "a newer minor", "a newer major"])
|
||||
def test_a_task_for_an_update_is_not_held_to_a_level(monkeypatch, version, security_level, listener):
|
||||
glob = load(monkeypatch, security_level, listener)
|
||||
|
||||
assert glob.task(version) == f"success-switched-{version}"
|
||||
assert glob.switched == [version]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("described, version, older", [
|
||||
("v0.3.60-12-gabc1234", "v0.3.60", True), ("v0.3.60-12-gabc1234", "v0.3.61", False),
|
||||
("v0.3.60-12-gabc1234", "v0.3.59", True), ("v0.3.60-1-gabc1234", "v0.3.60", True),
|
||||
("v0.45.0-32-g0123abc", "v0.45.0", True), ("v0.45.0-32-g0123abc", "v0.45.4", False),
|
||||
("v0.9.0", "v0.10.0", False), ("v0.10.0", "v0.9.0", True), ("v0.10.0", "v0.9.99", True),
|
||||
("v1.0.0", "v0.99.99", True), ("v0.3.60", "v0.3.060", False), ("v0.3.60", "v0.2.61", True),
|
||||
], ids=["commits after a release, that release", "commits after a release, a newer one", "commits after a release, an older one",
|
||||
"one commit after a release, that release", "nightly, the first release of its minor", "nightly, a later patch release",
|
||||
"a two-digit minor is newer", "a one-digit minor is older", "a higher patch of a lower minor",
|
||||
"a lower major", "leading zeros", "a higher patch of an older minor"])
|
||||
def test_releases_are_compared_by_their_numbers(monkeypatch, described, version, older):
|
||||
glob = load(monkeypatch, "strong", "loopback", described)
|
||||
|
||||
result = glob.task(version)
|
||||
|
||||
assert (result, glob.switched) == (("failed", []) if older else (f"success-switched-{version}", [version]))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("version", [
|
||||
"master", "HEAD~100", "abc1234", "0.3.61", "v0.3", "v0.3.61.1", "v0.3.61-rc1", "V0.3.61", " v0.3.61", "v0.3.61 ",
|
||||
"refs/tags/v0.3.61", "latest", "Nightly", "v0.3.61\n", "v0.3.61\nv0.3.59", "\nv0.3.61",
|
||||
], ids=["a branch", "an ancestor", "a commit", "no v", "two numbers", "four numbers", "a suffix", "upper case",
|
||||
"a leading space", "a trailing space", "a full ref", "another name", "nightly in another case", "a trailing newline",
|
||||
"two lines", "a leading newline"])
|
||||
def test_what_is_not_a_release_tag_is_held_like_an_older_release(monkeypatch, version):
|
||||
glob = load(monkeypatch, "normal", "loopback")
|
||||
assert glob.task(version) == "failed"
|
||||
assert glob.switched == []
|
||||
|
||||
glob = load(monkeypatch, "normal-", "loopback")
|
||||
assert glob.task(version) == f"success-switched-{version}"
|
||||
assert glob.switched == [version]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("described", [None, "", "latest", "latest-3-gabc1234", "0.3.60", "v0.3"],
|
||||
ids=["no tag", "nothing", "another tag", "commits after another tag", "no v", "two numbers"])
|
||||
@pytest.mark.parametrize("version", ["v0.3.61", "v9.9.9"])
|
||||
def test_without_a_release_to_compare_with_every_release_is_held(monkeypatch, described, version):
|
||||
glob = load(monkeypatch, "normal", "loopback", described)
|
||||
assert glob.task(version) == "failed"
|
||||
assert glob.switched == []
|
||||
|
||||
glob = load(monkeypatch, "weak", "personal_cloud", described)
|
||||
assert glob.task(version) == f"success-switched-{version}"
|
||||
assert glob.switched == [version]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("described", [None, "latest"], ids=["no tag", "another tag"])
|
||||
@pytest.mark.parametrize("security_level", LEVELS)
|
||||
def test_nightly_needs_no_release_to_compare_with(monkeypatch, security_level, described):
|
||||
glob = load(monkeypatch, security_level, "public", described)
|
||||
|
||||
assert glob.task("nightly") == "success-switched-nightly"
|
||||
assert glob.switched == ["nightly"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("target_version", [None, ""], ids=["no version", "an empty version"])
|
||||
@pytest.mark.parametrize("security_level", LEVELS)
|
||||
def test_an_update_without_a_version_is_as_before(monkeypatch, security_level, target_version):
|
||||
glob = load(monkeypatch, security_level, "public")
|
||||
|
||||
assert glob.task(target_version) == "skip"
|
||||
assert glob.updated == ["comfyui"]
|
||||
assert glob.switched == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("security_level", ["", "STRONG", "middle", "high+"])
|
||||
def test_a_security_level_that_is_not_one_of_the_four_allows_no_older_release(monkeypatch, security_level):
|
||||
glob = load(monkeypatch, security_level, "loopback")
|
||||
|
||||
assert glob.task("v0.3.59") == "failed"
|
||||
assert glob.task("v0.3.61") == "success-switched-v0.3.61"
|
||||
assert glob.switched == ["v0.3.61"]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def repository(tmp_path, monkeypatch):
|
||||
if shutil.which("git") is None:
|
||||
pytest.skip("git is not installed")
|
||||
# git takes its repository from these when they are set, as they are under a git hook
|
||||
for name in [name for name in os.environ if name.startswith("GIT_")]:
|
||||
monkeypatch.delenv(name)
|
||||
|
||||
def run(*args):
|
||||
subprocess.run(["git", "-C", str(tmp_path), "-c", "user.name=test", "-c", "user.email=test@example.invalid",
|
||||
"-c", "commit.gpgsign=false", *args], check=True, capture_output=True)
|
||||
|
||||
run("init", "-q")
|
||||
for release in ("v0.3.59", "v0.3.60"):
|
||||
run("commit", "-q", "--allow-empty", "-m", release)
|
||||
run("tag", release)
|
||||
return tmp_path, run
|
||||
|
||||
|
||||
def is_downgrade(path, tag):
|
||||
spec = importlib.util.spec_from_file_location("_git_compat", PACKAGE / "common/git_compat.py")
|
||||
git_compat = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(git_compat)
|
||||
core = load_functions(PACKAGE / "glob/manager_core.py", {"parse_semver", "is_comfyui_downgrade"}, {
|
||||
"re": re, "context": SimpleNamespace(comfy_path=str(path)), "open_repo": git_compat.open_repo,
|
||||
})
|
||||
return core["is_comfyui_downgrade"](tag)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("tag, older", [("v0.3.59", True), ("v0.3.60", False), ("v0.3.61", False), ("nightly", False),
|
||||
("master", True)])
|
||||
def test_in_a_repository_at_a_release_only_an_older_one_goes_back(repository, tag, older):
|
||||
path, _ = repository
|
||||
|
||||
assert is_downgrade(path, tag) is older
|
||||
|
||||
|
||||
@pytest.mark.parametrize("tag, older", [("v0.3.59", True), ("v0.3.60", True), ("v0.3.61", False), ("nightly", False)])
|
||||
def test_in_a_repository_with_a_commit_after_the_release_that_release_goes_back(repository, tag, older):
|
||||
path, run = repository
|
||||
run("commit", "-q", "--allow-empty", "-m", "after the release")
|
||||
|
||||
assert is_downgrade(path, tag) is older
|
||||
|
||||
|
||||
@pytest.mark.parametrize("tag, older", [("v0.3.59", False), ("v0.3.60", False), ("v0.3.58", True)])
|
||||
def test_in_a_repository_checked_out_at_an_earlier_release_the_later_one_does_not_go_back(repository, tag, older):
|
||||
path, run = repository
|
||||
run("checkout", "-q", "v0.3.59")
|
||||
|
||||
assert is_downgrade(path, tag) is older
|
||||
|
||||
|
||||
@pytest.mark.parametrize("tag, older", [("v0.3.60", True), ("nightly", False)])
|
||||
def test_in_a_repository_without_a_release_tag_every_release_goes_back(repository, tag, older):
|
||||
path, run = repository
|
||||
run("tag", "-d", "v0.3.59", "v0.3.60")
|
||||
|
||||
assert is_downgrade(path, tag) is older
|
||||
@@ -0,0 +1,129 @@
|
||||
import logging
|
||||
|
||||
import pytest
|
||||
|
||||
from _install_flags_testutil import import_context, import_reader
|
||||
|
||||
VALUES = {
|
||||
"security_level": ["normal", "strong", "normal-", "weak"],
|
||||
"network_mode": ["public", "private", "offline", "personal_cloud"],
|
||||
"db_mode": ["cache", "channel", "local", "remote"],
|
||||
"update_policy": ["stable-comfyui", "nightly-comfyui", "stable", "nightly"],
|
||||
}
|
||||
NON_DEFAULT = {key: values[1] for key, values in VALUES.items()}
|
||||
DEFAULTS = {key: values[0] for key, values in VALUES.items()}
|
||||
|
||||
|
||||
@pytest.fixture(params=["glob", "legacy"])
|
||||
def read(request, monkeypatch, tmp_path, caplog):
|
||||
core = import_reader(request.param)
|
||||
path = tmp_path / "config.ini"
|
||||
monkeypatch.setattr(import_context(), "manager_config_path", str(path))
|
||||
monkeypatch.setattr(core, "cached_config", None)
|
||||
|
||||
def read_text(written, changes=()):
|
||||
if written is not None:
|
||||
path.write_bytes(written if isinstance(written, bytes) else written.encode("utf-8"))
|
||||
caplog.clear()
|
||||
with caplog.at_level(logging.WARNING):
|
||||
settings = dict(core.get_config())
|
||||
for key, value in changes:
|
||||
core.get_config()[key] = value
|
||||
if changes:
|
||||
core.write_config()
|
||||
warnings = "\n".join(record.getMessage() for record in caplog.records)
|
||||
return settings, warnings, path.read_bytes() if path.exists() else None
|
||||
|
||||
return read_text
|
||||
|
||||
|
||||
def section(settings):
|
||||
return "[default]\n" + "".join(f"{key} = {value}\n" for key, value in settings.items())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", ["100%", "%(downgrade_blacklist)s", "%", "bogus", "weak,normal", "<b>weak</b>", "nor mal",
|
||||
"[/x]", "[bold]weak", "cache[/]"])
|
||||
@pytest.mark.parametrize("key", sorted(VALUES))
|
||||
def test_a_value_that_a_setting_cannot_have_gives_its_default_and_changes_no_other_setting(read, key, value):
|
||||
text = section({**NON_DEFAULT, key: value, "downgrade_blacklist": "kornia"})
|
||||
|
||||
settings, printed, file = read(text)
|
||||
|
||||
assert {name: settings[name] for name in VALUES} == {**NON_DEFAULT, key: DEFAULTS[key]}
|
||||
assert settings["downgrade_blacklist"] == "kornia"
|
||||
assert f"{key} = {value!r} in config.ini is not valid; '{DEFAULTS[key]}' is used." in printed
|
||||
assert file == text.encode("utf-8")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key", sorted(VALUES))
|
||||
def test_a_value_that_a_setting_cannot_have_stays_in_config_ini_when_another_setting_is_saved(read, key):
|
||||
text = section({**NON_DEFAULT, key: "bogus"})
|
||||
|
||||
_, _, file = read(text, changes=[("share_option", "none")])
|
||||
|
||||
assert f"{key} = bogus\n".encode() in file
|
||||
assert b"share_option = none\n" in file
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key, value", [(key, value) for key, values in sorted(VALUES.items()) for value in values])
|
||||
@pytest.mark.parametrize("written", [str.lower, str.upper], ids=["lower case", "upper case"])
|
||||
def test_a_value_that_a_setting_can_have_is_read_and_nothing_is_said(read, key, value, written):
|
||||
settings, printed, _ = read(section({key: written(value)}))
|
||||
|
||||
assert settings[key] == value
|
||||
assert printed == ""
|
||||
|
||||
|
||||
def test_a_config_ini_without_these_settings_has_their_defaults_and_nothing_is_said(read):
|
||||
settings, printed, _ = read(section({"file_logging": "True"}))
|
||||
|
||||
assert {name: settings[name] for name in VALUES} == DEFAULTS
|
||||
assert printed == ""
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key, value", [
|
||||
("downgrade_blacklist", "100%"), ("downgrade_blacklist", "%(security_level)s"), ("git_exe", "/opt/100%/git"),
|
||||
("channel_url", "https://example.invalid/some%20one/channel"), ("channel_url", "%"), ("git_exe", "/opt/100%%/git"),
|
||||
], ids=["a percent sign", "the form of a reference", "a path", "a percent-encoded url", "only a percent sign",
|
||||
"two percent signs"])
|
||||
def test_a_percent_sign_is_plain_text_and_the_other_settings_are_read(read, key, value):
|
||||
text = section({**NON_DEFAULT, key: value})
|
||||
|
||||
settings, printed, file = read(text)
|
||||
|
||||
assert settings[key] == value
|
||||
assert {name: settings[name] for name in VALUES} == NON_DEFAULT
|
||||
assert printed == ""
|
||||
assert file == text.encode("utf-8")
|
||||
|
||||
|
||||
def test_a_setting_is_written_beside_a_value_with_a_percent_sign_and_one_with_it_is_written(read):
|
||||
text = section({"security_level": "strong", "downgrade_blacklist": "100%"})
|
||||
|
||||
_, _, file = read(text, changes=[("db_mode", "local"), ("channel_url", "https://example.invalid/some%20one/channel")])
|
||||
|
||||
for line in (b"security_level = strong\n", b"downgrade_blacklist = 100%\n", b"db_mode = local\n",
|
||||
b"channel_url = https://example.invalid/some%20one/channel\n"):
|
||||
assert line in file
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", ["security_level = strong\n", "\ufeff[default]\nsecurity_level = strong\n",
|
||||
"[default\nsecurity_level = strong\n", "[other]\nsecurity_level = strong\n", "",
|
||||
"[default]\nsecurity_level = strong\nnot a setting [/x]\n",
|
||||
b"[default]\nsecurity_level = strong\ngit_exe = \xff\xfe\n"],
|
||||
ids=["no section", "a byte order mark", "an unclosed section", "no default section", "empty",
|
||||
"a line that is not a setting", "bytes that are not text"])
|
||||
def test_a_config_ini_that_cannot_be_read_gives_the_defaults_and_says_so(read, text):
|
||||
settings, printed, file = read(text)
|
||||
|
||||
assert {name: settings[name] for name in VALUES} == DEFAULTS
|
||||
assert "could not be read" in printed and "the default settings are used" in printed
|
||||
assert file == (text if isinstance(text, bytes) else text.encode("utf-8"))
|
||||
|
||||
|
||||
def test_without_a_config_ini_the_defaults_are_used_and_nothing_is_said(read):
|
||||
settings, printed, file = read(None)
|
||||
|
||||
assert {name: settings[name] for name in VALUES} == DEFAULTS
|
||||
assert printed == ""
|
||||
assert file is None
|
||||
@@ -0,0 +1,47 @@
|
||||
"""`print` of the two `manager_core` modules writes its text as it is.
|
||||
|
||||
The cases take what binds the name `print` out of a `manager_core.py`, an
|
||||
import or a function, and call it.
|
||||
"""
|
||||
import ast
|
||||
import io
|
||||
|
||||
import pytest
|
||||
|
||||
from legacy_html_testutil import PACKAGE
|
||||
|
||||
|
||||
@pytest.fixture(params=["glob", "legacy"])
|
||||
def printed(request):
|
||||
source = (PACKAGE / request.param / "manager_core.py").read_text(encoding="utf-8")
|
||||
nodes = [node for node in ast.parse(source).body
|
||||
if isinstance(node, (ast.Import, ast.ImportFrom)) and "rich" in ast.unparse(node)
|
||||
or isinstance(node, ast.FunctionDef) and node.name == "print"]
|
||||
namespace = {}
|
||||
exec(compile(ast.Module(body=nodes, type_ignores=[]), "<manager_core print>", "exec"), namespace)
|
||||
|
||||
def printed(*objects, **options):
|
||||
out = io.StringIO()
|
||||
namespace["print"](*objects, file=out, **options)
|
||||
return out.getvalue()
|
||||
|
||||
return printed
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", [
|
||||
"Install(git-clone) error: https://example.com/a[/b] / failed",
|
||||
"## ComfyUI-Manager: EXECUTE => ['python', '-m', 'pip', 'install', 'diffusers[torch]']",
|
||||
"skip black listed pip installation: 'requests[socks]'",
|
||||
"Uninstall: custom_nodes/pack:100:backup",
|
||||
"Download: git clone 'https://github.com/" + "a" * 120 + "'",
|
||||
], ids=["closing tag", "list with an extra", "extra", "emoji code", "longer than 80 columns"])
|
||||
def test_text_is_written_as_it_is(printed, text):
|
||||
assert printed(text) == text + "\n"
|
||||
|
||||
|
||||
def test_objects_are_written_as_their_text(printed):
|
||||
assert printed("Update error:", ValueError("no section [/x]"), 3) == "Update error: no section [/x] 3\n"
|
||||
|
||||
|
||||
def test_end_and_sep_are_kept(printed):
|
||||
assert printed("a", "b", sep="-", end="") == "a-b"
|
||||
@@ -0,0 +1,177 @@
|
||||
import ast
|
||||
import asyncio
|
||||
import functools
|
||||
import importlib.util
|
||||
import logging
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from packaging import version
|
||||
|
||||
from legacy_html_testutil import PACKAGE, load_functions
|
||||
|
||||
LEVELS = ["strong", "normal", "normal-", "weak"]
|
||||
LISTENERS = ["loopback", "personal_cloud", "public"]
|
||||
METHODS = frozenset({"is_enabled", "get_cnr_active_version", "is_unknown_active", "resolve_unspecified_version",
|
||||
"get_from_cnr_active_nodes", "get_from_cnr_inactive_nodes", "safe_version"})
|
||||
|
||||
CNR_ENABLED_NIGHTLY_DISABLED = dict(active={"pack": ("1.0.0", "custom_nodes/pack")},
|
||||
nightly_inactive={"pack": "custom_nodes/.disabled/pack@nightly"})
|
||||
|
||||
|
||||
def nightly_install_allowed(security_level, listener):
|
||||
return security_level != "strong" and listener != "public"
|
||||
|
||||
|
||||
@functools.lru_cache
|
||||
def normalized_key_dict(server):
|
||||
source = (PACKAGE / server / "manager_core.py").read_text(encoding="utf-8")
|
||||
classes = [node for node in ast.parse(source).body if isinstance(node, ast.ClassDef) and node.name == "NormalizedKeyDict"]
|
||||
namespace = {}
|
||||
exec(compile(ast.Module(classes, []), "manager_core.py", "exec"), namespace)
|
||||
return namespace["NormalizedKeyDict"]
|
||||
|
||||
|
||||
@functools.lru_cache
|
||||
def functions_named(path, names):
|
||||
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]
|
||||
assert len(nodes) == len(names)
|
||||
namespace = {"version": version}
|
||||
exec(compile(ast.Module(nodes, []), str(path), "exec"), namespace)
|
||||
return {name: namespace[name] for name in names}
|
||||
|
||||
|
||||
def load(monkeypatch, server, security_level, listener, active=None, nightly_inactive=None, cnr_inactive=None,
|
||||
unknown_active=None, unknown_inactive=None):
|
||||
enabled = []
|
||||
package = PACKAGE / server
|
||||
manager = type("UnifiedManager", (), functions_named(package / "manager_core.py", METHODS))()
|
||||
|
||||
def packs(items, normalized=server == "glob"):
|
||||
if not normalized:
|
||||
return dict(items or {})
|
||||
kept = normalized_key_dict(server)()
|
||||
for key, value in (items or {}).items():
|
||||
kept[key] = value
|
||||
return kept
|
||||
|
||||
manager.cnr_map = packs({"pack": {"latest_version": {"version": "1.0.0"}}}, normalized=True)
|
||||
manager.active_nodes = packs(active)
|
||||
manager.nightly_inactive_nodes = packs(nightly_inactive)
|
||||
manager.cnr_inactive_nodes = packs(cnr_inactive)
|
||||
manager.unknown_active_nodes = unknown_active or {}
|
||||
manager.unknown_inactive_nodes = unknown_inactive or {}
|
||||
manager.unified_enable = enabled.append
|
||||
core = SimpleNamespace(
|
||||
unified_manager=manager,
|
||||
get_config=lambda: {"security_level": security_level,
|
||||
"network_mode": "personal_cloud" if listener == "personal_cloud" else "public"},
|
||||
)
|
||||
namespace = {"logging": logging, "core": core, "SECURITY_MESSAGE_MIDDLE_P": ""}
|
||||
|
||||
if server == "glob":
|
||||
spec = importlib.util.spec_from_file_location("_generated_models", PACKAGE / "data_models/generated_models.py")
|
||||
models = importlib.util.module_from_spec(spec)
|
||||
monkeypatch.setitem(sys.modules, spec.name, models)
|
||||
spec.loader.exec_module(models)
|
||||
security = load_functions(package / "utils/security_utils.py", {"is_allowed_security_level"}, {
|
||||
"core": core, "args": SimpleNamespace(listen="127.0.0.1" if listener == "loopback" else "0.0.0.0"),
|
||||
"is_loopback": load_functions(PACKAGE / "common/manager_security.py", {"is_loopback"})["is_loopback"],
|
||||
"SecurityLevel": models.SecurityLevel, "RiskLevel": models.RiskLevel,
|
||||
})
|
||||
namespace.update(security_utils=SimpleNamespace(**security), OperationResult=models.OperationResult,
|
||||
EnablePackParams=models.EnablePackParams)
|
||||
item = lambda node_id: models.EnablePackParams(cnr_id=node_id) # noqa: E731
|
||||
else:
|
||||
namespace["is_local_mode"] = load_functions(package / "manager_server.py", {"is_loopback"})["is_loopback"](
|
||||
"127.0.0.1" if listener == "loopback" else "0.0.0.0")
|
||||
item = lambda node_id: ("ui", node_id) # noqa: E731
|
||||
|
||||
path = package / "manager_server.py"
|
||||
names = {"do_enable", "replaces_cnr_with_nightly"} | ({"is_allowed_security_level"} if server == "legacy" else set())
|
||||
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]
|
||||
assert len(nodes) == len(names)
|
||||
exec(compile(ast.Module(nodes, []), str(path), "exec"), namespace)
|
||||
|
||||
def enable(node_id="pack"):
|
||||
return asyncio.run(namespace["do_enable"](item(node_id)))
|
||||
|
||||
return SimpleNamespace(enable=enable, enabled=enabled)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("server", ["glob", "legacy"])
|
||||
@pytest.mark.parametrize("listener", LISTENERS)
|
||||
@pytest.mark.parametrize("security_level", LEVELS)
|
||||
def test_a_nightly_in_the_place_of_a_registry_version_needs_the_level_of_a_nightly_install(monkeypatch, server, security_level, listener):
|
||||
worker = load(monkeypatch, server, security_level, listener, **CNR_ENABLED_NIGHTLY_DISABLED)
|
||||
|
||||
result = worker.enable()
|
||||
|
||||
if nightly_install_allowed(security_level, listener):
|
||||
assert result == "success"
|
||||
assert worker.enabled == ["pack"]
|
||||
else:
|
||||
assert result == "failed"
|
||||
assert worker.enabled == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("server", ["glob", "legacy"])
|
||||
@pytest.mark.parametrize("listener", LISTENERS)
|
||||
@pytest.mark.parametrize("security_level", LEVELS)
|
||||
@pytest.mark.parametrize("versions", [
|
||||
dict(nightly_inactive={"pack": "custom_nodes/.disabled/pack@nightly"}),
|
||||
dict(cnr_inactive={"pack": {"1.0.0": "custom_nodes/.disabled/pack@1_0_0"}}),
|
||||
dict(active={"pack": ("nightly", "custom_nodes/pack")},
|
||||
cnr_inactive={"pack": {"1.0.0": "custom_nodes/.disabled/pack@1_0_0"}}),
|
||||
dict(active={"pack": ("1.0.0", "custom_nodes/pack")},
|
||||
cnr_inactive={"pack": {"0.9.0": "custom_nodes/.disabled/pack@0_9_0"}},
|
||||
nightly_inactive={"pack": "custom_nodes/.disabled/pack@nightly"}),
|
||||
dict(active={"pack": ("1.0.0", "custom_nodes/pack")}),
|
||||
dict(active={"pack": ("nightly", "custom_nodes/pack")}),
|
||||
dict(unknown_inactive={"pack": ("https://example.com/pack", "custom_nodes/.disabled/pack")}),
|
||||
dict(),
|
||||
], ids=["a disabled nightly, nothing enabled", "a disabled registry version, nothing enabled",
|
||||
"a registry version in the place of a nightly", "another registry version, with a nightly disabled too",
|
||||
"a registry version enabled, nothing disabled", "a nightly enabled, nothing disabled",
|
||||
"a disabled pack without a version", "a pack that is not installed"])
|
||||
def test_another_enable_is_not_held_to_a_level(monkeypatch, server, security_level, listener, versions):
|
||||
worker = load(monkeypatch, server, security_level, listener, **versions)
|
||||
|
||||
assert worker.enable() == "success"
|
||||
assert worker.enabled == ["pack"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("server", ["glob", "legacy"])
|
||||
@pytest.mark.parametrize("node_id", ["other", "pack@nightly", "pack2", ""],
|
||||
ids=["another pack", "with a version", "a longer name", "empty"])
|
||||
def test_a_pack_that_the_manager_does_not_know_is_not_held_to_a_level(monkeypatch, server, node_id):
|
||||
worker = load(monkeypatch, server, "strong", "public", **CNR_ENABLED_NIGHTLY_DISABLED)
|
||||
|
||||
assert worker.enable(node_id) == "success"
|
||||
assert worker.enabled == [node_id]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("listener", LISTENERS)
|
||||
@pytest.mark.parametrize("security_level", LEVELS)
|
||||
@pytest.mark.parametrize("node_id", ["Pack", "PACK", "pack ", " pack"],
|
||||
ids=["capitalized", "upper case", "trailing space", "leading space"])
|
||||
def test_the_glob_server_holds_the_pack_to_the_level_however_its_name_is_written(monkeypatch, security_level, listener, node_id):
|
||||
worker = load(monkeypatch, "glob", security_level, listener, **CNR_ENABLED_NIGHTLY_DISABLED)
|
||||
|
||||
result = worker.enable(node_id)
|
||||
|
||||
if nightly_install_allowed(security_level, listener):
|
||||
assert (result, worker.enabled) == ("success", [node_id])
|
||||
else:
|
||||
assert (result, worker.enabled) == ("failed", [])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("node_id", ["Pack", "pack "], ids=["capitalized", "trailing space"])
|
||||
def test_to_the_legacy_server_a_name_written_otherwise_is_another_pack(monkeypatch, node_id):
|
||||
worker = load(monkeypatch, "legacy", "strong", "public", **CNR_ENABLED_NIGHTLY_DISABLED)
|
||||
|
||||
assert worker.enable(node_id) == "success"
|
||||
assert worker.enabled == [node_id]
|
||||
@@ -380,7 +380,8 @@ def test_preflight_response_is_reused(core, monkeypatch, installed, instant, tmp
|
||||
(marker.parent / '.tracking').write_text('__init__.py')
|
||||
|
||||
def download(url, directory, name):
|
||||
(tmp_path / name).write_bytes(b'fixture')
|
||||
with zipfile.ZipFile(tmp_path / name, 'w') as archive:
|
||||
archive.writestr('__init__.py', '')
|
||||
|
||||
def extract(archive, directory):
|
||||
(Path(directory) / '__init__.py').write_text('replacement')
|
||||
@@ -557,7 +558,8 @@ def test_deferred_switch_reuses_status_with_current_policy(
|
||||
(from_path / '__init__.py').write_text('')
|
||||
|
||||
def download(url, directory, name):
|
||||
(Path(directory) / name).write_bytes(b'fixture')
|
||||
with zipfile.ZipFile(Path(directory) / name, 'w') as archive:
|
||||
archive.writestr('__init__.py', '')
|
||||
|
||||
downloader = Mock(side_effect=download)
|
||||
monkeypatch.setattr(manager_downloader, 'download_url', downloader)
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
import git
|
||||
import pytest
|
||||
|
||||
from _install_flags_testutil import GIT_LOCATION
|
||||
from test_snapshot_restore_pins import core # noqa: F401
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def git_finds_its_repository_by_the_directory(monkeypatch):
|
||||
for name in GIT_LOCATION:
|
||||
monkeypatch.delenv(name, raising=False)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def manager_clones_from_a_directory(monkeypatch):
|
||||
monkeypatch.setenv('GIT_CONFIG_COUNT', '1')
|
||||
monkeypatch.setenv('GIT_CONFIG_KEY_0', 'protocol.file.allow')
|
||||
monkeypatch.setenv('GIT_CONFIG_VALUE_0', 'always')
|
||||
|
||||
|
||||
def head(path):
|
||||
return subprocess.run(['git', 'rev-parse', 'HEAD'], cwd=path, check=True, capture_output=True, text=True).stdout.strip()
|
||||
|
||||
|
||||
def repository(path):
|
||||
path.mkdir(parents=True)
|
||||
commits = []
|
||||
for version in (1, 2):
|
||||
(path / '__init__.py').write_text('VERSION = %d' % version)
|
||||
for args in (['init', '-q'], ['add', '.'],
|
||||
['-c', 'user.name=test', '-c', 'user.email=test@example.invalid', 'commit', '-q', '-m', 'version %d' % version]):
|
||||
subprocess.run(['git', *args], cwd=path, check=True, capture_output=True)
|
||||
commits.append(head(path))
|
||||
return commits
|
||||
|
||||
|
||||
def git_with_local_submodules(path, *args):
|
||||
subprocess.run(['git', '-c', 'protocol.file.allow=always', '-c', 'user.name=test', '-c', 'user.email=test@example.invalid', *args],
|
||||
cwd=path, check=True, capture_output=True)
|
||||
|
||||
|
||||
def repository_with_a_submodule(tmp_path):
|
||||
library = repository(tmp_path / 'library')
|
||||
origin = tmp_path / 'origin'
|
||||
origin.mkdir()
|
||||
git_with_local_submodules(origin, 'init', '-q')
|
||||
git_with_local_submodules(origin, 'submodule', 'add', '-q', str(tmp_path / 'library'), 'library')
|
||||
pinned_commits = []
|
||||
for commit in library:
|
||||
git_with_local_submodules(origin / 'library', 'checkout', '-q', commit)
|
||||
git_with_local_submodules(origin, 'commit', '-q', '-a', '-m', 'library at ' + commit)
|
||||
pinned_commits.append(head(origin))
|
||||
return library, pinned_commits
|
||||
|
||||
|
||||
def test_ref_that_head_names_is_read(core, tmp_path): # noqa: F811
|
||||
commits = repository(tmp_path / 'fixture')
|
||||
head_file = tmp_path / 'fixture/.git/HEAD'
|
||||
branch = head_file.read_text().strip()[5:]
|
||||
|
||||
assert core.git_utils.get_commit_hash(str(tmp_path / 'fixture')) == commits[1]
|
||||
|
||||
head_file.write_text('ref:' + branch + '\n')
|
||||
assert core.git_utils.get_commit_hash(str(tmp_path / 'fixture')) == commits[1]
|
||||
|
||||
head_file.write_text('ref: \n')
|
||||
assert core.git_utils.get_commit_hash(str(tmp_path / 'fixture')) == 'unknown'
|
||||
|
||||
|
||||
def test_commit_of_a_pack_whose_refs_are_packed_is_read(core, tmp_path): # noqa: F811
|
||||
commits = repository(tmp_path / 'fixture')
|
||||
subprocess.run(['git', 'pack-refs', '--all'], cwd=tmp_path / 'fixture', check=True)
|
||||
with open(tmp_path / 'fixture/.git/packed-refs', 'a') as packed:
|
||||
packed.write('\n')
|
||||
branch = (tmp_path / 'fixture/.git/HEAD').read_text().strip()[5:]
|
||||
|
||||
assert not (tmp_path / 'fixture/.git' / branch).exists()
|
||||
assert core.git_utils.get_commit_hash(str(tmp_path / 'fixture')) == commits[1]
|
||||
|
||||
|
||||
def test_ref_whose_place_is_a_folder_is_not_read_as_a_file(core, tmp_path): # noqa: F811
|
||||
"""git takes a folder there for no ref: after `git pack-refs`, and after `git checkout --orphan feature` beside a branch `feature/x`."""
|
||||
commits = repository(tmp_path / 'fixture')
|
||||
subprocess.run(['git', 'pack-refs', '--all'], cwd=tmp_path / 'fixture', check=True)
|
||||
branch = (tmp_path / 'fixture/.git/HEAD').read_text().strip()[5:]
|
||||
(tmp_path / 'fixture/.git' / branch).mkdir(parents=True)
|
||||
|
||||
assert core.git_utils.get_commit_hash(str(tmp_path / 'fixture')) == commits[1]
|
||||
|
||||
subprocess.run(['git', 'branch', 'feature/x'], cwd=tmp_path / 'fixture', check=True)
|
||||
subprocess.run(['git', 'checkout', '-q', '--orphan', 'feature'], cwd=tmp_path / 'fixture', check=True)
|
||||
|
||||
assert core.git_utils.get_commit_hash(str(tmp_path / 'fixture')) == 'unknown'
|
||||
|
||||
|
||||
def test_commit_that_is_not_ascii_is_read_without_an_error(core, tmp_path): # noqa: F811
|
||||
repository(tmp_path / 'fixture')
|
||||
git_dir = tmp_path / 'fixture/.git'
|
||||
branch = (git_dir / 'HEAD').read_text().strip()[5:]
|
||||
subprocess.run(['git', 'pack-refs', '--all'], cwd=tmp_path / 'fixture', check=True)
|
||||
(git_dir / 'packed-refs').write_bytes(b'0123\xff ' + branch.encode() + b'\n')
|
||||
|
||||
assert core.git_utils.get_commit_hash(str(tmp_path / 'fixture')) == '0123\ufffd'
|
||||
|
||||
(git_dir / branch).write_bytes(b'0123\xff\n')
|
||||
assert core.git_utils.get_commit_hash(str(tmp_path / 'fixture')) == '0123\ufffd'
|
||||
|
||||
(git_dir / 'HEAD').write_bytes(b'0123\xff\n')
|
||||
assert core.git_utils.get_commit_hash(str(tmp_path / 'fixture')) == '0123\ufffd'
|
||||
|
||||
|
||||
def test_head_that_cannot_be_opened_has_no_commit(core, tmp_path): # noqa: F811
|
||||
(tmp_path / 'fixture/.git/HEAD').mkdir(parents=True)
|
||||
|
||||
assert core.git_utils.get_commit_hash(str(tmp_path / 'fixture')) == 'unknown'
|
||||
|
||||
|
||||
def test_files_that_may_not_be_read_have_no_commit(core, tmp_path): # noqa: F811
|
||||
(tmp_path / 'probe').touch()
|
||||
(tmp_path / 'probe').chmod(0)
|
||||
try:
|
||||
open(tmp_path / 'probe').close()
|
||||
except OSError:
|
||||
pass
|
||||
else:
|
||||
pytest.skip('a file can be read here whatever its mode, as by root or on Windows')
|
||||
|
||||
commits = repository(tmp_path / 'fixture')
|
||||
git_dir = tmp_path / 'fixture/.git'
|
||||
subprocess.run(['git', 'pack-refs', '--all'], cwd=tmp_path / 'fixture', check=True)
|
||||
branch = (git_dir / 'HEAD').read_text().strip()[5:]
|
||||
|
||||
(git_dir / 'packed-refs').chmod(0)
|
||||
assert core.git_utils.get_commit_hash(str(tmp_path / 'fixture')) == 'unknown'
|
||||
|
||||
(git_dir / branch).write_text(commits[1])
|
||||
(git_dir / branch).chmod(0)
|
||||
assert core.git_utils.get_commit_hash(str(tmp_path / 'fixture')) == 'unknown'
|
||||
|
||||
(git_dir / 'HEAD').chmod(0)
|
||||
assert core.git_utils.get_commit_hash(str(tmp_path / 'fixture')) == 'unknown'
|
||||
|
||||
|
||||
def test_commit_is_read_beside_refs_that_are_not_utf8(core, tmp_path): # noqa: F811
|
||||
commits = repository(tmp_path / 'fixture')
|
||||
subprocess.run(['git', 'pack-refs', '--all'], cwd=tmp_path / 'fixture', check=True)
|
||||
packed = tmp_path / 'fixture/.git/packed-refs'
|
||||
packed.write_bytes(b'0123456789abcdef0123456789abcdef01234567 refs/heads/\xff\xfe\n' + packed.read_bytes())
|
||||
|
||||
assert core.git_utils.get_commit_hash(str(tmp_path / 'fixture')) == commits[1]
|
||||
|
||||
|
||||
def test_head_that_is_not_utf8_is_read(core, tmp_path): # noqa: F811
|
||||
heads = tmp_path / 'fixture/.git/refs/heads'
|
||||
heads.mkdir(parents=True)
|
||||
(tmp_path / 'fixture/.git/HEAD').write_bytes(b'ref: refs/heads/\xff\xfe\n')
|
||||
try:
|
||||
with open(os.fsencode(heads) + b'/\xff\xfe', 'wb') as ref:
|
||||
ref.write(b'0123456789abcdef0123456789abcdef01234567\n')
|
||||
except (OSError, ValueError):
|
||||
pytest.skip('this file system has no file of such a name, as that of Windows')
|
||||
|
||||
assert core.git_utils.get_commit_hash(str(tmp_path / 'fixture')) == '0123456789abcdef0123456789abcdef01234567'
|
||||
|
||||
|
||||
# what MinGit 2.56 named the file of a branch that was cloned on Windows
|
||||
NAMES_OF_GIT_FOR_WINDOWS = [
|
||||
(b'rel-\xfe', 'rel-\u00fe'),
|
||||
(b'caf\xe9', 'caf\u00e9'),
|
||||
(b'rel-\x81', 'rel-81'),
|
||||
('\ud55c\uae00'.encode(), '\ud55c\uae00'),
|
||||
('\ud55c'.encode() + b'\xfe\xe9\xc3', '\ud55c\u00fe\u00e9\u00c3'),
|
||||
('a\U0001f600'.encode(), 'a\U0001f600'),
|
||||
(b'\xe0\x80\x80', '\u00e08080'),
|
||||
# a surrogate in UTF-8, which `xutftowcsn` of compat/mingw.c of git takes as one
|
||||
(b'\xed\xa0\x80', '\ud800'),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('name, file_name', NAMES_OF_GIT_FOR_WINDOWS)
|
||||
def test_file_of_a_ref_is_named_as_git_for_windows_names_it(core, name, file_name): # noqa: F811
|
||||
assert core.git_utils.file_name_of_git_for_windows(name) == file_name
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != 'nt', reason='the names that Git for Windows gives its files')
|
||||
def test_ref_that_git_for_windows_made_is_read(core, tmp_path): # noqa: F811
|
||||
"""A name that is not UTF-8 is no name of a file there, and Git for Windows writes the file under another."""
|
||||
heads = tmp_path / 'fixture/.git/refs/heads'
|
||||
heads.mkdir(parents=True)
|
||||
(tmp_path / 'fixture/.git/HEAD').write_bytes(b'ref: refs/heads/rel-\xfe\n')
|
||||
(heads / 'rel-\u00fe').write_text('0123456789abcdef0123456789abcdef01234567\n')
|
||||
|
||||
assert core.git_utils.get_commit_hash(str(tmp_path / 'fixture')) == '0123456789abcdef0123456789abcdef01234567'
|
||||
|
||||
|
||||
def test_packed_ref_is_matched_by_its_bytes(core, tmp_path): # noqa: F811
|
||||
commits = repository(tmp_path / 'fixture')
|
||||
subprocess.run(['git', 'pack-refs', '--all'], cwd=tmp_path / 'fixture', check=True)
|
||||
git_dir = tmp_path / 'fixture/.git'
|
||||
other = b'0123456789abcdef0123456789abcdef01234567 refs/heads/release-\xff\n'
|
||||
(git_dir / 'packed-refs').write_bytes(other + (git_dir / 'packed-refs').read_bytes())
|
||||
(git_dir / 'HEAD').write_bytes(b'ref: refs/heads/release-\xfe\n')
|
||||
|
||||
assert core.git_utils.get_commit_hash(str(tmp_path / 'fixture')) == 'unknown'
|
||||
|
||||
(git_dir / 'packed-refs').write_bytes(other + commits[1].encode() + b' refs/heads/release-\xfe\n')
|
||||
|
||||
assert core.git_utils.get_commit_hash(str(tmp_path / 'fixture')) == commits[1]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('clone', [['--recursive'], []], ids=['with its submodules', 'without its submodules'])
|
||||
def test_checkout_brings_the_submodules_to_the_commit(core, manager_clones_from_a_directory, tmp_path, clone): # noqa: F811
|
||||
library, pinned_commits = repository_with_a_submodule(tmp_path)
|
||||
git_with_local_submodules(tmp_path, 'clone', '-q', *clone, str(tmp_path / 'origin'), 'fixture')
|
||||
|
||||
assert core.repo_switch_commit(str(tmp_path / 'fixture'), pinned_commits[0]) is True
|
||||
assert head(tmp_path / 'fixture') == pinned_commits[0]
|
||||
assert head(tmp_path / 'fixture/library') == library[0]
|
||||
|
||||
|
||||
def test_submodules_are_brought_to_the_commit_of_a_pack_that_is_at_it_already(core, tmp_path): # noqa: F811
|
||||
library, pinned_commits = repository_with_a_submodule(tmp_path)
|
||||
git_with_local_submodules(tmp_path, 'clone', '-q', '--recursive', str(tmp_path / 'origin'), 'fixture')
|
||||
git_with_local_submodules(tmp_path / 'fixture/library', 'checkout', '-q', library[0])
|
||||
|
||||
assert core.repo_switch_commit(str(tmp_path / 'fixture'), pinned_commits[1]) is False
|
||||
assert head(tmp_path / 'fixture/library') == library[1]
|
||||
|
||||
|
||||
def test_submodule_that_was_never_fetched_is_left_alone_in_a_pack_cloned_without_its_submodules(core, tmp_path): # noqa: F811
|
||||
"""As git does without `--init`: no submodule of such a clone is active."""
|
||||
library, pinned_commits = repository_with_a_submodule(tmp_path)
|
||||
git_with_local_submodules(tmp_path, 'clone', '-q', str(tmp_path / 'origin'), 'fixture')
|
||||
# moved, as git makes files read-only that Windows does not remove
|
||||
(tmp_path / 'library').rename(tmp_path / 'library.away')
|
||||
|
||||
assert core.repo_switch_commit(str(tmp_path / 'fixture'), pinned_commits[1]) is False
|
||||
assert list((tmp_path / 'fixture/library').iterdir()) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize('reachable', [True, False], ids=['reachable', 'away'])
|
||||
def test_submodule_that_was_never_fetched_is_fetched_in_a_pack_cloned_as_manager_clones(core, manager_clones_from_a_directory, tmp_path, # noqa: F811
|
||||
caplog, reachable):
|
||||
"""`clone --recursive` makes every submodule active, also one of a later commit: git updates it without `--init`."""
|
||||
repository(tmp_path / 'library')
|
||||
plain, pack = tmp_path / 'plain', tmp_path / 'fixture'
|
||||
plain.mkdir()
|
||||
git_with_local_submodules(plain, 'init', '-q')
|
||||
git_with_local_submodules(plain, 'commit', '-q', '--allow-empty', '-m', 'no submodule')
|
||||
git_with_local_submodules(tmp_path, 'clone', '-q', '--recursive', str(plain), str(pack))
|
||||
git_with_local_submodules(plain, 'submodule', 'add', '-q', str(tmp_path / 'library'), 'library')
|
||||
git_with_local_submodules(plain, 'commit', '-q', '-m', 'a submodule')
|
||||
git_with_local_submodules(pack, 'pull', '-q')
|
||||
if not reachable:
|
||||
# moved, as git makes files read-only that Windows does not remove
|
||||
(tmp_path / 'library').rename(tmp_path / 'library.away')
|
||||
|
||||
with caplog.at_level(logging.ERROR):
|
||||
switched = core.repo_switch_commit(str(pack), head(plain))
|
||||
|
||||
assert (switched, (pack / 'library/__init__.py').exists(), f"'{pack}'" in caplog.text, 'library' in caplog.text) == \
|
||||
((False, True, False, False) if reachable else (None, False, True, True))
|
||||
|
||||
|
||||
def test_git_is_not_run_for_the_submodules_of_a_pack_that_has_none(core, tmp_path, monkeypatch): # noqa: F811
|
||||
commits = repository(tmp_path / 'fixture')
|
||||
ran = []
|
||||
execute = git.Git.execute
|
||||
|
||||
def recorded(self, command, *args, **kwargs):
|
||||
ran.append(list(command))
|
||||
return execute(self, command, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(git.Git, 'execute', recorded)
|
||||
|
||||
assert core.repo_switch_commit(str(tmp_path / 'fixture'), commits[1]) is False
|
||||
assert [command for command in ran if 'submodule' in command] == []
|
||||
@@ -578,6 +578,28 @@ finally:
|
||||
self.assertTrue(p2['detached'])
|
||||
self.assertTrue(p2['not_head'])
|
||||
|
||||
def test_checkout_head_by_name(self):
|
||||
# The head of a branch, as get_head_by_name gives it, checks that branch out
|
||||
head = self.head_sha
|
||||
snippet = f"""
|
||||
import tempfile, shutil
|
||||
dest = tempfile.mkdtemp()
|
||||
try:
|
||||
repo = clone_repo(REPO_PATH, os.path.join(dest, 'cloned'))
|
||||
repo.checkout('v1.0.0')
|
||||
repo.checkout(repo.get_head_by_name('master'))
|
||||
result = {{"branch": repo.active_branch_name, "detached": repo.head_is_detached,
|
||||
"at_head": repo.head_commit_hexsha == {head!r}}}
|
||||
repo.close()
|
||||
print(json.dumps(result))
|
||||
finally:
|
||||
shutil.rmtree(dest, ignore_errors=True)
|
||||
"""
|
||||
gp, p2 = _run_both(snippet, self.repo_path)
|
||||
expected = {"branch": "master", "detached": False, "at_head": True}
|
||||
self.assertEqual(gp, expected)
|
||||
self.assertEqual(p2, expected)
|
||||
|
||||
# === checkout_new_branch ===
|
||||
|
||||
def test_checkout_new_branch(self):
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
import configparser
|
||||
import importlib.util
|
||||
import logging
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from legacy_html_testutil import PACKAGE, load_functions
|
||||
|
||||
URL = "https://github.com/someone/some%20pack"
|
||||
PLAIN = '[core]\n\tbare = false\n[remote "origin"]\n\turl = https://github.com/someone/pack\n'
|
||||
PERCENT = f'[core]\n\tbare = false\n[remote "origin"]\n\turl = {URL}\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n'
|
||||
NO_VALUE = '[core]\n\tbare\n[remote "origin"]\n\turl = https://github.com/someone/pack\n'
|
||||
NO_VALUE_THEN_DEEPER = '[core]\n\tbare\n\t\tfilemode = false\n[remote "origin"]\n\turl = https://github.com/someone/pack\n'
|
||||
NO_REMOTE = '[core]\n\tbare = false\n'
|
||||
BOM = "\ufeff" + PLAIN
|
||||
NOT_A_CONFIG = "ref: refs/heads/master\n" + PLAIN
|
||||
NOT_ASCII = PLAIN + '[user]\n\tname = 홍길동\n'
|
||||
NOT_UTF8 = PLAIN.encode() + b'[user]\n\tname = \xff\xfe\n'
|
||||
BRANCH_NOT_UTF8 = PLAIN.encode() + b'[branch "release-\xfe"]\n\tremote = origin\n\tmerge = refs/heads/release-\xfe\n'
|
||||
ORIGIN = '[remote "origin"]\n\turl = https://github.com/someone/pack\n'
|
||||
OTHER = '\t[remote "other"]\n\turl = https://github.com/someone/other\n'
|
||||
VALUE_OVER_TWO_LINES = '[core]\n\tdescription = a \\\n' + OTHER + ORIGIN
|
||||
QUOTED_VALUE_OVER_TWO_LINES = '[core]\n\tdescription = "a # b \\\n' + OTHER.replace('\n', '"\n', 1) + ORIGIN
|
||||
COMMENT_THAT_ENDS_IN_A_BACKSLASH = '[core]\n\t# a comment \\\n' + ORIGIN
|
||||
VALUE_THAT_ENDS_IN_A_BACKSLASH = '[core]\n\tdescription = a\\\\\n' + ORIGIN
|
||||
VALUE_THAT_GOES_ON_WHERE_THE_FILE_ENDS = '[remote "origin"]\n\turl = https://github.com/someone/pack\\'
|
||||
URL_BEFORE_THE_FIRST_SECTION = "url = https://someone:a-token@github.com/someone/pack\n" + PLAIN
|
||||
|
||||
|
||||
def git_utils():
|
||||
spec = importlib.util.spec_from_file_location("_git_utils", PACKAGE / "common/git_utils.py")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def git_url():
|
||||
return git_utils().git_url
|
||||
|
||||
|
||||
def resolve(core):
|
||||
return lambda: load_functions(PACKAGE / core / "manager_core.py", {"resolve_giturl_from_path"}, {
|
||||
"os": os, "configparser": configparser, "logging": logging, "git_utils": git_utils(),
|
||||
})["resolve_giturl_from_path"]
|
||||
|
||||
|
||||
@pytest.fixture(params=[git_url, resolve("glob"), resolve("legacy")], ids=["git_url", "glob", "legacy"])
|
||||
def read(request, tmp_path):
|
||||
reader = request.param()
|
||||
|
||||
def read(config, mode=None):
|
||||
(tmp_path / ".git").mkdir(exist_ok=True)
|
||||
(tmp_path / ".git" / "config").write_bytes(config if isinstance(config, bytes) else config.encode())
|
||||
if mode is not None:
|
||||
(tmp_path / ".git" / "config").chmod(mode)
|
||||
return reader(str(tmp_path))
|
||||
|
||||
return read
|
||||
|
||||
|
||||
def test_url_is_read(read):
|
||||
assert read(PLAIN) == "https://github.com/someone/pack"
|
||||
|
||||
|
||||
def test_url_with_a_percent_sign_is_read_as_it_is(read):
|
||||
assert read(PERCENT) == URL
|
||||
|
||||
|
||||
def test_url_is_read_beside_a_key_without_a_value(read):
|
||||
assert read(NO_VALUE) == "https://github.com/someone/pack"
|
||||
|
||||
|
||||
def test_config_without_a_remote_has_no_url(read):
|
||||
assert read(NO_REMOTE) is None
|
||||
|
||||
|
||||
def test_url_without_a_value_is_no_url(read):
|
||||
assert read('[remote "origin"]\n\turl\n') is None
|
||||
|
||||
|
||||
def test_url_is_read_after_a_byte_order_mark(read):
|
||||
assert read(BOM) == "https://github.com/someone/pack"
|
||||
|
||||
|
||||
def test_url_is_read_beside_text_that_is_not_ascii(read):
|
||||
assert read(NOT_ASCII) == "https://github.com/someone/pack"
|
||||
|
||||
|
||||
def test_url_is_read_beside_bytes_that_are_not_utf8(read):
|
||||
assert read(NOT_UTF8) == "https://github.com/someone/pack"
|
||||
|
||||
|
||||
def test_url_is_read_beside_a_branch_that_is_not_utf8(read):
|
||||
assert read(BRANCH_NOT_UTF8) == "https://github.com/someone/pack"
|
||||
|
||||
|
||||
def test_config_that_cannot_be_parsed_has_no_url_and_is_reported(read, caplog, tmp_path):
|
||||
assert read(NOT_A_CONFIG) is None
|
||||
assert str(tmp_path / ".git" / "config") in caplog.text
|
||||
|
||||
|
||||
def test_key_before_a_deeper_line_is_read(read):
|
||||
"""For git a line that is indented more is a key of its own; the parser would take it as more of the value before it."""
|
||||
assert read(NO_VALUE_THEN_DEEPER) == "https://github.com/someone/pack"
|
||||
assert read('[remote "origin"]\n\turl = https://github.com/someone/pack\n\t\tfetch = +refs/heads/*:refs/remotes/origin/*\n') == "https://github.com/someone/pack"
|
||||
|
||||
|
||||
def test_value_that_goes_on_at_the_next_line_is_one_value(read):
|
||||
"""As for git: what looks like a section in the second line of a value is text of that value."""
|
||||
assert read(VALUE_OVER_TWO_LINES) == "https://github.com/someone/pack"
|
||||
assert read(QUOTED_VALUE_OVER_TWO_LINES) == "https://github.com/someone/pack"
|
||||
assert read(VALUE_THAT_GOES_ON_WHERE_THE_FILE_ENDS) == "https://github.com/someone/pack"
|
||||
|
||||
|
||||
def test_line_that_does_not_go_on_is_a_line_of_its_own(read):
|
||||
assert read(COMMENT_THAT_ENDS_IN_A_BACKSLASH) == "https://github.com/someone/pack"
|
||||
assert read(VALUE_THAT_ENDS_IN_A_BACKSLASH) == "https://github.com/someone/pack"
|
||||
|
||||
|
||||
def test_config_that_cannot_be_parsed_is_reported_without_its_text(read, caplog, tmp_path):
|
||||
assert read(URL_BEFORE_THE_FIRST_SECTION) is None
|
||||
assert str(tmp_path / ".git" / "config") in caplog.text
|
||||
assert "a-token" not in caplog.text
|
||||
|
||||
|
||||
def test_config_that_cannot_be_parsed_is_reported_once(read, caplog, tmp_path):
|
||||
for _ in range(3):
|
||||
assert read(NOT_A_CONFIG) is None
|
||||
|
||||
assert caplog.text.count(f"Cannot read '{tmp_path / '.git' / 'config'}'") == 1
|
||||
|
||||
|
||||
def test_config_that_may_not_be_read_has_no_url_and_is_reported(read, caplog, tmp_path):
|
||||
url = read(PLAIN, mode=0)
|
||||
try:
|
||||
open(tmp_path / ".git" / "config").close()
|
||||
except OSError:
|
||||
pass
|
||||
else:
|
||||
pytest.skip("the file can be read here, as by root or on Windows")
|
||||
|
||||
assert url is None
|
||||
assert str(tmp_path / ".git" / "config") in caplog.text
|
||||
@@ -0,0 +1,383 @@
|
||||
import ast
|
||||
import configparser
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
|
||||
import git
|
||||
import pytest
|
||||
|
||||
from _install_flags_testutil import GIT_LOCATION, import_context, import_reader
|
||||
from legacy_html_testutil import PACKAGE, load_functions
|
||||
|
||||
pytestmark = pytest.mark.skipif(os.name == "nt", reason="the executables of the cases are shell scripts")
|
||||
|
||||
COMMON = PACKAGE / "common"
|
||||
NOT_A_GIT = {
|
||||
"a path that does not exist": None,
|
||||
"a program that fails": "#!/bin/sh\nexit 3\n",
|
||||
"a program that is not git": "#!/bin/sh\necho hello\n",
|
||||
"a program that waits": "#!/bin/sh\nexec sleep 30\n",
|
||||
"a program that prints bytes that are not text": "#!/bin/sh\nprintf '\\377\\376'\n",
|
||||
"a file that cannot be run": "not a program\n",
|
||||
}
|
||||
IMPORT = """
|
||||
import json, sys
|
||||
sys.path.insert(0, {common!r})
|
||||
import git_compat
|
||||
git_compat.find_git_executable.__defaults__ = (2,)
|
||||
used = None
|
||||
if not git_compat.USE_PYGIT2:
|
||||
import git
|
||||
git.Repo.init({repo!r})
|
||||
used = git.Git.GIT_PYTHON_GIT_EXECUTABLE
|
||||
print(json.dumps({{"pygit2": git_compat.USE_PYGIT2, "git": used}}))
|
||||
"""
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def git_finds_its_repository_by_the_directory(monkeypatch):
|
||||
for name in (*GIT_LOCATION, 'GIT_EXE_PATH', 'GIT_PYTHON_GIT_EXECUTABLE'):
|
||||
monkeypatch.delenv(name, raising=False)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def recording_git(tmp_path):
|
||||
calls = tmp_path / "calls"
|
||||
executable = tmp_path / "recording-git"
|
||||
executable.write_text(f'#!/bin/sh\necho "$@" >> "{calls}"\nexec "{shutil.which("git")}" "$@"\n')
|
||||
executable.chmod(0o755)
|
||||
return SimpleNamespace(path=str(executable),
|
||||
calls=lambda: calls.read_text().splitlines() if calls.exists() else [],
|
||||
forget=lambda: calls.unlink(missing_ok=True))
|
||||
|
||||
|
||||
@pytest.fixture(params=NOT_A_GIT)
|
||||
def not_a_git(request, tmp_path):
|
||||
path = tmp_path / "not-a-git"
|
||||
if NOT_A_GIT[request.param] is not None:
|
||||
path.write_text(NOT_A_GIT[request.param])
|
||||
path.chmod(0o755)
|
||||
return str(path)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def imported(tmp_path):
|
||||
def imported(git_exe=None, git_on_path=True, pygit2=False):
|
||||
env = {key: value for key, value in os.environ.items()
|
||||
if key not in ("GIT_EXE_PATH", "GIT_PYTHON_GIT_EXECUTABLE", "GIT_PYTHON_REFRESH", "CM_USE_PYGIT2")}
|
||||
if git_exe is not None:
|
||||
env["GIT_EXE_PATH"] = git_exe
|
||||
if not git_on_path:
|
||||
(tmp_path / "no-git").mkdir()
|
||||
env["PATH"] = str(tmp_path / "no-git")
|
||||
if pygit2:
|
||||
env["CM_USE_PYGIT2"] = "1"
|
||||
code = IMPORT.format(common=str(COMMON), repo=str(tmp_path / "repo"))
|
||||
result = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, env=env, timeout=60)
|
||||
assert result.returncode == 0, result.stderr
|
||||
return json.loads(result.stdout.strip().splitlines()[-1]), result.stderr
|
||||
|
||||
return imported
|
||||
|
||||
|
||||
def test_configured_git_is_run(imported, recording_git):
|
||||
assert imported(recording_git.path)[0] == {"pygit2": False, "git": recording_git.path}
|
||||
assert any(line.startswith("init") for line in recording_git.calls())
|
||||
|
||||
|
||||
def test_configured_git_is_run_without_a_git_on_path(imported, recording_git):
|
||||
assert imported(recording_git.path, git_on_path=False)[0] == {"pygit2": False, "git": recording_git.path}
|
||||
assert any(line.startswith("init") for line in recording_git.calls())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("git_exe", [None, ""])
|
||||
def test_no_setting_keeps_the_default_git(imported, git_exe):
|
||||
state, reported = imported(git_exe)
|
||||
|
||||
assert state == {"pygit2": False, "git": "git"}
|
||||
assert "git_exe" not in reported
|
||||
|
||||
|
||||
def test_setting_that_is_no_git_is_reported_and_the_default_kept(imported, not_a_git):
|
||||
state, reported = imported(not_a_git)
|
||||
|
||||
assert state == {"pygit2": False, "git": "git"}
|
||||
assert not_a_git in reported
|
||||
|
||||
|
||||
LATE = """
|
||||
import json, os, sys
|
||||
import git
|
||||
sys.path.insert(0, {common!r})
|
||||
import git_compat
|
||||
git_compat.setup_git_environment(os.environ["GIT_EXE_PATH"])
|
||||
git.Repo.init({repo!r})
|
||||
print(json.dumps(git.Git.GIT_PYTHON_GIT_EXECUTABLE))
|
||||
"""
|
||||
|
||||
|
||||
def test_configured_git_is_run_when_gitpython_was_imported_first(recording_git, tmp_path):
|
||||
env = {key: value for key, value in os.environ.items() if key not in ("GIT_PYTHON_GIT_EXECUTABLE", "CM_USE_PYGIT2")}
|
||||
env["GIT_EXE_PATH"] = recording_git.path
|
||||
code = LATE.format(common=str(COMMON), repo=str(tmp_path / "repo"))
|
||||
result = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, env=env, timeout=60)
|
||||
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert json.loads(result.stdout.strip().splitlines()[-1]) == recording_git.path
|
||||
assert any(line.startswith("init") for line in recording_git.calls())
|
||||
|
||||
|
||||
def test_what_was_refused_at_the_import_is_not_selected_or_reported_again(tmp_path):
|
||||
fails = tmp_path / "fails"
|
||||
fails.write_text("#!/bin/sh\nexit 3\n")
|
||||
fails.chmod(0o755)
|
||||
env = {key: value for key, value in os.environ.items() if key not in ("GIT_PYTHON_GIT_EXECUTABLE", "CM_USE_PYGIT2")}
|
||||
env["GIT_EXE_PATH"] = str(fails)
|
||||
code = LATE.format(common=str(COMMON), repo=str(tmp_path / "repo"))
|
||||
result = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, env=env, timeout=60)
|
||||
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert json.loads(result.stdout.strip().splitlines()[-1]) == "git"
|
||||
assert result.stderr.count(str(fails)) == 1
|
||||
|
||||
|
||||
def test_git_compat_is_imported_without_any_git(tmp_path):
|
||||
(tmp_path / "no-git").mkdir()
|
||||
(tmp_path / "no-pygit2").mkdir()
|
||||
(tmp_path / "no-pygit2" / "pygit2.py").write_text("raise ImportError('pygit2 is not installed')\n")
|
||||
env = {key: value for key, value in os.environ.items()
|
||||
if key not in ("GIT_EXE_PATH", "GIT_PYTHON_GIT_EXECUTABLE", "GIT_PYTHON_REFRESH", "CM_USE_PYGIT2")}
|
||||
env["PATH"] = str(tmp_path / "no-git")
|
||||
code = (f"import sys; sys.path[:0] = [{str(tmp_path / 'no-pygit2')!r}, {str(COMMON)!r}]\n"
|
||||
"import git_compat, git\n"
|
||||
"try:\n git.Git().version()\nexcept git.GitCommandNotFound:\n print('fails at use')\n")
|
||||
result = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, env=env, timeout=60)
|
||||
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert result.stdout.strip().splitlines()[-1] == "fails at use"
|
||||
assert "no git" in result.stderr.lower()
|
||||
|
||||
|
||||
def test_gitpython_can_be_imported_beside_the_pygit2_backend_without_a_git(tmp_path):
|
||||
pytest.importorskip("pygit2")
|
||||
(tmp_path / "no-git").mkdir()
|
||||
env = {key: value for key, value in os.environ.items()
|
||||
if key not in ("GIT_EXE_PATH", "GIT_PYTHON_GIT_EXECUTABLE", "GIT_PYTHON_REFRESH", "CM_USE_PYGIT2")}
|
||||
env["PATH"] = str(tmp_path / "no-git")
|
||||
code = f"import sys; sys.path.insert(0, {str(COMMON)!r})\nimport git_compat, git\nprint(git_compat.USE_PYGIT2)\n"
|
||||
result = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, env=env, timeout=60)
|
||||
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert result.stdout.strip().splitlines()[-1] == "True"
|
||||
|
||||
|
||||
def test_configured_git_is_run_when_pygit2_is_asked_for_but_not_installed(recording_git, tmp_path):
|
||||
(tmp_path / "no-git").mkdir()
|
||||
(tmp_path / "no-pygit2").mkdir()
|
||||
(tmp_path / "no-pygit2" / "pygit2.py").write_text("raise ImportError('pygit2 is not installed')\n")
|
||||
env = {key: value for key, value in os.environ.items() if key not in ("GIT_PYTHON_GIT_EXECUTABLE", "GIT_PYTHON_REFRESH")}
|
||||
env.update(PATH=str(tmp_path / "no-git"), GIT_EXE_PATH=recording_git.path, CM_USE_PYGIT2="1")
|
||||
code = (f"import json, os, sys; sys.path[:0] = [{str(tmp_path / 'no-pygit2')!r}, {str(COMMON)!r}]\n"
|
||||
"import git_compat, git\n"
|
||||
"git_compat.setup_git_environment(os.environ['GIT_EXE_PATH'])\n"
|
||||
f"git.Repo.init({str(tmp_path / 'repo')!r})\n"
|
||||
"print(json.dumps([git_compat.USE_PYGIT2, git.Git.GIT_PYTHON_GIT_EXECUTABLE]))\n")
|
||||
result = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, env=env, timeout=60)
|
||||
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert json.loads(result.stdout.strip().splitlines()[-1]) == [False, recording_git.path]
|
||||
assert any(line.startswith("init") for line in recording_git.calls())
|
||||
|
||||
|
||||
def test_gitpython_is_imported_by_prestartup_after_the_setting_is_handed_on():
|
||||
body = ast.parse((PACKAGE / "prestartup_script.py").read_text(encoding="utf-8")).body
|
||||
steps = []
|
||||
for node in body:
|
||||
if isinstance(node, ast.Expr) and isinstance(node.value, ast.Call) and ast.unparse(node.value.func) == "set_git_executable":
|
||||
steps.append("setting")
|
||||
elif isinstance(node, (ast.Import, ast.ImportFrom)) and any(name in ast.unparse(node) for name in ("git_compat", "context", "import git")):
|
||||
steps.append("GitPython")
|
||||
|
||||
assert steps == ["setting", "GitPython"]
|
||||
|
||||
|
||||
def test_git_named_by_a_command_on_path_is_run_by_its_full_path(imported, git_compat, tmp_path, monkeypatch):
|
||||
"""GitPython takes a name without a directory as a file of the current directory."""
|
||||
assert imported("git")[0] == {"pygit2": False, "git": shutil.which("git")}
|
||||
|
||||
monkeypatch.chdir(tmp_path)
|
||||
git_compat.setup_git_environment("git")
|
||||
|
||||
assert git.Git.GIT_PYTHON_GIT_EXECUTABLE == shutil.which("git")
|
||||
|
||||
|
||||
def test_git_named_by_a_command_is_not_taken_from_the_current_directory(git_compat, recording_git, tmp_path, monkeypatch):
|
||||
"""Windows looks for a command in the current directory first. Here it is PATH that names that directory."""
|
||||
default = shutil.which("git")
|
||||
shutil.copy(recording_git.path, tmp_path / "git")
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.setenv("PATH", os.pathsep.join([".", os.environ["PATH"]]))
|
||||
|
||||
git_compat.setup_git_environment("git")
|
||||
|
||||
assert git.Git.GIT_PYTHON_GIT_EXECUTABLE == default
|
||||
assert recording_git.calls() == []
|
||||
|
||||
|
||||
def test_pygit2_backend_does_not_use_the_setting(imported, recording_git):
|
||||
pytest.importorskip("pygit2")
|
||||
|
||||
assert imported(recording_git.path, pygit2=True)[0] == {"pygit2": True, "git": None}
|
||||
assert recording_git.calls() == []
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def git_compat(monkeypatch):
|
||||
for name in ("CM_USE_PYGIT2", "GIT_EXE_PATH"):
|
||||
monkeypatch.delenv(name, raising=False)
|
||||
spec = importlib.util.spec_from_file_location("_git_compat_under_test", COMMON / "git_compat.py")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
assert not module.USE_PYGIT2
|
||||
find = module.find_git_executable
|
||||
monkeypatch.setattr(module, "find_git_executable", lambda git_exe, timeout=2: find(git_exe, timeout=timeout))
|
||||
yield module
|
||||
git.refresh()
|
||||
|
||||
|
||||
def test_git_given_after_the_import_is_run(git_compat, recording_git, tmp_path):
|
||||
git_compat.setup_git_environment(recording_git.path)
|
||||
recording_git.forget()
|
||||
|
||||
git.Repo.init(tmp_path / "repo")
|
||||
|
||||
assert any(line.startswith("init") for line in recording_git.calls())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("git_exe", ["", None])
|
||||
def test_nothing_given_after_the_import_keeps_the_default(git_compat, git_exe, capsys):
|
||||
default = git.Git.GIT_PYTHON_GIT_EXECUTABLE
|
||||
capsys.readouterr()
|
||||
|
||||
git_compat.setup_git_environment(git_exe)
|
||||
|
||||
assert capsys.readouterr().err == "" and git.Git.GIT_PYTHON_GIT_EXECUTABLE == default
|
||||
|
||||
|
||||
def test_what_is_no_git_given_after_the_import_is_reported(git_compat, not_a_git, tmp_path, capsys):
|
||||
default = git.Git.GIT_PYTHON_GIT_EXECUTABLE
|
||||
flags = git.remote.FetchInfo._flag_map.copy()
|
||||
|
||||
git_compat.setup_git_environment(not_a_git)
|
||||
|
||||
assert not_a_git in capsys.readouterr().err
|
||||
assert git.Git.GIT_PYTHON_GIT_EXECUTABLE == default and git.remote.FetchInfo._flag_map == flags
|
||||
git.Repo.init(tmp_path / "repo")
|
||||
assert (tmp_path / "repo" / ".git").is_dir()
|
||||
|
||||
|
||||
def test_check_does_not_wait_for_a_program_that_the_setting_started(git_compat, tmp_path):
|
||||
"""With a pipe for the answer, the check would wait for every program that holds the pipe: on Windows also after its time is up."""
|
||||
executable = tmp_path / "starts-a-program"
|
||||
executable.write_text(f'#!/bin/sh\nsleep 30 &\necho $! > "{tmp_path}/pid"\n')
|
||||
executable.chmod(0o755)
|
||||
started = time.monotonic()
|
||||
|
||||
try:
|
||||
assert git_compat.find_git_executable(str(executable), timeout=20) is None
|
||||
assert time.monotonic() - started < 10
|
||||
finally:
|
||||
os.kill(int((tmp_path / "pid").read_text()), signal.SIGTERM)
|
||||
|
||||
|
||||
PERCENT = "%LOCALAPPDATA%\\Git\\bin\\git.exe"
|
||||
|
||||
|
||||
def set_git_executable(monkeypatch, git_exe):
|
||||
# set and removed, so that the variable the function sets is removed after the case, also when there was none
|
||||
monkeypatch.setenv("GIT_EXE_PATH", "")
|
||||
monkeypatch.delenv("GIT_EXE_PATH")
|
||||
config = configparser.ConfigParser(strict=False)
|
||||
config.read_string("[default]\n" + ("" if git_exe is None else f"git_exe = {git_exe}\n"))
|
||||
load_functions(PACKAGE / "prestartup_script.py", {"set_git_executable"}, {"os": os, "default_conf": config["default"]})["set_git_executable"]()
|
||||
return os.environ.get("GIT_EXE_PATH")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("git_exe, given", [("/opt/git/bin/git", "/opt/git/bin/git"), (PERCENT, PERCENT), ("", None), (None, None)])
|
||||
def test_prestartup_hands_the_setting_to_git_compat(monkeypatch, git_exe, given):
|
||||
assert set_git_executable(monkeypatch, git_exe) == given
|
||||
|
||||
|
||||
def test_prestartup_without_a_configuration_file_sets_nothing(monkeypatch):
|
||||
monkeypatch.setenv("GIT_EXE_PATH", "")
|
||||
monkeypatch.delenv("GIT_EXE_PATH")
|
||||
load_functions(PACKAGE / "prestartup_script.py", {"set_git_executable"}, {"os": os, "default_conf": {}})["set_git_executable"]()
|
||||
|
||||
assert os.environ.get("GIT_EXE_PATH") is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("core", ["glob", "legacy"])
|
||||
def test_setting_with_a_percent_sign_is_read_as_written_and_the_others_kept(core, monkeypatch, tmp_path):
|
||||
"""A path of Windows may hold a `%`, which the parser takes as the start of a reference."""
|
||||
(tmp_path / "config.ini").write_text(f"[default]\ngit_exe = {PERCENT}\ndb_mode = local\nnetwork_mode = offline\n")
|
||||
monkeypatch.setattr(import_context(), "manager_config_path", str(tmp_path / "config.ini"))
|
||||
|
||||
config = import_reader(core).read_config()
|
||||
|
||||
assert (config["git_exe"], config["db_mode"], config["network_mode"]) == (PERCENT, "local", "offline")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("core", ["glob", "legacy"])
|
||||
def test_setting_saved_beside_a_git_exe_with_a_percent_sign_keeps_it(core, monkeypatch, tmp_path):
|
||||
path = tmp_path / "config.ini"
|
||||
path.write_text(f"[default]\ngit_exe = {PERCENT}\ndb_mode = local\n")
|
||||
monkeypatch.setattr(import_context(), "manager_config_path", str(path))
|
||||
module = import_reader(core)
|
||||
monkeypatch.setattr(module, "cached_config", None)
|
||||
|
||||
module.get_config()["db_mode"] = "remote"
|
||||
module.write_config()
|
||||
|
||||
assert sorted(line for line in path.read_text().splitlines() if line.startswith(("git_exe", "db_mode"))) == [
|
||||
"db_mode = remote", f"git_exe = {PERCENT}"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("where", ["legacy/manager_server.py", "glob/utils/environment_utils.py"])
|
||||
def test_callers_pass_the_setting_on(where):
|
||||
passed = []
|
||||
load_functions(PACKAGE / where, {"setup_environment"}, {
|
||||
"setup_git_environment": passed.append,
|
||||
"core": SimpleNamespace(get_config=lambda: {"git_exe": "/opt/git/bin/git"}),
|
||||
})["setup_environment"]()
|
||||
|
||||
assert passed == ["/opt/git/bin/git"]
|
||||
|
||||
|
||||
def test_git_helper_runs_the_git_of_the_process_that_starts_it(recording_git, tmp_path):
|
||||
origin, pack = tmp_path / "origin", tmp_path / "pack"
|
||||
|
||||
def git(where, *args):
|
||||
return subprocess.run(["git", "-c", "user.name=test", "-c", "user.email=test@example.invalid", *args],
|
||||
cwd=where, check=True, capture_output=True, text=True).stdout.strip()
|
||||
|
||||
origin.mkdir()
|
||||
git(origin, "init", "-q")
|
||||
git(origin, "commit", "-q", "--allow-empty", "-m", "first")
|
||||
git(tmp_path, "clone", "-q", str(origin), str(pack))
|
||||
git(origin, "commit", "-q", "--allow-empty", "-m", "second")
|
||||
(tmp_path / "folder_paths.py").touch()
|
||||
env = {key: value for key, value in os.environ.items() if key not in ("GIT_PYTHON_REFRESH", "CM_USE_PYGIT2")}
|
||||
env.update(GIT_EXE_PATH=recording_git.path, COMFYUI_PATH=str(tmp_path))
|
||||
|
||||
helper = subprocess.run([sys.executable, str(COMMON / "git_helper.py"), "--pull", str(pack)], cwd=str(tmp_path), env=env, capture_output=True, timeout=60)
|
||||
|
||||
assert helper.returncode == 0, helper.stdout + helper.stderr
|
||||
assert git(pack, "rev-parse", "HEAD") == git(origin, "rev-parse", "HEAD")
|
||||
assert any(line.startswith("fetch") for line in recording_git.calls())
|
||||
@@ -0,0 +1,206 @@
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
from _install_flags_testutil import GIT_LOCATION
|
||||
from test_snapshot_restore_pins import core # noqa: F401
|
||||
|
||||
|
||||
def git(path, *args):
|
||||
subprocess.run(['git', '-c', 'protocol.file.allow=always', '-c', 'user.name=test', '-c', 'user.email=test@example.invalid', *args],
|
||||
cwd=path, check=True, capture_output=True)
|
||||
|
||||
|
||||
def head(path):
|
||||
return subprocess.run(['git', 'rev-parse', 'HEAD'], cwd=path, check=True, capture_output=True, text=True).stdout.strip()
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def git_of_the_case(monkeypatch, tmp_path):
|
||||
for name in GIT_LOCATION:
|
||||
monkeypatch.delenv(name, raising=False)
|
||||
monkeypatch.setenv('GIT_CONFIG_COUNT', '1')
|
||||
monkeypatch.setenv('GIT_CONFIG_KEY_0', 'protocol.file.allow')
|
||||
monkeypatch.setenv('GIT_CONFIG_VALUE_0', 'always')
|
||||
(tmp_path / 'folder_paths.py').touch()
|
||||
monkeypatch.setenv('COMFYUI_PATH', str(tmp_path))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def origin(tmp_path):
|
||||
submodules = tmp_path / 'asset', tmp_path / 'library'
|
||||
origin = tmp_path / 'origin'
|
||||
for repository in (*submodules, origin):
|
||||
repository.mkdir()
|
||||
git(repository, 'init', '-q')
|
||||
commits = []
|
||||
for version in (1, 2):
|
||||
for submodule in submodules:
|
||||
(submodule / '__init__.py').write_text('VERSION = %d' % version)
|
||||
git(submodule, 'add', '.')
|
||||
git(submodule, 'commit', '-q', '-m', 'version %d' % version)
|
||||
if version == 1:
|
||||
git(origin, 'submodule', 'add', '-q', str(submodule), submodule.name)
|
||||
else:
|
||||
git(origin / submodule.name, 'pull', '-q')
|
||||
git(origin, 'commit', '-q', '-a', '-m', 'library %d' % version)
|
||||
commits.append(head(origin))
|
||||
if version == 1:
|
||||
git(tmp_path, 'clone', '-q', '--recursive', str(origin), 'pack')
|
||||
return commits
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def pack(tmp_path, origin):
|
||||
(tmp_path / 'library').rename(tmp_path / 'library.away')
|
||||
return tmp_path / 'pack'
|
||||
|
||||
|
||||
def test_pull_that_fails_at_the_submodules_leaves_the_pack_at_its_commit(core, tmp_path, origin, pack): # noqa: F811
|
||||
with pytest.raises(Exception):
|
||||
core.git_pull(str(pack))
|
||||
|
||||
assert head(pack) == origin[0]
|
||||
assert (pack / 'asset/__init__.py').read_text() == 'VERSION = 1'
|
||||
|
||||
(tmp_path / 'library.away').rename(tmp_path / 'library')
|
||||
core.git_pull(str(pack))
|
||||
|
||||
assert head(pack) == origin[1]
|
||||
assert (pack / 'library/__init__.py').read_text() == 'VERSION = 2'
|
||||
assert (pack / 'asset/__init__.py').read_text() == 'VERSION = 2'
|
||||
|
||||
|
||||
def test_pull_of_the_git_helper_that_fails_is_a_failure(core, monkeypatch, tmp_path, origin, pack): # noqa: F811
|
||||
monkeypatch.setattr(core.platform, 'system', lambda: 'Windows')
|
||||
|
||||
with pytest.raises(Exception):
|
||||
core.git_pull(str(pack))
|
||||
|
||||
assert head(pack) == origin[0]
|
||||
assert (pack / 'asset/__init__.py').read_text() == 'VERSION = 1'
|
||||
|
||||
(tmp_path / 'library.away').rename(tmp_path / 'library')
|
||||
core.git_pull(str(pack))
|
||||
|
||||
assert head(pack) == origin[1]
|
||||
|
||||
|
||||
def library_not_cloned(pack):
|
||||
git(pack, 'submodule', 'deinit', '-q', '-f', 'library')
|
||||
# moved, as git makes files read-only that Windows does not remove
|
||||
(pack / '.git/modules/library').rename(pack.parent / 'library.modules')
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def helper(core, monkeypatch): # noqa: F811
|
||||
monkeypatch.setattr(core.platform, 'system', lambda: 'Windows')
|
||||
|
||||
|
||||
def test_pull_of_the_git_helper_that_fails_at_the_submodules_puts_them_back(core, helper, tmp_path, origin): # noqa: F811
|
||||
asset, nested, pack = tmp_path / 'asset', tmp_path / 'nested', tmp_path / 'pack'
|
||||
nested.mkdir()
|
||||
git(nested, 'init', '-q')
|
||||
git(nested, 'commit', '-q', '--allow-empty', '-m', 'nested')
|
||||
git(asset, 'submodule', 'add', '-q', str(nested), 'nested')
|
||||
git(asset, 'commit', '-q', '-m', 'a submodule')
|
||||
git(tmp_path / 'origin/asset', 'pull', '-q')
|
||||
git(tmp_path / 'origin', 'commit', '-q', '-a', '-m', 'asset with a submodule')
|
||||
nested.rename(tmp_path / 'nested.away')
|
||||
|
||||
with pytest.raises(Exception):
|
||||
core.git_pull(str(pack))
|
||||
|
||||
assert head(pack) == origin[0]
|
||||
assert not (pack / 'asset/.gitmodules').exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('where', ['in the server process', 'in the git helper'])
|
||||
def test_pull_of_a_pack_whose_branch_is_ahead_of_its_remote_is_no_failure(core, request, tmp_path, origin, where): # noqa: F811
|
||||
pack = tmp_path / 'pack'
|
||||
git(pack, 'pull', '-q', '--recurse-submodules')
|
||||
git(pack, 'commit', '-q', '--allow-empty', '-m', 'a commit of the pack alone')
|
||||
tip = head(pack)
|
||||
if where == 'in the git helper':
|
||||
request.getfixturevalue('helper')
|
||||
|
||||
core.git_pull(str(pack))
|
||||
|
||||
assert head(pack) == tip
|
||||
|
||||
|
||||
def library_at_a_commit_away(tmp_path):
|
||||
library = tmp_path / 'library'
|
||||
(library / '__init__.py').write_text('VERSION = 3')
|
||||
git(library, 'commit', '-q', '-a', '-m', 'version 3')
|
||||
git(tmp_path / 'origin/library', 'pull', '-q')
|
||||
git(tmp_path / 'origin', 'commit', '-q', '-a', '-m', 'library 3')
|
||||
version_3 = head(library)
|
||||
library.rename(tmp_path / 'library.away')
|
||||
return version_3
|
||||
|
||||
|
||||
@pytest.mark.parametrize('where', ['in the server process', 'in the git helper'])
|
||||
def test_pull_that_fails_puts_back_the_branch_of_a_pack_that_was_not_on_it(core, request, tmp_path, origin, where): # noqa: F811
|
||||
pack = tmp_path / 'pack'
|
||||
git(pack, 'pull', '-q', '--recurse-submodules')
|
||||
git(pack, 'checkout', '-q', origin[0])
|
||||
git(pack, 'submodule', 'update', '-q', '--recursive')
|
||||
library_not_cloned(pack)
|
||||
library_at_a_commit_away(tmp_path)
|
||||
if where == 'in the git helper':
|
||||
request.getfixturevalue('helper')
|
||||
|
||||
with pytest.raises(Exception):
|
||||
core.git_pull(str(pack))
|
||||
|
||||
assert head(pack) == origin[1]
|
||||
|
||||
|
||||
def test_pull_whose_submodules_cannot_be_put_back_either_fails_with_the_error_of_the_update(core, monkeypatch, capfd, tmp_path, origin): # noqa: F811
|
||||
pack = tmp_path / 'pack'
|
||||
git(pack, 'pull', '-q', '--no-recurse-submodules')
|
||||
version_3 = library_at_a_commit_away(tmp_path)
|
||||
|
||||
monkeypatch.setattr(core.platform, 'system', lambda: 'Linux')
|
||||
with pytest.raises(Exception) as failure:
|
||||
core.git_pull(str(pack))
|
||||
|
||||
assert version_3 in str(failure.value)
|
||||
|
||||
monkeypatch.setattr(core.platform, 'system', lambda: 'Windows')
|
||||
capfd.readouterr()
|
||||
with pytest.raises(Exception):
|
||||
core.git_pull(str(pack))
|
||||
|
||||
assert version_3 in capfd.readouterr().out
|
||||
|
||||
|
||||
@pytest.mark.parametrize('where', ['in the server process', 'in the git helper'])
|
||||
def test_pull_that_fails_leaves_a_submodule_that_was_never_fetched_alone(core, request, tmp_path, where): # noqa: F811
|
||||
for name in ('asset', 'library', 'extra', 'origin'):
|
||||
(tmp_path / name).mkdir()
|
||||
git(tmp_path / name, 'init', '-q')
|
||||
for name in ('asset', 'library', 'extra'):
|
||||
(tmp_path / name / '__init__.py').write_text('VERSION = 1')
|
||||
git(tmp_path / name, 'add', '.')
|
||||
git(tmp_path / name, 'commit', '-q', '-m', 'version 1')
|
||||
origin, plain = tmp_path / 'origin', tmp_path / 'plain'
|
||||
for name in ('asset', 'library'):
|
||||
git(origin, 'submodule', 'add', '-q', str(tmp_path / name), name)
|
||||
git(origin, 'commit', '-q', '-m', 'two submodules')
|
||||
git(tmp_path, 'clone', '-q', str(origin), 'plain')
|
||||
git(plain, 'submodule', 'update', '-q', '--init', 'asset')
|
||||
git(origin, 'rm', '-q', 'library')
|
||||
git(origin, 'submodule', 'add', '-q', str(tmp_path / 'extra'), 'extra')
|
||||
git(origin, 'commit', '-q', '-m', 'library removed, extra added')
|
||||
(tmp_path / 'extra').rename(tmp_path / 'extra.away')
|
||||
before = head(plain)
|
||||
if where == 'in the git helper':
|
||||
request.getfixturevalue('helper')
|
||||
|
||||
with pytest.raises(Exception):
|
||||
core.git_pull(str(plain))
|
||||
|
||||
assert head(plain) == before
|
||||
assert list((plain / 'library').iterdir()) == []
|
||||
@@ -0,0 +1,179 @@
|
||||
import ast
|
||||
import asyncio
|
||||
import re
|
||||
from types import SimpleNamespace
|
||||
from typing import Optional
|
||||
|
||||
import pytest
|
||||
from aiohttp import web
|
||||
from aiohttp.test_utils import TestClient, TestServer
|
||||
|
||||
from legacy_html_testutil import PACKAGE
|
||||
|
||||
JS_DIR = PACKAGE / "js"
|
||||
FILES = sorted(str(path.relative_to(PACKAGE)) for server in ("glob", "legacy") for path in (PACKAGE / server).rglob("*.py"))
|
||||
CHECK = "reject_non_json_post"
|
||||
|
||||
NOT_GET = ("routes.post", "routes.put", "routes.patch", "routes.delete")
|
||||
BODYLESS = {"/v2/manager/queue/start", "/v2/manager/queue/reset", "/v2/manager/queue/update_all", "/v2/manager/queue/update_comfyui",
|
||||
"/v2/snapshot/save", "/v2/snapshot/remove", "/v2/snapshot/restore", "/v2/manager/reboot"}
|
||||
|
||||
NOT_JSON = [
|
||||
None, "text/plain", "text/plain;charset=UTF-8", "application/x-www-form-urlencoded",
|
||||
"multipart/form-data; boundary=x", "application/octet-stream", "text/json", "application/jsonp",
|
||||
"application/json-patch+json", "application/ld+json", "",
|
||||
]
|
||||
JSON = ["application/json", "application/json; charset=utf-8", "application/json;charset=UTF-8", "Application/JSON"]
|
||||
|
||||
|
||||
def functions(filename):
|
||||
tree = ast.parse((PACKAGE / filename).read_text(encoding="utf-8"))
|
||||
return {node.name: node for node in tree.body if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))}
|
||||
|
||||
|
||||
def routes_that_change_something():
|
||||
found = []
|
||||
for filename in FILES:
|
||||
for node in functions(filename).values():
|
||||
for decorator in node.decorator_list:
|
||||
if isinstance(decorator, ast.Call) and ast.unparse(decorator.func).endswith(NOT_GET):
|
||||
found.append((filename, decorator.args[0].value, node.name))
|
||||
return found
|
||||
|
||||
|
||||
ROUTES = routes_that_change_something()
|
||||
|
||||
|
||||
def load_check():
|
||||
node = functions("common/manager_security.py").get(CHECK)
|
||||
assert node is not None, "manager_security.py has no " + CHECK
|
||||
namespace = {"web": web, "Optional": Optional}
|
||||
exec(compile(ast.Module(body=[node], type_ignores=[]), "manager_security.py", "exec"), namespace)
|
||||
return namespace[CHECK]
|
||||
|
||||
|
||||
def load_handler(filename, name):
|
||||
routes = web.RouteTableDef()
|
||||
security = SimpleNamespace(**{CHECK: load_check()})
|
||||
namespace = {"web": web, "routes": routes, "PromptServer": SimpleNamespace(instance=SimpleNamespace(routes=routes)),
|
||||
"security_utils": security, "manager_security": security}
|
||||
exec(compile(ast.Module(body=[functions(filename)[name]], type_ignores=[]), filename, "exec"), namespace)
|
||||
return namespace[name]
|
||||
|
||||
|
||||
def test_the_routes_are_found():
|
||||
routes = {route for _, route, _ in ROUTES}
|
||||
|
||||
assert len(ROUTES) >= 38
|
||||
assert {"/v2/manager/queue/task", "/v2/manager/queue/batch", "/v2/customnode/install/git_url", "/v2/manager/db_mode",
|
||||
"/v2/comfyui_manager/comfyui_switch_version", "/v2/manager/share"} <= routes
|
||||
for server in ("glob", "legacy"):
|
||||
assert BODYLESS | {"/v2/manager/share_option"} <= {route for filename, route, _ in ROUTES if filename.startswith(server + "/")}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("content_type", ["text/plain", "application/x-www-form-urlencoded", "application/octet-stream"])
|
||||
@pytest.mark.parametrize("filename, route, name", ROUTES, ids=["%s %s" % (f.split("/")[0], route) for f, route, _ in ROUTES])
|
||||
def test_a_route_refuses_a_request_that_is_not_json_before_anything_else(filename, route, name, content_type):
|
||||
read = []
|
||||
|
||||
async def read_json():
|
||||
read.append(True)
|
||||
return {}
|
||||
|
||||
request = SimpleNamespace(content_type=content_type, json=read_json)
|
||||
try:
|
||||
response = load_handler(filename, name)(request)
|
||||
if asyncio.iscoroutine(response):
|
||||
response = asyncio.run(response)
|
||||
except NameError as error:
|
||||
pytest.fail("the handler went on to use `%s`" % error.name)
|
||||
|
||||
assert response.status == 400
|
||||
assert "application/json" in response.text
|
||||
assert read == []
|
||||
|
||||
|
||||
def answer(content_type):
|
||||
check = load_check()
|
||||
|
||||
async def handler(request):
|
||||
return check(request) or web.Response(status=200)
|
||||
|
||||
async def post():
|
||||
app = web.Application()
|
||||
app.router.add_post("/", handler)
|
||||
async with TestClient(TestServer(app)) as client:
|
||||
headers = {} if content_type is None else {"Content-Type": content_type}
|
||||
async with client.post("/", data=b'{"value": "x"}', headers=headers, skip_auto_headers=["Content-Type"]) as response:
|
||||
return response.status
|
||||
|
||||
return asyncio.run(post())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("content_type", NOT_JSON, ids=[repr(c) for c in NOT_JSON])
|
||||
def test_a_content_type_that_is_not_json_is_refused(content_type):
|
||||
assert answer(content_type) == 400
|
||||
|
||||
|
||||
@pytest.mark.parametrize("content_type", JSON)
|
||||
def test_json_is_accepted_with_any_parameters_and_in_any_case(content_type):
|
||||
assert answer(content_type) == 200
|
||||
|
||||
|
||||
def past_literal(source, pos):
|
||||
if source.startswith("//", pos):
|
||||
return source.index("\n", pos)
|
||||
if source.startswith("/*", pos):
|
||||
return source.index("*/", pos) + 2
|
||||
quote = source[pos]
|
||||
if quote not in "\"'`":
|
||||
return pos
|
||||
pos += 1
|
||||
while source[pos] != quote:
|
||||
pos += 2 if source[pos] == "\\" else 1
|
||||
return pos + 1
|
||||
|
||||
|
||||
def script_calls():
|
||||
found = []
|
||||
for path in sorted(JS_DIR.glob("*.js")):
|
||||
source = path.read_text(encoding="utf-8")
|
||||
for match in re.finditer(r"\bfetch(?:Api|Data)\(", source):
|
||||
pos, depth, commas = match.end(), 1, []
|
||||
while depth:
|
||||
skipped = past_literal(source, pos)
|
||||
if skipped != pos:
|
||||
pos = skipped
|
||||
continue
|
||||
depth += {"(": 1, "[": 1, "{": 1, ")": -1, "]": -1, "}": -1}.get(source[pos], 0)
|
||||
if source[pos] == "," and depth == 1:
|
||||
commas.append(pos)
|
||||
pos += 1
|
||||
options = source[commas[0] + 1:[*commas, pos - 1][1]].strip() if commas else ""
|
||||
found.append((path.name, source.count("\n", 0, match.start()) + 1, source[match.start():pos], options))
|
||||
return found
|
||||
|
||||
|
||||
PASSES_ITS_OPTIONS_ON = [("common.js", "fetchData(route, options)"), ("common.js", "fetchApi(route, options)")]
|
||||
|
||||
|
||||
def test_the_options_of_a_call_are_written_where_it_is_made():
|
||||
assert [(name, call) for name, _, call, options in script_calls()
|
||||
if options and not options.startswith("{")] == PASSES_ITS_OPTIONS_ON
|
||||
|
||||
|
||||
def calls_that_post():
|
||||
return [(name, line, call) for name, line, call, _ in script_calls()
|
||||
if re.search(r"""['"]?\bbody\b['"]?\s*[:,}]|\bmethod\s*:\s*['"](?!GET)""", call)]
|
||||
|
||||
|
||||
CALLS = calls_that_post()
|
||||
|
||||
|
||||
def test_the_calls_are_found():
|
||||
assert len(CALLS) >= 24
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name, line, call", CALLS, ids=["%s:%d" % (name, line) for name, line, _ in CALLS])
|
||||
def test_a_script_that_posts_names_json(name, line, call):
|
||||
assert re.search(r"""['"]Content-Type['"]\s*:\s*['"]application/json['"]""", call), call
|
||||
@@ -0,0 +1,120 @@
|
||||
"""The legacy server answers a failed ComfyUI version request, and a batch queues a ComfyUI update.
|
||||
|
||||
Each case runs the real handlers of `legacy/manager_server.py`; what they call
|
||||
in `core` is replaced, so nothing is fetched, switched or updated.
|
||||
"""
|
||||
import ast
|
||||
import asyncio
|
||||
import importlib.util
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
import threading
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from aiohttp import web
|
||||
|
||||
from legacy_html_testutil import PACKAGE, load_functions
|
||||
|
||||
SERVER = PACKAGE / "legacy/manager_server.py"
|
||||
SECURITY = PACKAGE / "common/manager_security.py"
|
||||
NAMES = {"comfyui_versions", "comfyui_switch_version", "queue_batch", "update_comfyui", "_update_comfyui"}
|
||||
STABLE = ("update-comfyui", ("comfyui", True))
|
||||
NIGHTLY = ("update-comfyui", ("comfyui", False))
|
||||
POLICIES = [("stable-comfyui", STABLE), ("stable", STABLE), ("nightly-comfyui", NIGHTLY), ("nightly", NIGHTLY)]
|
||||
|
||||
|
||||
def manager_security():
|
||||
spec = importlib.util.spec_from_file_location("_manager_security", SECURITY)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def fail(*args):
|
||||
raise RuntimeError("not a git repository")
|
||||
|
||||
|
||||
def server(policy="stable-comfyui", **core):
|
||||
"""The handlers under test and the list they queue to."""
|
||||
defined = {node.name for node in ast.parse(SERVER.read_text(encoding="utf-8")).body
|
||||
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))}
|
||||
queued = []
|
||||
route = lambda path: lambda handler: handler # noqa: E731
|
||||
handlers = load_functions(SERVER, NAMES & defined, {
|
||||
"web": web, "logging": logging, "json": json, "sys": sys,
|
||||
"routes": SimpleNamespace(get=route, post=route),
|
||||
"core": SimpleNamespace(get_config=lambda: {"update_policy": policy}, **core),
|
||||
"manager_security": manager_security(),
|
||||
"is_allowed_security_level": lambda level: True, "SECURITY_MESSAGE_HIGH_P": "",
|
||||
"temp_queue_batch": queued, "task_worker_lock": threading.Lock(),
|
||||
"finalize_temp_queue_batch": lambda batch, failed: None, "_queue_start": lambda: None,
|
||||
})
|
||||
return handlers, queued
|
||||
|
||||
|
||||
def request(body=None, content_type="application/json"):
|
||||
async def read():
|
||||
return body
|
||||
|
||||
return SimpleNamespace(json=read, content_type=content_type)
|
||||
|
||||
|
||||
def answer(handler, *args):
|
||||
response = asyncio.run(handler(*args))
|
||||
return response.status, response.text
|
||||
|
||||
|
||||
def test_version_list_that_cannot_be_read_is_answered_with_400(caplog):
|
||||
handlers, _ = server(get_comfyui_versions=fail)
|
||||
assert answer(handlers["comfyui_versions"], request()) == (400, None)
|
||||
assert "ComfyUI update fail: not a git repository" in caplog.text
|
||||
|
||||
|
||||
def test_version_list_is_answered_with_the_versions():
|
||||
handlers, _ = server(get_comfyui_versions=lambda: (["nightly", "v0.3.1"], "v0.3.1", "v0.3.1"))
|
||||
assert answer(handlers["comfyui_versions"], request()) == (
|
||||
200, '{"versions": ["nightly", "v0.3.1"], "current": "v0.3.1"}')
|
||||
|
||||
|
||||
def test_version_switch_that_fails_is_answered_with_400(caplog):
|
||||
handlers, _ = server(switch_comfyui=fail)
|
||||
assert answer(handlers["comfyui_switch_version"], request({"ver": "v0.3.0"})) == (400, None)
|
||||
assert "ComfyUI update fail: not a git repository" in caplog.text
|
||||
|
||||
|
||||
def test_version_switch_is_passed_on_and_answered_with_200():
|
||||
switched = []
|
||||
handlers, _ = server(switch_comfyui=switched.append)
|
||||
assert answer(handlers["comfyui_switch_version"], request({"ver": "v0.3.0"})) == (200, None)
|
||||
assert switched == ["v0.3.0"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("policy, update", POLICIES)
|
||||
def test_batch_queues_the_comfyui_update_of_the_policy(policy, update):
|
||||
handlers, queued = server(policy)
|
||||
batch = {"batch_id": "b", "update_comfyui": True}
|
||||
assert answer(handlers["queue_batch"], request(batch)) == (200, '{"failed": []}')
|
||||
assert queued == [update]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("batch", [{"batch_id": "b"}, {"batch_id": "b", "update_comfyui": False}],
|
||||
ids=["no update_comfyui", "update_comfyui false"])
|
||||
def test_batch_that_asks_for_no_comfyui_update_queues_none(batch):
|
||||
handlers, queued = server()
|
||||
assert answer(handlers["queue_batch"], request(batch)) == (200, '{"failed": []}')
|
||||
assert queued == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("policy, update", POLICIES)
|
||||
def test_update_route_queues_the_comfyui_update_of_the_policy(policy, update):
|
||||
handlers, queued = server(policy)
|
||||
assert answer(handlers["update_comfyui"], request())[0] == 200
|
||||
assert queued == [update]
|
||||
|
||||
|
||||
def test_update_route_still_refuses_a_form_post():
|
||||
handlers, queued = server()
|
||||
assert answer(handlers["update_comfyui"], request(content_type="application/x-www-form-urlencoded"))[0] == 400
|
||||
assert queued == []
|
||||
@@ -0,0 +1,64 @@
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from aiohttp import web
|
||||
|
||||
from legacy_html_testutil import PACKAGE, load_functions
|
||||
|
||||
|
||||
def load():
|
||||
cloned, installed = [], []
|
||||
|
||||
async def gitclone_install(url):
|
||||
cloned.append(url)
|
||||
return SimpleNamespace(action="install", result=True, target=url, msg="")
|
||||
|
||||
namespace = {
|
||||
"routes": web.RouteTableDef(), "web": web, "logging": logging,
|
||||
"core": SimpleNamespace(gitclone_install=gitclone_install, pip_install=installed.append),
|
||||
"manager_security": SimpleNamespace(reject_non_json_post=lambda request: None),
|
||||
"_dedicated_install_allowed": lambda flag: True,
|
||||
}
|
||||
load_functions(PACKAGE / "legacy/manager_server.py", {"install_custom_node_git_url", "install_custom_node_pip"}, namespace)
|
||||
return namespace["install_custom_node_git_url"], namespace["install_custom_node_pip"], cloned, installed
|
||||
|
||||
|
||||
def post(handler, text):
|
||||
async def read_json():
|
||||
return json.loads(text)
|
||||
|
||||
return asyncio.run(handler(SimpleNamespace(json=read_json))).status
|
||||
|
||||
|
||||
def test_a_git_url_is_installed_from_the_url_field():
|
||||
git_url, _, cloned, _ = load()
|
||||
|
||||
assert post(git_url, '{"url": "https://github.com/someone/a-pack"}') == 200
|
||||
assert cloned == ["https://github.com/someone/a-pack"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text, packages", [
|
||||
('{"packages": "a-package"}', ["a-package"]),
|
||||
('{"packages": "a-package another==1.0"}', ["a-package", "another==1.0"]),
|
||||
], ids=["one package", "two packages"])
|
||||
def test_pip_packages_are_installed_from_the_packages_field(text, packages):
|
||||
_, pip, _, installed = load()
|
||||
|
||||
assert post(pip, text) == 200
|
||||
assert installed == [packages]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", ["", "https://github.com/someone/a-pack", "{", '{"other": 1}', "{}", "[]", '"a-pack"', "null", "5",
|
||||
'{"url": 5, "packages": 5}', '{"url": null, "packages": null}', '{"url": ["a"], "packages": ["a"]}',
|
||||
'{"url": {"a": 1}, "packages": {"a": 1}}', '{"url": true, "packages": true}'],
|
||||
ids=["empty", "plain text", "cut off", "another field", "no field", "a list", "a string", "null", "a number",
|
||||
"the field a number", "the field null", "the field a list", "the field an object", "the field a boolean"])
|
||||
@pytest.mark.parametrize("route", [0, 1], ids=["git_url", "pip"])
|
||||
def test_a_body_without_the_field_is_a_bad_request_and_installs_nothing(route, text):
|
||||
handlers = load()
|
||||
|
||||
assert post(handlers[route], text) == 400
|
||||
assert handlers[2] == [] and handlers[3] == []
|
||||
@@ -14,7 +14,7 @@ PATHS GUARDED (the OTHER security_level gates):
|
||||
deny branch (``is_allowed_security_level
|
||||
('block')`` is hard-False; Q1)
|
||||
P3 nodepack/snapshot high+/middle — ``comfyui_switch_version`` (high+),
|
||||
gates ``restore_snapshot`` (middle+)
|
||||
gates ``restore_snapshot`` (high+)
|
||||
P4 model non-.safetensors high+ gate — ``_install_model`` (L1713)
|
||||
|
||||
NON-VACUITY (the bar from the GOAL MM): every assertion below is written so
|
||||
@@ -145,10 +145,6 @@ def _run(coro):
|
||||
|
||||
|
||||
class FakeRequest:
|
||||
"""Minimal stand-in for an aiohttp request. ``content_type`` satisfies
|
||||
``reject_simple_form_post``; nothing else is read on the deny path (the
|
||||
gate returns before any body access)."""
|
||||
|
||||
def __init__(self, content_type="application/json"):
|
||||
self.content_type = content_type
|
||||
|
||||
@@ -160,7 +156,7 @@ class FakeRequest:
|
||||
# ===========================================================================
|
||||
|
||||
# (security_level, is_local_mode, network_mode, expected_allowed)
|
||||
_MIDDLE_PLUS = [ # P1 batch entry, _update_all, _install_model entry, restore_snapshot
|
||||
_MIDDLE_PLUS = [
|
||||
("weak", True, "public", True),
|
||||
("normal", True, "public", True),
|
||||
("normal-", True, "public", True),
|
||||
@@ -298,10 +294,9 @@ def test_p3_comfyui_switch_version_denies_high_plus_403(ms, gate):
|
||||
assert resp.status == 403
|
||||
|
||||
|
||||
def test_p3_restore_snapshot_denies_middle_plus_403(ms, gate):
|
||||
"""P3 middle+ handler: restore_snapshot denies with 403 at sl=strong
|
||||
(middle+ requires normal or lower)."""
|
||||
gate("strong", is_local_mode=True)
|
||||
@pytest.mark.parametrize("security_level", ["strong", "normal"])
|
||||
def test_p3_restore_snapshot_denies_high_plus_403(ms, gate, security_level):
|
||||
gate(security_level, is_local_mode=True)
|
||||
resp = _run(ms.restore_snapshot(FakeRequest()))
|
||||
assert resp.status == 403
|
||||
|
||||
|
||||
@@ -2,10 +2,14 @@
|
||||
|
||||
A logger that always answered "not a terminal" made colorama, and any other library that
|
||||
asks, strip its colors and hide its progress display for the whole session.
|
||||
|
||||
The last cases are about what is written once the log file is closed: the restart under
|
||||
comfy-cli closes it and then exits, and what is logged on the way out must not fail.
|
||||
"""
|
||||
import ast
|
||||
import io
|
||||
import textwrap
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
@@ -35,15 +39,53 @@ class StreamThatCannotBeAsked:
|
||||
raise OSError("The handle is invalid")
|
||||
|
||||
|
||||
def loggers(stdout, stderr, log_closed=False):
|
||||
class LogFile:
|
||||
def __init__(self, closed=False):
|
||||
self.closed = closed
|
||||
self.written = []
|
||||
|
||||
def write(self, text):
|
||||
if self.closed:
|
||||
raise ValueError("I/O operation on closed file.")
|
||||
self.written.append(text)
|
||||
|
||||
def flush(self):
|
||||
pass
|
||||
|
||||
|
||||
def loggers(stdout, stderr, log_closed=False, **module_globals):
|
||||
"""Lift ComfyUIManagerLogger; importing prestartup_script would run the startup."""
|
||||
source = SOURCE.read_text(encoding="utf-8")
|
||||
node = next(n for n in ast.walk(ast.parse(source)) if isinstance(n, ast.ClassDef) and n.name == "ComfyUIManagerLogger")
|
||||
scope = {"original_stdout": stdout, "original_stderr": stderr, "log_file": SimpleNamespace(closed=log_closed)}
|
||||
scope = {"original_stdout": stdout, "original_stderr": stderr, "log_file": SimpleNamespace(closed=log_closed),
|
||||
**module_globals}
|
||||
exec(textwrap.dedent("\n".join(source.splitlines()[node.lineno - 1:node.end_lineno])), scope)
|
||||
return scope["ComfyUIManagerLogger"](True), scope["ComfyUIManagerLogger"](False)
|
||||
|
||||
|
||||
def close_logs(log_file, log_lock):
|
||||
"""The two ways to close the log file: the logger's method, and the function run at exit."""
|
||||
source = SOURCE.read_text(encoding="utf-8")
|
||||
tree = ast.parse(source)
|
||||
in_class = {id(n) for c in ast.walk(tree) if isinstance(c, ast.ClassDef) for n in ast.walk(c)}
|
||||
function = next(n for n in ast.walk(tree)
|
||||
if isinstance(n, ast.FunctionDef) and n.name == "close_log" and id(n) not in in_class)
|
||||
scope = {"sys": SimpleNamespace(), "original_stdout": None, "original_stderr": None,
|
||||
"log_file": log_file, "log_lock": log_lock}
|
||||
exec(textwrap.dedent("\n".join(source.splitlines()[function.lineno - 1:function.end_lineno])), scope)
|
||||
out, _ = loggers(None, None, **{name: scope[name] for name in ("sys", "log_file", "log_lock")})
|
||||
return out.close_log, scope["close_log"]
|
||||
|
||||
|
||||
def writing_logger(log_file):
|
||||
"""The stderr logger with what its writes need, and the list of what reached the console."""
|
||||
console = []
|
||||
stream = SimpleNamespace(flush=lambda: None)
|
||||
_, err = loggers(stream, stream, log_file=log_file, log_lock=threading.Lock(), std_log_lock=threading.Lock(),
|
||||
current_timestamp=lambda: "12:00:00", write_stdout=console.append, write_stderr=console.append)
|
||||
return err, console
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def ansitowin32(monkeypatch):
|
||||
"""colorama's stream wrapper, with its probe of the Windows console answered.
|
||||
@@ -121,3 +163,38 @@ def test_colorama_keeps_ansi_codes_only_on_a_terminal(ansitowin32, stream, kept)
|
||||
out, _ = loggers(stream, stream)
|
||||
|
||||
assert ansitowin32.AnsiToWin32(out).strip is (not kept)
|
||||
|
||||
|
||||
def test_open_log_file_gets_what_is_written():
|
||||
log_file = LogFile()
|
||||
logger, console = writing_logger(log_file)
|
||||
|
||||
logger.sync_write("first\n")
|
||||
logger.sync_write("logged only\n", file_only=True)
|
||||
|
||||
assert log_file.written == ["first\n", "[12:00:00] logged only\n"]
|
||||
assert console == ["first\n"]
|
||||
|
||||
|
||||
def test_closed_log_file_is_left_alone():
|
||||
log_file = LogFile(closed=True)
|
||||
logger, console = writing_logger(log_file)
|
||||
|
||||
# what the logging handler does with a record that arrives after close_log()
|
||||
logger.sync_write("logged only\n", file_only=True)
|
||||
logger.sync_write("still shown\n")
|
||||
|
||||
assert log_file.written == []
|
||||
assert console == ["still shown\n"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("which", [0, 1])
|
||||
def test_log_file_is_closed_under_the_lock_of_the_writes(which):
|
||||
log_lock = threading.Lock()
|
||||
held = []
|
||||
log_file = SimpleNamespace(close=lambda: held.append(log_lock.locked()))
|
||||
|
||||
close_logs(log_file, log_lock)[which]()
|
||||
|
||||
# a write checks that the file is open and writes to it under this lock
|
||||
assert held == [True]
|
||||
|
||||
@@ -0,0 +1,295 @@
|
||||
import asyncio
|
||||
import json
|
||||
import mimetypes
|
||||
import os
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from aiohttp import web
|
||||
|
||||
from legacy_html_testutil import PACKAGE, load_functions
|
||||
|
||||
MATRIX_ORG = "https://matrix.org"
|
||||
SAVED = ("matrix.org", "user", "the saved password")
|
||||
PASSWORDS_THAT_LOG_IN = {SAVED[2], "a new password"}
|
||||
FUNCTIONS = ("is_matrix_org", "get_matrix_auth", "set_matrix_auth", "api_get_matrix_auth", "share_art")
|
||||
|
||||
|
||||
class LoginResponse:
|
||||
access_token = "token"
|
||||
|
||||
|
||||
class UploadResponse:
|
||||
content_uri = "mxc://test/asset"
|
||||
|
||||
|
||||
@pytest.fixture(params=["glob", "legacy"])
|
||||
def manager(request, tmp_path):
|
||||
logins = []
|
||||
|
||||
class AsyncClient:
|
||||
def __init__(self, homeserver, username):
|
||||
self.homeserver, self.username = homeserver, username
|
||||
|
||||
async def login(self, password):
|
||||
logins.append((self.homeserver, self.username, password))
|
||||
return LoginResponse() if password in PASSWORDS_THAT_LOG_IN else None
|
||||
|
||||
async def upload(self, data, content_type=None, filename=None):
|
||||
return UploadResponse(), None
|
||||
|
||||
async def room_send(self, **kwargs):
|
||||
pass
|
||||
|
||||
async def close(self):
|
||||
pass
|
||||
|
||||
files = tmp_path / "manager"
|
||||
output_dir = tmp_path / "output"
|
||||
files.mkdir()
|
||||
output_dir.mkdir()
|
||||
(output_dir / "a.png").write_bytes(b"output image")
|
||||
|
||||
namespace = load_functions(PACKAGE / request.param / "share_3rdparty.py", set(FUNCTIONS), {
|
||||
"PromptServer": SimpleNamespace(instance=SimpleNamespace(routes=web.RouteTableDef())),
|
||||
"folder_paths": SimpleNamespace(get_output_directory=lambda: str(output_dir),
|
||||
get_temp_directory=lambda: str(tmp_path / "temp")),
|
||||
"context": SimpleNamespace(manager_files_path=str(files)),
|
||||
"os": os, "web": web, "json": json, "mimetypes": mimetypes, "matrix_nio_is_available": True,
|
||||
"manager_security": SimpleNamespace(reject_non_json_post=lambda request: None),
|
||||
"AsyncClient": AsyncClient, "LoginResponse": LoginResponse, "UploadResponse": UploadResponse,
|
||||
})
|
||||
return SimpleNamespace(file=files / "matrix_auth", logins=logins, **{name: namespace[name] for name in FUNCTIONS})
|
||||
|
||||
|
||||
def share(manager, matrix_auth, destinations=("matrix",)):
|
||||
body = {
|
||||
"matrix_auth": matrix_auth, "share_destinations": list(destinations),
|
||||
"credits": "", "title": "", "description": "", "prompt": {"workflow": {}}, "selected_output_index": 0,
|
||||
"potential_outputs": [{"type": "image", "image": {"filename": "a.png", "subfolder": "", "type": "output"}}],
|
||||
}
|
||||
|
||||
async def read_json():
|
||||
return body
|
||||
|
||||
try:
|
||||
return asyncio.run(manager.share_art(SimpleNamespace(json=read_json))).status
|
||||
except Exception:
|
||||
return 500
|
||||
|
||||
|
||||
def account(homeserver=SAVED[0], username=SAVED[1], password=""):
|
||||
return {"homeserver": homeserver, "username": username, "password": password}
|
||||
|
||||
|
||||
MATRIX_ORG_FORMS = ["matrix.org", "https://matrix.org", "http://matrix.org"]
|
||||
|
||||
OTHER_HOMESERVERS = [
|
||||
"matrix.example", "matrix.org.example", "sub.matrix.org", "matrix", "org", "Matrix.org", "MATRIX.ORG",
|
||||
"matrix.org/", "matrix.org.", " matrix.org", "matrix.org ", "matrix.org:8448", "matrix.org:443",
|
||||
"user@matrix.org", "matrix.org@other.example", "other.example/matrix.org", "other.example#matrix.org",
|
||||
"other.example?matrix.org", "https://other.example", "http://other.example", "https://https://matrix.org",
|
||||
"ftp://matrix.org", "//matrix.org", "matrix.org\\other.example", "matrix.org\nother.example", "127.0.0.1", "localhost:8188",
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", [
|
||||
"matrix.org\nuser\nthe saved password",
|
||||
"matrix.org\nuser\nthe saved password\n",
|
||||
"\n\nmatrix.org\nuser\nthe saved password\n\n",
|
||||
], ids=["three lines", "a final newline", "blank lines around"])
|
||||
def test_the_answer_has_the_homeserver_and_the_username(manager, text):
|
||||
manager.file.write_text(text)
|
||||
|
||||
response = asyncio.run(manager.api_get_matrix_auth(None))
|
||||
|
||||
assert response.status == 200
|
||||
assert json.loads(response.text) == {"homeserver": "matrix.org", "username": "user"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", [
|
||||
None, "", "matrix.org\nuser", "matrix.org\nuser\nthe saved password\nmore",
|
||||
"matrix.org\n\nthe saved password", "matrix.org\nuser\n", "\nuser\nthe saved password",
|
||||
], ids=["no file", "an empty file", "two lines", "four lines", "an empty username", "an empty password",
|
||||
"an empty homeserver"])
|
||||
def test_a_file_that_is_not_an_account_is_answered_as_nothing_saved(manager, text):
|
||||
if text is not None:
|
||||
manager.file.write_text(text)
|
||||
|
||||
assert asyncio.run(manager.api_get_matrix_auth(None)).status == 404
|
||||
assert share(manager, account()) == 400
|
||||
assert manager.logins == [(MATRIX_ORG, "user", "")]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("homeserver", [h for h in OTHER_HOMESERVERS if h == h.strip() and "\n" not in h])
|
||||
def test_an_account_saved_for_another_homeserver_is_not_used(manager, homeserver):
|
||||
text = "\n".join((homeserver, SAVED[1], SAVED[2]))
|
||||
manager.file.write_text(text)
|
||||
|
||||
assert asyncio.run(manager.api_get_matrix_auth(None)).status == 404
|
||||
assert share(manager, account()) == 400
|
||||
assert manager.logins == [(MATRIX_ORG, "user", "")]
|
||||
assert manager.file.read_text() == text
|
||||
|
||||
|
||||
@pytest.mark.parametrize("homeserver", MATRIX_ORG_FORMS[1:])
|
||||
def test_matrix_org_saved_with_a_scheme_is_the_saved_account(manager, homeserver):
|
||||
text = "\n".join((homeserver, SAVED[1], SAVED[2]))
|
||||
manager.file.write_text(text)
|
||||
|
||||
assert json.loads(asyncio.run(manager.api_get_matrix_auth(None)).text) == {"homeserver": homeserver, "username": "user"}
|
||||
assert share(manager, account()) == 200
|
||||
assert manager.logins == [(MATRIX_ORG, "user", SAVED[2])]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("password", ["", None], ids=["empty", "null"])
|
||||
def test_no_password_for_the_saved_account_logs_in_with_the_saved_one(manager, password):
|
||||
manager.file.write_text("\n".join(SAVED))
|
||||
|
||||
assert share(manager, account(password=password)) == 200
|
||||
assert manager.logins == [(MATRIX_ORG, "user", SAVED[2])]
|
||||
assert manager.file.read_text() == "\n".join(SAVED)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("matrix_auth", [
|
||||
*(account(homeserver) for homeserver in MATRIX_ORG_FORMS), {"username": "user", "password": ""},
|
||||
], ids=[*MATRIX_ORG_FORMS, "no homeserver field"])
|
||||
def test_matrix_org_is_logged_in_however_the_request_writes_it(manager, matrix_auth):
|
||||
manager.file.write_text("\n".join(SAVED))
|
||||
|
||||
assert share(manager, matrix_auth) == 200
|
||||
assert manager.logins == [(MATRIX_ORG, "user", SAVED[2])]
|
||||
assert manager.file.read_text() == "\n".join(SAVED)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("homeserver", OTHER_HOMESERVERS + [""])
|
||||
@pytest.mark.parametrize("password", ["", "a new password"], ids=["no password", "a password that logs in"])
|
||||
def test_another_homeserver_is_refused_before_any_login(manager, homeserver, password):
|
||||
manager.file.write_text("\n".join(SAVED))
|
||||
|
||||
assert share(manager, account(homeserver, password=password)) == 400
|
||||
assert manager.logins == []
|
||||
assert manager.file.read_text() == "\n".join(SAVED)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("username", ["User", "user ", " user", "user2", "use", ""],
|
||||
ids=["upper case", "trailing space", "leading space", "longer", "shorter", "empty"])
|
||||
def test_a_username_written_otherwise_is_another_account(manager, username):
|
||||
manager.file.write_text("\n".join(SAVED))
|
||||
|
||||
assert share(manager, account(username=username)) == 400
|
||||
assert manager.logins == [(MATRIX_ORG, username, "")]
|
||||
assert manager.file.read_text() == "\n".join(SAVED)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("homeserver", MATRIX_ORG_FORMS)
|
||||
def test_a_password_that_logs_in_replaces_the_saved_account(manager, homeserver):
|
||||
manager.file.write_text("\n".join(SAVED))
|
||||
|
||||
assert share(manager, account(homeserver, "someone", "a new password")) == 200
|
||||
assert manager.logins == [(MATRIX_ORG, "someone", "a new password")]
|
||||
assert manager.file.read_text() == "matrix.org\nsomeone\na new password"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("password", ["a wrong password", " "], ids=["wrong", "a space"])
|
||||
def test_a_password_that_does_not_log_in_leaves_the_saved_account(manager, password):
|
||||
manager.file.write_text("\n".join(SAVED))
|
||||
|
||||
assert share(manager, account(password=password)) == 400
|
||||
assert manager.logins == [(MATRIX_ORG, "user", password)]
|
||||
assert manager.file.read_text() == "\n".join(SAVED)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("homeserver", ["matrix.org", "other.example"])
|
||||
def test_sharing_without_matrix_leaves_the_saved_account(manager, homeserver):
|
||||
manager.file.write_text("\n".join(SAVED))
|
||||
|
||||
assert share(manager, account(homeserver), destinations=()) == 200
|
||||
assert manager.logins == []
|
||||
assert manager.file.read_text() == "\n".join(SAVED)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("matrix_auth", [
|
||||
None, [], {}, {"homeserver": "matrix.org", "username": "user"},
|
||||
{"homeserver": None, "username": "user", "password": ""},
|
||||
{"homeserver": ["matrix.org"], "username": "user", "password": ""},
|
||||
{"homeserver": 1, "username": "user", "password": ""},
|
||||
{"homeserver": "matrix.org", "username": None, "password": None},
|
||||
{"homeserver": "matrix.org", "username": 1, "password": 0},
|
||||
], ids=["null", "a list", "no fields", "no password field", "null homeserver", "a list as homeserver",
|
||||
"a number as homeserver", "null username", "numbers"])
|
||||
def test_a_malformed_account_leaves_the_saved_account(manager, matrix_auth):
|
||||
manager.file.write_text("\n".join(SAVED))
|
||||
|
||||
assert share(manager, matrix_auth) >= 400
|
||||
assert SAVED[2] not in [login[2] for login in manager.logins]
|
||||
assert all(login[0] == MATRIX_ORG for login in manager.logins)
|
||||
assert manager.file.read_text() == "\n".join(SAVED)
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name == "nt", reason="the mode of a file is not kept on Windows")
|
||||
@pytest.mark.parametrize("umask", [0o022, 0o002, 0o000])
|
||||
@pytest.mark.parametrize("before", [None, 0o664, 0o644, 0o600], ids=["no file", "0664", "0644", "0600"])
|
||||
def test_the_saved_account_is_a_file_of_its_user_only(manager, before, umask):
|
||||
if before is not None:
|
||||
manager.file.write_text("\n".join(SAVED))
|
||||
manager.file.chmod(before)
|
||||
previous = os.umask(umask)
|
||||
try:
|
||||
assert share(manager, account(username="someone", password="a new password")) == 200
|
||||
finally:
|
||||
os.umask(previous)
|
||||
|
||||
assert manager.file.stat().st_mode & 0o777 == 0o600
|
||||
assert manager.file.read_text() == "matrix.org\nsomeone\na new password"
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name == "nt", reason="the mode of a file is not kept on Windows")
|
||||
def test_the_password_is_written_after_the_file_is_of_its_user_only(manager, monkeypatch):
|
||||
manager.file.write_text("\n".join(SAVED))
|
||||
manager.file.chmod(0o644)
|
||||
seen = []
|
||||
chmod = os.chmod
|
||||
|
||||
def record(path, mode):
|
||||
chmod(path, mode)
|
||||
seen.append((manager.file.stat().st_mode & 0o777, manager.file.read_text()))
|
||||
|
||||
monkeypatch.setattr(os, "chmod", record)
|
||||
|
||||
assert share(manager, account(username="someone", password="a new password")) == 200
|
||||
assert seen == [(0o600, "\n".join(SAVED))]
|
||||
assert manager.file.read_text() == "matrix.org\nsomeone\na new password"
|
||||
|
||||
|
||||
def test_a_file_whose_mode_cannot_be_set_is_saved_all_the_same(manager, monkeypatch):
|
||||
manager.file.write_text("\n".join(SAVED))
|
||||
|
||||
def refuse(path, mode):
|
||||
raise PermissionError(1, "Operation not permitted", str(path))
|
||||
|
||||
monkeypatch.setattr(os, "chmod", refuse)
|
||||
|
||||
assert share(manager, account(username="someone", password="a new password")) == 200
|
||||
assert manager.file.read_text() == "matrix.org\nsomeone\na new password"
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name == "nt", reason="the mode of a file is not kept on Windows")
|
||||
def test_a_new_file_is_of_its_user_only_from_the_moment_it_is_made(manager, monkeypatch):
|
||||
seen = []
|
||||
monkeypatch.setattr(os, "chmod", lambda path, mode: seen.append(manager.file.stat().st_mode & 0o777))
|
||||
previous = os.umask(0)
|
||||
try:
|
||||
assert share(manager, account(username="someone", password="a new password")) == 200
|
||||
finally:
|
||||
os.umask(previous)
|
||||
|
||||
assert seen == [0o600]
|
||||
assert manager.file.stat().st_mode & 0o777 == 0o600
|
||||
|
||||
|
||||
def test_a_shorter_account_replaces_a_longer_one_whole(manager):
|
||||
manager.file.write_text("matrix.org\n" + "a" * 200 + "\nthe saved password")
|
||||
|
||||
assert share(manager, account(username="someone", password="a new password")) == 200
|
||||
assert manager.file.read_text() == "matrix.org\nsomeone\na new password"
|
||||
@@ -0,0 +1,23 @@
|
||||
"""`openapi.yaml` lists, for `db_mode` and the update policy, the values the routes accept."""
|
||||
import ast
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
from legacy_html_testutil import PACKAGE
|
||||
|
||||
SPEC = yaml.safe_load((PACKAGE.parent / "openapi.yaml").read_text(encoding="utf-8"))
|
||||
ACCEPTED = {node.targets[0].id: ast.literal_eval(node.value)
|
||||
for node in ast.parse((PACKAGE / "glob/utils/environment_utils.py").read_text(encoding="utf-8")).body
|
||||
if isinstance(node, ast.Assign) and getattr(node.targets[0], "id", "").startswith("ALLOWED_")}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("route, accepted", [
|
||||
("/v2/manager/db_mode", "ALLOWED_DB_MODES"),
|
||||
("/v2/manager/policy/update", "ALLOWED_UPDATE_POLICIES"),
|
||||
])
|
||||
def test_values_of_a_setting_route_are_the_ones_the_route_accepts(route, accepted):
|
||||
answered = SPEC["paths"][route]["get"]["responses"]["200"]["content"]["text/plain"]["schema"]["enum"]
|
||||
asked = SPEC["paths"][route]["post"]["requestBody"]["content"]["application/json"]["schema"]["properties"]["value"]["enum"]
|
||||
|
||||
assert sorted(answered) == sorted(asked) == sorted(ACCEPTED[accepted])
|
||||
@@ -0,0 +1,129 @@
|
||||
"""A progress message of the server that is not UTF-8 by itself does not end a clone or a fetch of the pygit2 backend.
|
||||
|
||||
pygit2 decodes each piece of such a message as UTF-8 before it hands it on, and a piece can end in the
|
||||
middle of a character: with a server that writes its messages in Korean, a clone failed now and then.
|
||||
Each case runs in a process of its own, with pygit2 asked for and no git executable on `PATH`, against a
|
||||
`git daemon` whose message is the first two bytes of a Korean character. The server of the cases with a proxy, in
|
||||
tests/test_pygit2_submodules.py, writes the same message.
|
||||
"""
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from _install_flags_testutil import GIT_LOCATION
|
||||
from test_git_commit_and_submodules import git_with_local_submodules, head, repository
|
||||
from test_pygit2_submodules import MESSAGE_CUT_IN_A_CHARACTER, git_host_behind_a_proxy, pin, run_with_pygit2 # noqa: F401
|
||||
|
||||
pytest.importorskip('pygit2')
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def git_finds_its_repository_by_the_directory(monkeypatch):
|
||||
for name in GIT_LOCATION:
|
||||
monkeypatch.delenv(name, raising=False)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def git_host(tmp_path):
|
||||
exec_path = subprocess.run(['git', '--exec-path'], capture_output=True, text=True).stdout.strip()
|
||||
if not shutil.which('git-daemon', path=exec_path):
|
||||
pytest.skip('git daemon is not installed')
|
||||
served = tmp_path / 'served'
|
||||
served.mkdir()
|
||||
with socket.socket() as probe:
|
||||
probe.bind(('127.0.0.1', 0))
|
||||
port = probe.getsockname()[1]
|
||||
daemon = subprocess.Popen(['git', 'daemon', '--export-all', '--reuseaddr', f'--base-path={served}', '--listen=127.0.0.1', f'--port={port}', str(served)],
|
||||
env={**os.environ, **MESSAGE_CUT_IN_A_CHARACTER},
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
try:
|
||||
for _ in range(100):
|
||||
try:
|
||||
socket.create_connection(('127.0.0.1', port), timeout=0.2).close()
|
||||
break
|
||||
except OSError:
|
||||
time.sleep(0.05)
|
||||
yield served, f'git://127.0.0.1:{port}'
|
||||
finally:
|
||||
daemon.terminate()
|
||||
daemon.wait()
|
||||
|
||||
|
||||
def test_clone(tmp_path, git_host):
|
||||
served, url = git_host
|
||||
repository(served / 'fixture')
|
||||
|
||||
child = run_with_pygit2(tmp_path, f"git_compat.clone_repo({url + '/fixture'!r}, {str(tmp_path / 'clone')!r})")
|
||||
|
||||
assert child.returncode == 0, child.stderr[-600:]
|
||||
assert (tmp_path / 'clone/__init__.py').read_text() == 'VERSION = 2'
|
||||
|
||||
|
||||
def test_fetch(tmp_path, git_host):
|
||||
served, url = git_host
|
||||
repository(served / 'fixture')
|
||||
clone = tmp_path / 'clone'
|
||||
git_with_local_submodules(tmp_path, 'clone', '-q', url + '/fixture', str(clone))
|
||||
(served / 'fixture/__init__.py').write_text('VERSION = 3')
|
||||
git_with_local_submodules(served / 'fixture', 'commit', '-q', '-a', '-m', 'version 3')
|
||||
|
||||
child = run_with_pygit2(tmp_path, f'git_compat.open_repo({str(clone)!r}).fetch_remote_by_index(0)')
|
||||
|
||||
assert child.returncode == 0, child.stderr[-600:]
|
||||
git_with_local_submodules(clone, 'cat-file', '-e', head(served / 'fixture'))
|
||||
|
||||
|
||||
def test_update_of_the_submodules(tmp_path, git_host):
|
||||
served, url = git_host
|
||||
repository(served / 'library')
|
||||
origin = tmp_path / 'origin'
|
||||
origin.mkdir()
|
||||
git_with_local_submodules(origin, 'init', '-q')
|
||||
git_with_local_submodules(origin, 'submodule', 'add', '-q', url + '/library', 'library')
|
||||
git_with_local_submodules(origin, 'commit', '-q', '-a', '-m', 'a submodule')
|
||||
clone = tmp_path / 'clone'
|
||||
git_with_local_submodules(tmp_path, 'clone', '-q', str(origin), str(clone))
|
||||
|
||||
child = run_with_pygit2(tmp_path, f'git_compat.open_repo({str(clone)!r}).submodule_update()')
|
||||
|
||||
assert child.returncode == 0, child.stderr[-600:]
|
||||
assert (clone / 'library/__init__.py').read_text() == 'VERSION = 2'
|
||||
|
||||
|
||||
def test_update_of_the_submodules_that_are_fetched(tmp_path, git_host):
|
||||
served, url = git_host
|
||||
repository(served / 'library')
|
||||
origin = tmp_path / 'origin'
|
||||
origin.mkdir()
|
||||
git_with_local_submodules(origin, 'init', '-q')
|
||||
git_with_local_submodules(origin, 'submodule', 'add', '-q', url + '/library', 'library')
|
||||
git_with_local_submodules(origin, 'commit', '-q', '-a', '-m', 'a submodule')
|
||||
clone = tmp_path / 'clone'
|
||||
git_with_local_submodules(tmp_path, 'clone', '-q', '--recurse-submodules', str(origin), str(clone))
|
||||
(served / 'library/__init__.py').write_text('VERSION = 3')
|
||||
git_with_local_submodules(served / 'library', 'commit', '-q', '-a', '-m', 'version 3')
|
||||
pin(clone, 'library', head(served / 'library'))
|
||||
|
||||
child = run_with_pygit2(tmp_path, f'git_compat.open_repo({str(clone)!r}).submodule_update(init=False)')
|
||||
|
||||
assert child.returncode == 0, child.stderr[-600:]
|
||||
assert (clone / 'library/__init__.py').read_text() == 'VERSION = 3'
|
||||
|
||||
|
||||
def test_fetch_of_a_remote_with_an_ssh_url(tmp_path, git_host_behind_a_proxy): # noqa: F811
|
||||
repository(tmp_path / 'fixture')
|
||||
clone = tmp_path / 'clone'
|
||||
git_with_local_submodules(tmp_path, 'clone', '-q', str(tmp_path / 'fixture'), str(clone))
|
||||
git_with_local_submodules(clone, 'remote', 'set-url', 'origin', 'git@localhost:fixture')
|
||||
(tmp_path / 'fixture/__init__.py').write_text('VERSION = 3')
|
||||
git_with_local_submodules(tmp_path / 'fixture', 'commit', '-q', '-a', '-m', 'version 3')
|
||||
|
||||
child = run_with_pygit2(tmp_path, f'git_compat.open_repo({str(clone)!r}).fetch_remote_by_index(0)')
|
||||
|
||||
assert child.returncode == 0, child.stderr[-600:]
|
||||
git_with_local_submodules(clone, 'cat-file', '-e', head(tmp_path / 'fixture'))
|
||||
@@ -0,0 +1,585 @@
|
||||
import os
|
||||
import shutil
|
||||
import socket
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import pytest
|
||||
|
||||
from _install_flags_testutil import GIT_LOCATION
|
||||
from test_git_commit_and_submodules import git_with_local_submodules, head, repository, repository_with_a_submodule
|
||||
|
||||
pytest.importorskip('pygit2')
|
||||
|
||||
# For a git server: what `pack-objects` writes to stderr reaches the client as a progress message, here the first
|
||||
# two bytes of a Korean character. pygit2 decodes each piece of a message, and a piece can end like that.
|
||||
MESSAGE_CUT_IN_A_CHARACTER = {'GIT_CONFIG_COUNT': '1', 'GIT_CONFIG_KEY_0': 'uploadpack.packObjectsHook',
|
||||
'GIT_CONFIG_VALUE_0': """sh -c 'printf "\\355\\225" >&2; exec "$@"' --"""}
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def git_finds_its_repository_by_the_directory(monkeypatch):
|
||||
for name in GIT_LOCATION:
|
||||
monkeypatch.delenv(name, raising=False)
|
||||
|
||||
|
||||
def run_with_pygit2(tmp_path, code):
|
||||
(tmp_path / 'no-git').mkdir(exist_ok=True)
|
||||
common = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'comfyui_manager', 'common')
|
||||
code = f'import sys; sys.path.insert(0, {common!r}); import git_compat\nassert git_compat.USE_PYGIT2\n{code}\n'
|
||||
env = {key: value for key, value in os.environ.items() if key not in ('GIT_EXE_PATH', 'GIT_PYTHON_GIT_EXECUTABLE')}
|
||||
return subprocess.run([sys.executable, '-c', code], env={**env, 'PATH': str(tmp_path / 'no-git'), 'CM_USE_PYGIT2': '1'},
|
||||
capture_output=True, text=True)
|
||||
|
||||
|
||||
def update_submodules_with_pygit2(tmp_path, clone, init=True, first=''):
|
||||
return run_with_pygit2(tmp_path, f'{first}\ngit_compat.open_repo({str(clone)!r}).submodule_update(init={init})')
|
||||
|
||||
|
||||
def test_pygit2_updates_the_fetched_submodules_beside_one_never_fetched(tmp_path):
|
||||
library = repository(tmp_path / 'library')
|
||||
origin = tmp_path / 'origin'
|
||||
origin.mkdir()
|
||||
git_with_local_submodules(origin, 'init', '-q')
|
||||
for name in ('a-never-fetched', 'b-fetched'):
|
||||
git_with_local_submodules(origin, 'submodule', 'add', '-q', str(tmp_path / 'library'), name)
|
||||
git_with_local_submodules(origin, 'commit', '-q', '-a', '-m', 'two submodules')
|
||||
clone = tmp_path / 'clone'
|
||||
git_with_local_submodules(tmp_path, 'clone', '-q', str(origin), str(clone))
|
||||
git_with_local_submodules(clone, 'submodule', 'update', '-q', '--init', 'b-fetched')
|
||||
git_with_local_submodules(clone / 'b-fetched', 'checkout', '-q', library[0])
|
||||
(tmp_path / 'no-git').mkdir()
|
||||
common = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'comfyui_manager', 'common')
|
||||
code = (f'import sys; sys.path.insert(0, {common!r}); import git_compat\n'
|
||||
f'assert git_compat.USE_PYGIT2\ngit_compat.open_repo({str(clone)!r}).submodule_update(init=False)\n')
|
||||
env = {key: value for key, value in os.environ.items() if key not in ('GIT_EXE_PATH', 'GIT_PYTHON_GIT_EXECUTABLE')}
|
||||
|
||||
child = subprocess.run([sys.executable, '-c', code], env={**env, 'PATH': str(tmp_path / 'no-git'), 'CM_USE_PYGIT2': '1'},
|
||||
capture_output=True, text=True)
|
||||
|
||||
assert child.returncode == 0, child.stderr
|
||||
assert head(clone / 'b-fetched') == library[1]
|
||||
assert os.listdir(clone / 'a-never-fetched') == []
|
||||
|
||||
|
||||
def test_pygit2_updates_a_submodule_of_a_submodule(tmp_path):
|
||||
library, _ = repository_with_a_submodule(tmp_path)
|
||||
outer = tmp_path / 'outer'
|
||||
outer.mkdir()
|
||||
git_with_local_submodules(outer, 'init', '-q')
|
||||
git_with_local_submodules(outer, 'submodule', 'add', '-q', str(tmp_path / 'origin'), 'origin')
|
||||
git_with_local_submodules(outer, 'commit', '-q', '-a', '-m', 'a submodule with a submodule')
|
||||
clone = tmp_path / 'clone'
|
||||
git_with_local_submodules(tmp_path, 'clone', '-q', str(outer), str(clone))
|
||||
|
||||
child = update_submodules_with_pygit2(tmp_path, clone)
|
||||
|
||||
assert child.returncode == 0, child.stderr
|
||||
assert (clone / 'origin/library/__init__.py').exists()
|
||||
assert head(clone / 'origin/library') == library[1]
|
||||
|
||||
git_with_local_submodules(clone / 'origin/library', 'checkout', '-q', library[0])
|
||||
child = update_submodules_with_pygit2(tmp_path, clone)
|
||||
|
||||
assert child.returncode == 0, child.stderr
|
||||
assert head(clone / 'origin/library') == library[1]
|
||||
|
||||
git_with_local_submodules(clone / 'origin/library', 'checkout', '-q', library[0])
|
||||
child = update_submodules_with_pygit2(tmp_path, clone, init=False)
|
||||
|
||||
assert child.returncode == 0, child.stderr
|
||||
assert head(clone / 'origin/library') == library[1]
|
||||
|
||||
|
||||
def test_pygit2_leaves_a_submodule_of_a_submodule_that_was_never_fetched_alone(tmp_path):
|
||||
repository_with_a_submodule(tmp_path)
|
||||
outer, clone = tmp_path / 'outer', tmp_path / 'clone'
|
||||
outer.mkdir()
|
||||
git_with_local_submodules(outer, 'init', '-q')
|
||||
git_with_local_submodules(outer, 'submodule', 'add', '-q', str(tmp_path / 'origin'), 'origin')
|
||||
git_with_local_submodules(outer, 'commit', '-q', '-a', '-m', 'a submodule with a submodule')
|
||||
git_with_local_submodules(tmp_path, 'clone', '-q', str(outer), str(clone))
|
||||
git_with_local_submodules(clone, 'submodule', 'update', '-q', '--init', 'origin')
|
||||
|
||||
child = update_submodules_with_pygit2(tmp_path, clone, init=False)
|
||||
|
||||
assert child.returncode == 0, child.stderr
|
||||
assert os.listdir(clone / 'origin/library') == []
|
||||
|
||||
|
||||
def test_pygit2_passes_over_a_submodule_that_gitmodules_alone_names(tmp_path):
|
||||
"""As git does: an entry left in `.gitmodules` for a submodule that was removed is not a failure."""
|
||||
library, _ = repository_with_a_submodule(tmp_path)
|
||||
with open(tmp_path / 'origin/.gitmodules', 'a', encoding='utf-8') as gitmodules:
|
||||
gitmodules.write(f'[submodule "a-removed"]\n\tpath = a-removed\n\turl = {(tmp_path / "nowhere").as_posix()}\n')
|
||||
git_with_local_submodules(tmp_path / 'origin', 'commit', '-q', '-a', '-m', 'an entry without a submodule')
|
||||
clone = tmp_path / 'clone'
|
||||
git_with_local_submodules(tmp_path, 'clone', '-q', str(tmp_path / 'origin'), str(clone))
|
||||
|
||||
child = update_submodules_with_pygit2(tmp_path, clone)
|
||||
|
||||
assert child.returncode == 0, child.stderr
|
||||
assert head(clone / 'library') == library[1]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('init', [True, False])
|
||||
def test_pygit2_passes_over_a_submodule_that_gitmodules_alone_names_whose_directory_was_fetched(tmp_path, init):
|
||||
"""As git leaves it after a pull that removed the submodule: its directory is still there."""
|
||||
library, _ = repository_with_a_submodule(tmp_path)
|
||||
origin, clone = tmp_path / 'origin', tmp_path / 'clone'
|
||||
git_with_local_submodules(origin, 'submodule', 'add', '-q', str(tmp_path / 'library'), 'a-removed')
|
||||
git_with_local_submodules(origin, 'commit', '-q', '-m', 'a submodule that is removed next')
|
||||
git_with_local_submodules(tmp_path, 'clone', '-q', '--recursive', str(origin), str(clone))
|
||||
git_with_local_submodules(origin, 'rm', '-q', '--cached', 'a-removed')
|
||||
git_with_local_submodules(origin, 'commit', '-q', '-m', 'an entry without a submodule')
|
||||
git_with_local_submodules(clone, 'pull', '-q')
|
||||
git_with_local_submodules(clone / 'library', 'checkout', '-q', library[0])
|
||||
|
||||
child = update_submodules_with_pygit2(tmp_path, clone, init=init)
|
||||
|
||||
assert child.returncode == 0, child.stderr
|
||||
assert head(clone / 'library') == library[1]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('init', [True, False])
|
||||
def test_pygit2_updates_a_submodule_whose_name_is_not_its_path(tmp_path, init):
|
||||
repository(tmp_path / 'library')
|
||||
origin, clone = tmp_path / 'origin', tmp_path / 'clone'
|
||||
origin.mkdir()
|
||||
git_with_local_submodules(origin, 'init', '-q')
|
||||
git_with_local_submodules(origin, 'submodule', 'add', '-q', '--name', 'vendor', str(tmp_path / 'library'), 'third_party/library')
|
||||
git_with_local_submodules(origin, 'commit', '-q', '-m', 'a submodule with a name of its own')
|
||||
if init:
|
||||
git_with_local_submodules(tmp_path, 'clone', '-q', str(origin), str(clone))
|
||||
else:
|
||||
git_with_local_submodules(tmp_path, 'clone', '-q', '--recursive', str(origin), str(clone))
|
||||
git_with_local_submodules(clone / 'third_party/library', 'checkout', '-q', 'HEAD~1')
|
||||
|
||||
child = update_submodules_with_pygit2(tmp_path, clone, init=init)
|
||||
|
||||
assert child.returncode == 0, child.stderr
|
||||
assert (clone / 'third_party/library/__init__.py').read_text() == 'VERSION = 2'
|
||||
|
||||
|
||||
def test_pygit2_passes_over_a_submodule_whose_name_is_not_one_that_git_accepts(tmp_path):
|
||||
"""As git does at a clone: a name is a folder in `.git/modules`, and one that leads out of it is not followed."""
|
||||
library, _ = repository_with_a_submodule(tmp_path)
|
||||
origin, clone = tmp_path / 'origin', tmp_path / 'clone'
|
||||
git_with_local_submodules(origin, 'submodule', 'add', '-q', '--name', 'another', str(tmp_path / 'library'), 'another')
|
||||
gitmodules = (origin / '.gitmodules').read_text()
|
||||
(origin / '.gitmodules').write_text(gitmodules.replace('[submodule "another"]', '[submodule "../../../beside"]'))
|
||||
git_with_local_submodules(origin, 'commit', '-q', '-a', '-m', 'a name that leads out')
|
||||
git_with_local_submodules(tmp_path, 'clone', '-q', str(origin), str(clone))
|
||||
|
||||
child = update_submodules_with_pygit2(tmp_path, clone)
|
||||
|
||||
assert child.returncode == 0, child.stderr
|
||||
assert head(clone / 'library') == library[1]
|
||||
assert os.listdir(clone / 'another') == []
|
||||
assert not (tmp_path / 'beside').exists()
|
||||
|
||||
|
||||
def test_pygit2_passes_over_a_submodule_whose_path_leads_out_of_the_nodepack(tmp_path):
|
||||
library = repository(tmp_path / 'library')
|
||||
origin, clone = tmp_path / 'origin', tmp_path / 'packs/clone'
|
||||
origin.mkdir()
|
||||
git_with_local_submodules(origin, 'init', '-q')
|
||||
|
||||
def object_of(kind, text):
|
||||
return subprocess.run(['git', kind, *(['-w', '--stdin'] if kind == 'hash-object' else [])], cwd=origin, input=text, check=True,
|
||||
capture_output=True, text=True).stdout.strip()
|
||||
|
||||
gitmodules = f'[submodule "outside"]\n\tpath = a/../../outside\n\turl = {(tmp_path / "library").as_posix()}\n'
|
||||
tree = object_of('mktree', f'160000 commit {library[1]}\toutside\n')
|
||||
for name in ('..', '..'):
|
||||
tree = object_of('mktree', f'040000 tree {tree}\t{name}\n')
|
||||
tree = object_of('mktree', f'100644 blob {object_of("hash-object", gitmodules)}\t.gitmodules\n040000 tree {tree}\ta\n')
|
||||
commit = subprocess.run(['git', '-c', 'user.name=test', '-c', 'user.email=test@example.invalid', 'commit-tree', tree, '-m', 'a path that leads out'],
|
||||
cwd=origin, check=True, capture_output=True, text=True).stdout.strip()
|
||||
git_with_local_submodules(origin, 'update-ref', 'HEAD', commit)
|
||||
(tmp_path / 'packs').mkdir()
|
||||
# git does not check such a tree out
|
||||
git_with_local_submodules(tmp_path, 'clone', '-q', '--no-checkout', str(origin), str(clone))
|
||||
(clone / '.gitmodules').write_text(gitmodules)
|
||||
|
||||
child = update_submodules_with_pygit2(tmp_path, clone)
|
||||
|
||||
assert child.returncode == 0, child.stderr
|
||||
assert not (tmp_path / 'packs/outside').exists()
|
||||
|
||||
|
||||
def test_pygit2_passes_over_a_submodule_without_a_url(tmp_path):
|
||||
library, _ = repository_with_a_submodule(tmp_path)
|
||||
origin, clone = tmp_path / 'origin', tmp_path / 'clone'
|
||||
git_with_local_submodules(origin, 'submodule', 'add', '-q', str(tmp_path / 'library'), 'a-without-a-url')
|
||||
git_with_local_submodules(origin, 'config', '-f', '.gitmodules', '--unset', 'submodule.a-without-a-url.url')
|
||||
git_with_local_submodules(origin, 'commit', '-q', '-a', '-m', 'an entry without a url')
|
||||
git_with_local_submodules(tmp_path, 'clone', '-q', str(origin), str(clone))
|
||||
|
||||
child = update_submodules_with_pygit2(tmp_path, clone)
|
||||
|
||||
assert child.returncode == 0, child.stderr
|
||||
assert head(clone / 'library') == library[1]
|
||||
assert os.listdir(clone / 'a-without-a-url') == []
|
||||
|
||||
|
||||
def add_repository_without_gitmodules(tmp_path, origin):
|
||||
repository(origin / 'stray')
|
||||
git_with_local_submodules(origin, 'add', 'stray')
|
||||
git_with_local_submodules(origin, 'commit', '-q', '-m', 'a repository added without `git submodule`')
|
||||
clone = tmp_path / 'clone'
|
||||
git_with_local_submodules(tmp_path, 'clone', '-q', str(origin), str(clone))
|
||||
return clone
|
||||
|
||||
|
||||
def test_pygit2_passes_over_a_commit_in_the_tree_without_gitmodules(tmp_path):
|
||||
repository(tmp_path / 'origin')
|
||||
clone = add_repository_without_gitmodules(tmp_path, tmp_path / 'origin')
|
||||
|
||||
child = update_submodules_with_pygit2(tmp_path, clone)
|
||||
|
||||
assert child.returncode == 0, child.stderr
|
||||
assert os.listdir(clone / 'stray') == []
|
||||
|
||||
|
||||
def test_pygit2_updates_the_submodules_beside_a_commit_that_gitmodules_does_not_name(tmp_path):
|
||||
library, _ = repository_with_a_submodule(tmp_path)
|
||||
clone = add_repository_without_gitmodules(tmp_path, tmp_path / 'origin')
|
||||
|
||||
child = update_submodules_with_pygit2(tmp_path, clone)
|
||||
|
||||
assert child.returncode == 0, child.stderr
|
||||
assert head(clone / 'library') == library[1]
|
||||
|
||||
|
||||
def test_pygit2_does_not_pass_over_a_submodule_it_could_not_fetch(tmp_path):
|
||||
repository_with_a_submodule(tmp_path)
|
||||
clone = tmp_path / 'clone'
|
||||
git_with_local_submodules(tmp_path, 'clone', '-q', str(tmp_path / 'origin'), str(clone))
|
||||
# moved, as git makes files read-only that Windows does not remove
|
||||
(tmp_path / 'library').rename(tmp_path / 'library.away')
|
||||
|
||||
child = update_submodules_with_pygit2(tmp_path, clone)
|
||||
|
||||
assert child.returncode != 0, child.stderr
|
||||
assert 'GitCommandError' in child.stderr
|
||||
|
||||
|
||||
def test_pygit2_does_not_pass_over_a_git_that_did_not_come_back(tmp_path):
|
||||
repository_with_a_submodule(tmp_path)
|
||||
clone = tmp_path / 'clone'
|
||||
git_with_local_submodules(tmp_path, 'clone', '-q', str(tmp_path / 'origin'), str(clone))
|
||||
# moved, as git makes files read-only that Windows does not remove
|
||||
(tmp_path / 'library').rename(tmp_path / 'library.away')
|
||||
late = ('import subprocess\n'
|
||||
'def late(command, timeout, **_):\n'
|
||||
' raise subprocess.TimeoutExpired(command, timeout)\n'
|
||||
'subprocess.run = late')
|
||||
|
||||
child = update_submodules_with_pygit2(tmp_path, clone, first=late)
|
||||
|
||||
assert child.returncode != 0, child.stderr
|
||||
assert 'TimeoutExpired' in child.stderr
|
||||
|
||||
|
||||
@pytest.mark.parametrize('submodules', [['library'], ['asset', 'library']], ids=['alone', 'after one that was fetched'])
|
||||
def test_pygit2_fetches_a_submodule_whose_fetch_failed_at_the_update_before(tmp_path, submodules):
|
||||
origin, pack = tmp_path / 'origin', tmp_path / 'pack'
|
||||
repository(origin)
|
||||
git_with_local_submodules(tmp_path, 'clone', '-q', str(origin), str(pack))
|
||||
for name in submodules:
|
||||
repository(tmp_path / name)
|
||||
git_with_local_submodules(origin, 'submodule', 'add', '-q', str(tmp_path / name), name)
|
||||
git_with_local_submodules(origin, 'commit', '-q', '-m', 'submodules')
|
||||
(tmp_path / 'library').rename(tmp_path / 'library.away')
|
||||
update = (f'repo = git_compat.open_repo({str(pack)!r})\n'
|
||||
'commit = repo.head_commit_hexsha\n'
|
||||
'repo.pull_ff_only()\n'
|
||||
'try:\n'
|
||||
' repo.submodule_update()\n'
|
||||
'except Exception:\n'
|
||||
' repo.undo_pull(commit)\n'
|
||||
' raise')
|
||||
|
||||
child = run_with_pygit2(tmp_path, update)
|
||||
|
||||
assert child.returncode != 0, child.stderr
|
||||
assert head(pack) != head(origin)
|
||||
|
||||
(tmp_path / 'library.away').rename(tmp_path / 'library')
|
||||
child = run_with_pygit2(tmp_path, update)
|
||||
|
||||
assert child.returncode == 0, child.stderr
|
||||
assert head(pack) == head(origin)
|
||||
for name in submodules:
|
||||
assert (pack / name / '__init__.py').read_text() == 'VERSION = 2'
|
||||
|
||||
|
||||
def library_with_a_commit_that_was_never_pushed(tmp_path):
|
||||
library, _ = repository_with_a_submodule(tmp_path)
|
||||
clone = tmp_path / 'clone'
|
||||
git_with_local_submodules(tmp_path, 'clone', '-q', '--recursive', str(tmp_path / 'origin'), str(clone))
|
||||
git_with_local_submodules(clone / 'library', 'checkout', '-q', '-b', 'work')
|
||||
git_with_local_submodules(clone / 'library', 'commit', '-q', '--allow-empty', '-m', 'a commit that was never pushed')
|
||||
never_pushed = head(clone / 'library')
|
||||
git_with_local_submodules(clone / 'library', 'checkout', '-q', library[1])
|
||||
return clone, library[1], never_pushed
|
||||
|
||||
|
||||
def removed_by_git(clone):
|
||||
git_with_local_submodules(clone, 'submodule', 'deinit', '-q', '-f', 'library')
|
||||
|
||||
|
||||
def removed_by_hand(clone):
|
||||
shutil.rmtree(clone / 'library')
|
||||
|
||||
|
||||
def removed_with_a_head_that_names_no_branch(clone):
|
||||
removed_by_git(clone)
|
||||
(clone / '.git/modules/library/HEAD').write_text('ref: refs/heads/a-branch-that-is-not-there\n')
|
||||
|
||||
|
||||
@pytest.mark.parametrize('remove', [removed_by_git, removed_by_hand, removed_with_a_head_that_names_no_branch])
|
||||
def test_pygit2_checks_a_submodule_out_again_with_the_commits_that_are_in_it_alone(tmp_path, remove):
|
||||
clone, pinned, never_pushed = library_with_a_commit_that_was_never_pushed(tmp_path)
|
||||
remove(clone)
|
||||
|
||||
child = update_submodules_with_pygit2(tmp_path, clone)
|
||||
|
||||
assert child.returncode == 0, child.stderr
|
||||
assert (clone / 'library/__init__.py').read_text() == 'VERSION = 2'
|
||||
assert head(clone / 'library') == pinned
|
||||
assert subprocess.run(['git', 'cat-file', '-e', never_pushed], cwd=clone / 'library').returncode == 0
|
||||
top = subprocess.run(['git', '--git-dir', str(clone / '.git/modules/library'), 'rev-parse', '--show-toplevel'], capture_output=True, text=True)
|
||||
assert os.path.samefile(top.stdout.strip(), clone / 'library'), top.stderr
|
||||
|
||||
|
||||
def test_pygit2_checks_out_again_a_submodule_whose_name_is_not_its_path(tmp_path):
|
||||
library = repository(tmp_path / 'library')
|
||||
origin, clone = tmp_path / 'origin', tmp_path / 'clone'
|
||||
origin.mkdir()
|
||||
git_with_local_submodules(origin, 'init', '-q')
|
||||
git_with_local_submodules(origin, 'submodule', 'add', '-q', '--name', 'vendor', str(tmp_path / 'library'), 'third_party/library')
|
||||
git_with_local_submodules(origin, 'commit', '-q', '-m', 'a submodule with a name of its own')
|
||||
child = run_with_pygit2(tmp_path, f'git_compat.clone_repo({str(origin)!r}, {str(clone)!r})')
|
||||
assert child.returncode == 0, child.stderr
|
||||
git_with_local_submodules(clone / 'third_party/library', 'commit', '-q', '--allow-empty', '-m', 'a commit that was never pushed')
|
||||
never_pushed = head(clone / 'third_party/library')
|
||||
git_with_local_submodules(clone / 'third_party/library', 'checkout', '-q', library[1])
|
||||
shutil.rmtree(clone / 'third_party/library')
|
||||
|
||||
child = update_submodules_with_pygit2(tmp_path, clone)
|
||||
|
||||
assert child.returncode == 0, child.stderr
|
||||
assert head(clone / 'third_party/library') == library[1]
|
||||
assert subprocess.run(['git', 'cat-file', '-e', never_pushed], cwd=clone / 'third_party/library').returncode == 0
|
||||
|
||||
|
||||
def test_pygit2_leaves_the_repository_of_another_submodule_where_it_is(tmp_path):
|
||||
"""git keeps the repository of a submodule in `.git/modules` under its name, and pygit2 under its path: `lib` is both here."""
|
||||
repository(tmp_path / 'library')
|
||||
repository(tmp_path / 'another')
|
||||
origin, clone = tmp_path / 'origin', tmp_path / 'clone'
|
||||
origin.mkdir()
|
||||
git_with_local_submodules(origin, 'init', '-q')
|
||||
git_with_local_submodules(origin, 'submodule', 'add', '-q', '--name', 'lib', str(tmp_path / 'library'), 'vendor/lib')
|
||||
git_with_local_submodules(origin, 'commit', '-q', '-m', 'a submodule named lib')
|
||||
git_with_local_submodules(tmp_path, 'clone', '-q', '--recursive', str(origin), str(clone))
|
||||
git_with_local_submodules(origin, 'submodule', 'add', '-q', '--name', 'another', str(tmp_path / 'another'), 'lib')
|
||||
git_with_local_submodules(origin, 'commit', '-q', '-m', 'a submodule at lib')
|
||||
git_with_local_submodules(clone, 'pull', '-q')
|
||||
|
||||
child = update_submodules_with_pygit2(tmp_path, clone)
|
||||
|
||||
assert child.returncode != 0
|
||||
assert os.listdir(clone / 'lib') == []
|
||||
top = subprocess.run(['git', 'rev-parse', '--show-toplevel'], cwd=clone / 'vendor/lib', check=True, capture_output=True, text=True)
|
||||
assert os.path.samefile(top.stdout.strip(), clone / 'vendor/lib')
|
||||
|
||||
|
||||
def test_pygit2_fetches_a_submodule_where_a_folder_that_is_no_repository_is_left(tmp_path):
|
||||
library, _ = repository_with_a_submodule(tmp_path)
|
||||
clone = tmp_path / 'clone'
|
||||
git_with_local_submodules(tmp_path, 'clone', '-q', str(tmp_path / 'origin'), str(clone))
|
||||
(clone / '.git/modules/library').mkdir(parents=True)
|
||||
(clone / '.git/modules/library/a-file').write_text('')
|
||||
|
||||
child = update_submodules_with_pygit2(tmp_path, clone)
|
||||
|
||||
assert child.returncode == 0, child.stderr
|
||||
assert head(clone / 'library') == library[1]
|
||||
assert os.listdir(clone / '.git/modules/library') != ['a-file', 'config']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('names_its_folder', [True, False])
|
||||
def test_pygit2_keeps_what_was_changed_in_a_submodule_that_is_at_its_commit(tmp_path, names_its_folder):
|
||||
repository_with_a_submodule(tmp_path)
|
||||
clone = tmp_path / 'clone'
|
||||
git_with_local_submodules(tmp_path, 'clone', '-q', '--recursive', str(tmp_path / 'origin'), str(clone))
|
||||
(clone / 'library/__init__.py').write_text('changed by the user')
|
||||
if not names_its_folder:
|
||||
git_with_local_submodules(clone / 'library', 'config', '--unset', 'core.worktree')
|
||||
|
||||
child = update_submodules_with_pygit2(tmp_path, clone)
|
||||
|
||||
assert child.returncode == 0, child.stderr
|
||||
assert (clone / 'library/__init__.py').read_text() == 'changed by the user'
|
||||
|
||||
|
||||
def test_pygit2_checks_a_submodule_out_again_without_a_clone_when_a_proxy_is_set(tmp_path, monkeypatch):
|
||||
clone, pinned, _ = library_with_a_commit_that_was_never_pushed(tmp_path)
|
||||
removed_by_git(clone)
|
||||
(tmp_path / 'home').mkdir()
|
||||
(tmp_path / 'home/.gitconfig').write_text('[http]\n\tproxy = http://127.0.0.1:9\n')
|
||||
monkeypatch.setenv('HOME', str(tmp_path / 'home'))
|
||||
|
||||
child = update_submodules_with_pygit2(tmp_path, clone)
|
||||
|
||||
assert child.returncode == 0, child.stderr
|
||||
assert head(clone / 'library') == pinned
|
||||
|
||||
|
||||
class GitHostBehindAProxy(BaseHTTPRequestHandler):
|
||||
protocol_version = 'HTTP/1.1'
|
||||
|
||||
def handle(self):
|
||||
# one that did not ask the proxy begins with a TLS hello, and is not answered
|
||||
if self.connection.recv(1, socket.MSG_PEEK) == b'C':
|
||||
super().handle()
|
||||
|
||||
def do_CONNECT(self):
|
||||
self.send_response(200)
|
||||
self.end_headers()
|
||||
self.connection = self.server.tls.wrap_socket(self.connection, server_side=True)
|
||||
self.rfile = self.connection.makefile('rb')
|
||||
self.wfile = self.connection.makefile('wb', 0)
|
||||
|
||||
def finish(self):
|
||||
super().finish()
|
||||
self.connection.close()
|
||||
|
||||
def do_GET(self):
|
||||
url = urlsplit(self.path)
|
||||
self.server.asked.add(url.path.split('/')[1])
|
||||
body = self.rfile.read(int(self.headers.get('Content-Length', 0)))
|
||||
cgi = {'GIT_PROJECT_ROOT': self.server.root, 'GIT_HTTP_EXPORT_ALL': '1', 'REQUEST_METHOD': self.command,
|
||||
'PATH_INFO': url.path, 'QUERY_STRING': url.query, 'CONTENT_TYPE': self.headers.get('Content-Type', '')}
|
||||
answer = subprocess.run([self.server.backend], input=body, env={**os.environ, **cgi, **MESSAGE_CUT_IN_A_CHARACTER}, check=True, capture_output=True).stdout
|
||||
headers, _, content = answer.partition(b'\r\n\r\n')
|
||||
status = headers.partition(b'Status: ')[2].split(b'\r\n')[0] or b'200 OK'
|
||||
self.wfile.write(b'HTTP/1.1 %s\r\nContent-Length: %d\r\n%s\r\n\r\n%s' % (status, len(content), headers, content))
|
||||
|
||||
do_POST = do_GET
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def git_host_behind_a_proxy(tmp_path, monkeypatch):
|
||||
backend = os.path.join(subprocess.run(['git', '--exec-path'], check=True, capture_output=True, text=True).stdout.strip(), 'git-http-backend')
|
||||
if not os.path.exists(backend) or shutil.which('openssl') is None:
|
||||
pytest.skip('git-http-backend and openssl are needed')
|
||||
|
||||
# https, and a name: libgit2 leaves the proxy aside for http, and does not match a certificate with an address
|
||||
certificate, key = str(tmp_path / 'certificate.pem'), str(tmp_path / 'key.pem')
|
||||
subprocess.run(['openssl', 'req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-days', '2', '-keyout', key, '-out', certificate,
|
||||
'-subj', '/CN=localhost', '-addext', 'subjectAltName=DNS:localhost'], check=True, capture_output=True)
|
||||
server = ThreadingHTTPServer(('127.0.0.1', 0), GitHostBehindAProxy)
|
||||
server.tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
server.tls.load_cert_chain(certificate, key)
|
||||
server.backend, server.root, server.asked = backend, str(tmp_path), set()
|
||||
server.url = 'https://localhost:%d/' % server.server_port
|
||||
|
||||
(tmp_path / 'home').mkdir()
|
||||
(tmp_path / 'home/.gitconfig').write_text('[http]\n\tproxy = http://127.0.0.1:%d\n' % server.server_port)
|
||||
monkeypatch.setenv('HOME', str(tmp_path / 'home'))
|
||||
monkeypatch.setenv('SSL_CERT_FILE', certificate)
|
||||
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
yield server
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def pin(path, submodule, commit):
|
||||
git_with_local_submodules(path, 'update-index', '--cacheinfo', f'160000,{commit},{submodule}')
|
||||
git_with_local_submodules(path, 'commit', '-q', '-m', f'{submodule} at {commit}')
|
||||
return head(path)
|
||||
|
||||
|
||||
def test_pygit2_fetches_the_submodules_through_the_proxy(tmp_path, git_host_behind_a_proxy):
|
||||
library, _ = repository_with_a_submodule(tmp_path)
|
||||
origin, outer, clone = tmp_path / 'origin', tmp_path / 'outer', tmp_path / 'clone'
|
||||
git_with_local_submodules(origin, 'config', '-f', '.gitmodules', 'submodule.library.url', '../library')
|
||||
git_with_local_submodules(origin, 'commit', '-q', '-a', '-m', 'the library beside it')
|
||||
outer.mkdir()
|
||||
git_with_local_submodules(outer, 'init', '-q')
|
||||
git_with_local_submodules(outer, 'submodule', 'add', '-q', '../origin', 'origin')
|
||||
git_with_local_submodules(outer, 'commit', '-q', '-a', '-m', 'a submodule with a submodule')
|
||||
|
||||
cloned = f'git_compat.clone_repo({git_host_behind_a_proxy.url + "outer"!r}, {str(clone)!r})'
|
||||
child = update_submodules_with_pygit2(tmp_path, clone, first=cloned)
|
||||
|
||||
assert child.returncode == 0, child.stderr
|
||||
assert head(clone / 'origin/library') == library[1]
|
||||
assert git_host_behind_a_proxy.asked == {'outer', 'origin', 'library'}
|
||||
|
||||
(tmp_path / 'library/__init__.py').write_text('VERSION = 3')
|
||||
git_with_local_submodules(tmp_path / 'library', 'commit', '-q', '-a', '-m', 'version 3')
|
||||
later = head(tmp_path / 'library')
|
||||
pin(clone, 'origin', pin(origin, 'library', later))
|
||||
child = update_submodules_with_pygit2(tmp_path, clone)
|
||||
|
||||
assert child.returncode == 0, child.stderr
|
||||
assert head(clone / 'origin/library') == later
|
||||
|
||||
(tmp_path / 'library/__init__.py').write_text('VERSION = 4')
|
||||
git_with_local_submodules(tmp_path / 'library', 'commit', '-q', '-a', '-m', 'version 4')
|
||||
latest = head(tmp_path / 'library')
|
||||
pin(clone, 'origin', pin(origin, 'library', latest))
|
||||
child = update_submodules_with_pygit2(tmp_path, clone, init=False)
|
||||
|
||||
assert child.returncode == 0, child.stderr
|
||||
assert head(clone / 'origin/library') == latest
|
||||
|
||||
|
||||
def test_pygit2_fetches_a_submodule_with_an_ssh_url_over_https(tmp_path, git_host_behind_a_proxy):
|
||||
library, _ = repository_with_a_submodule(tmp_path)
|
||||
origin, clone = tmp_path / 'origin', tmp_path / 'clone'
|
||||
git_with_local_submodules(origin, 'config', '-f', '.gitmodules', 'submodule.library.url', 'git@localhost:library')
|
||||
git_with_local_submodules(origin, 'commit', '-q', '-a', '-m', 'an ssh url')
|
||||
|
||||
cloned = f'git_compat.clone_repo({git_host_behind_a_proxy.url + "origin"!r}, {str(clone)!r})'
|
||||
child = update_submodules_with_pygit2(tmp_path, clone, first=cloned)
|
||||
|
||||
assert child.returncode == 0, child.stderr
|
||||
assert head(clone / 'library') == library[1]
|
||||
|
||||
|
||||
def test_pull_of_the_git_helper_with_pygit2_updates_a_pack_whose_submodule_is_at_another_commit(tmp_path):
|
||||
library = repository(tmp_path / 'library')
|
||||
origin = tmp_path / 'origin'
|
||||
origin.mkdir()
|
||||
git_with_local_submodules(origin, 'init', '-q')
|
||||
git_with_local_submodules(origin, 'submodule', 'add', '-q', str(tmp_path / 'library'), 'library')
|
||||
git_with_local_submodules(origin / 'library', 'checkout', '-q', library[0])
|
||||
git_with_local_submodules(origin, 'commit', '-q', '-a', '-m', 'library at its first commit')
|
||||
pack = tmp_path / 'custom_nodes/pack'
|
||||
git_with_local_submodules(tmp_path, 'clone', '-q', '--recursive', str(origin), str(pack))
|
||||
git_with_local_submodules(origin, 'commit', '-q', '--allow-empty', '-m', 'a commit to pull')
|
||||
git_with_local_submodules(pack / 'library', 'checkout', '-q', library[1])
|
||||
(tmp_path / 'folder_paths.py').touch()
|
||||
(tmp_path / 'no-git').mkdir()
|
||||
helper = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'comfyui_manager', 'common', 'git_helper.py')
|
||||
env = {key: value for key, value in os.environ.items() if key not in ('GIT_EXE_PATH', 'GIT_PYTHON_GIT_EXECUTABLE')}
|
||||
|
||||
pulled = subprocess.run([sys.executable, helper, '--pull', str(pack)], cwd=pack.parent, capture_output=True, text=True,
|
||||
env={**env, 'PATH': str(tmp_path / 'no-git'), 'CM_USE_PYGIT2': '1', 'COMFYUI_PATH': str(tmp_path)})
|
||||
|
||||
assert (pulled.returncode, head(pack)) == (0, head(origin)), pulled.stdout + pulled.stderr
|
||||
assert head(pack / 'library') == library[0]
|
||||
@@ -0,0 +1,42 @@
|
||||
import ast
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
PACK = '한글 nodepack'
|
||||
|
||||
|
||||
def reserved(tmp_path, core, call):
|
||||
tests = os.path.dirname(__file__)
|
||||
code = (f'import sys; sys.path[:0] = [{os.path.dirname(tests)!r}, {tests!r}]\n'
|
||||
'from _install_flags_testutil import import_reader\n'
|
||||
f'core = import_reader({core!r})\n'
|
||||
f'core.context.manager_startup_script_path = {str(tmp_path)!r}\n'
|
||||
f'core.get_default_custom_nodes_path = lambda: {str(tmp_path)!r}\n'
|
||||
f'{call}\n')
|
||||
# from a file: with this locale a command line cannot hold the name of the nodepack
|
||||
(tmp_path / 'reserve.py').write_text(code, encoding='utf-8')
|
||||
child = subprocess.run([sys.executable, str(tmp_path / 'reserve.py')], capture_output=True, text=True,
|
||||
env={**os.environ, 'LC_ALL': 'C', 'PYTHONUTF8': '0', 'PYTHONCOERCECLOCALE': '0'})
|
||||
assert child.returncode == 0, child.stderr[-600:]
|
||||
with open(tmp_path / 'install-scripts.txt', encoding='utf-8') as file:
|
||||
return [ast.literal_eval(line) for line in file]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('core', ['glob', 'legacy'])
|
||||
def test_install_script_of_a_pack_whose_path_the_locale_cannot_write_is_reserved(tmp_path, core):
|
||||
path = str(tmp_path / PACK)
|
||||
|
||||
assert reserved(tmp_path, core, f"core.reserve_script({path!r}, ['install.py'])") == [[path, 'install.py']]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('core', ['glob', 'legacy'])
|
||||
def test_switch_of_a_pack_whose_path_the_locale_cannot_write_is_reserved(tmp_path, core):
|
||||
path = str(tmp_path / PACK)
|
||||
call = f"core.UnifiedManager().reserve_cnr_switch('fixture', 'https://example.invalid/fixture.zip', {path!r}, {path!r}, False)"
|
||||
|
||||
entry, = reserved(tmp_path, core, call)
|
||||
|
||||
assert entry[3:5] == [path, path]
|
||||
@@ -114,7 +114,7 @@ def run_restart_site(path, execv):
|
||||
nodes = [node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == "restart"]
|
||||
assert len(nodes) == 1, f"restart code not found in {path}"
|
||||
|
||||
allow = SimpleNamespace(reject_simple_form_post=lambda request: None, is_allowed_security_level=lambda level: True)
|
||||
allow = SimpleNamespace(reject_non_json_post=lambda request: None, is_allowed_security_level=lambda level: True)
|
||||
namespace = {
|
||||
"os": SimpleNamespace(environ={}, path=os.path, execv=execv), # not a comfy-cli session
|
||||
"sys": sys,
|
||||
|
||||
@@ -48,7 +48,7 @@ def restore(monkeypatch, capsys):
|
||||
check_call=check_call, check_output=check_output,
|
||||
CalledProcessError=subprocess.CalledProcessError))
|
||||
|
||||
manager_util.restore_pip_snapshot(PIPS, options)
|
||||
run.not_installed = manager_util.restore_pip_snapshot(PIPS, options)
|
||||
report = capsys.readouterr().out.strip().splitlines()[-1]
|
||||
return commands, report
|
||||
|
||||
@@ -103,6 +103,16 @@ def test_every_failed_package_is_reported(restore):
|
||||
assert report == f"Installation failed for pip packages: {['alpha==1.0', 'beta==2.0', *urls]}"
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failing, not_installed', [
|
||||
([], []),
|
||||
(['beta', 'delta'], ['beta==2.0', 'file:///wheels/delta.whl']),
|
||||
])
|
||||
def test_packages_that_were_not_installed_are_returned(restore, failing, not_installed):
|
||||
restore(['--pip-non-url', '--pip-non-local-url', '--pip-local-url'], failing=failing)
|
||||
|
||||
assert restore.not_installed == not_installed
|
||||
|
||||
|
||||
def test_group_without_its_option_is_left_alone(restore):
|
||||
commands, report = restore([])
|
||||
|
||||
|
||||
@@ -0,0 +1,527 @@
|
||||
import ast
|
||||
import asyncio
|
||||
import os
|
||||
import pathlib
|
||||
import subprocess
|
||||
import traceback
|
||||
from types import SimpleNamespace
|
||||
from typing import Annotated, Optional
|
||||
from unittest.mock import AsyncMock, Mock
|
||||
|
||||
import pytest
|
||||
|
||||
from _install_flags_testutil import GIT_LOCATION
|
||||
from test_snapshot_restore_pins import COMMIT, REPO_URL, core, manager, restore # noqa: F401
|
||||
|
||||
CM_CLI = pathlib.Path(__file__).resolve().parent.parent / 'cm_cli/__main__.py'
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def git_finds_its_repository_by_the_directory(monkeypatch):
|
||||
for name in GIT_LOCATION:
|
||||
monkeypatch.delenv(name, raising=False)
|
||||
|
||||
|
||||
def pinned(url, commit=COMMIT):
|
||||
return {'git_custom_nodes': {url: {'hash': commit, 'disabled': False}}}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def summary(core, tmp_path, capsys): # noqa: F811
|
||||
def summary(**snapshot):
|
||||
restore(core, tmp_path, **snapshot)
|
||||
return [line.strip() for line in capsys.readouterr().out.splitlines() if line.startswith('[ ')]
|
||||
|
||||
return summary
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def answer(core): # noqa: F811
|
||||
def answer(action, ok):
|
||||
result = core.ManagedResult(action)
|
||||
return Mock(return_value=result if ok else result.fail('failed'))
|
||||
|
||||
return answer
|
||||
|
||||
|
||||
def git_pack(path, url):
|
||||
(path / '.git').mkdir(parents=True)
|
||||
(path / '.git/config').write_text('[remote "origin"]\n\turl = %s\n' % url)
|
||||
return url, str(path)
|
||||
|
||||
|
||||
def in_registry(manager): # noqa: F811
|
||||
manager.repo_cnr_map[REPO_URL] = {'id': 'fixture'}
|
||||
manager.get_custom_nodes.return_value = {'fixture': {'repository': REPO_URL}}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def clones(manager, tmp_path): # noqa: F811
|
||||
def clones(kind, clone):
|
||||
if kind == 'url':
|
||||
manager.repo_install = lambda url, path, return_postinstall=False, **options: clone(path, return_postinstall)
|
||||
return
|
||||
|
||||
async def install(pack_id, version_spec, return_postinstall=False, **options):
|
||||
manager.active_nodes[pack_id] = (version_spec, str(tmp_path / pack_id))
|
||||
return clone(str(tmp_path / pack_id), return_postinstall)
|
||||
|
||||
in_registry(manager)
|
||||
manager.install_by_id = AsyncMock(side_effect=install)
|
||||
|
||||
return clones
|
||||
|
||||
|
||||
CLONES = pytest.mark.parametrize('kind', ['registry', 'url'])
|
||||
|
||||
|
||||
def head(path):
|
||||
return subprocess.run(['git', 'rev-parse', 'HEAD'], cwd=path, check=True, capture_output=True, text=True).stdout.strip()
|
||||
|
||||
|
||||
def repository(path):
|
||||
path.mkdir(parents=True)
|
||||
commits = []
|
||||
for version in (1, 2):
|
||||
(path / '__init__.py').write_text('VERSION = %d' % version)
|
||||
for args in (['init', '-q'], ['add', '.'],
|
||||
['-c', 'user.name=test', '-c', 'user.email=test@example.invalid', 'commit', '-q', '-m', 'version %d' % version]):
|
||||
subprocess.run(['git', *args], cwd=path, check=True, capture_output=True)
|
||||
commits.append(head(path))
|
||||
return commits
|
||||
|
||||
|
||||
@pytest.mark.parametrize('cloned, line', [(True, '[ INSTALLED ] fixture'), (False, '[ FAILED ] fixture')])
|
||||
def test_clone_follows_its_result(core, manager, summary, answer, monkeypatch, tmp_path, cloned, line): # noqa: F811
|
||||
manager.repo_install = answer('install-git', cloned)
|
||||
monkeypatch.setattr(core, 'repo_switch_commit', Mock(return_value=True))
|
||||
|
||||
assert summary(**pinned(REPO_URL + '.git')) == [line]
|
||||
assert manager.repo_install.call_args.args[1] == str(tmp_path / 'fixture')
|
||||
|
||||
|
||||
def test_url_that_is_not_cloned_is_reported_as_failed(manager, summary, tmp_path): # noqa: F811
|
||||
assert summary(**pinned('/home/someone/repos/fixture')) == ['[ FAILED ] fixture']
|
||||
assert not (tmp_path / 'fixture').exists()
|
||||
|
||||
|
||||
def test_url_that_cannot_be_parsed_is_reported_as_failed_and_the_restore_goes_on(manager, summary): # noqa: F811
|
||||
entry = {'hash': COMMIT, 'disabled': False}
|
||||
|
||||
assert summary(git_custom_nodes={'https://[not-a-host/first': dict(entry), '/home/someone/repos/second': dict(entry)}) == [
|
||||
'[ FAILED ] first', '[ FAILED ] second']
|
||||
|
||||
|
||||
def test_cloned_pack_is_checked_out_at_the_pinned_commit(core, manager, summary, tmp_path): # noqa: F811
|
||||
commits = repository(tmp_path / 'origin')
|
||||
|
||||
def clone(url, path, **options):
|
||||
subprocess.run(['git', 'clone', '-q', str(tmp_path / 'origin'), path], check=True, capture_output=True)
|
||||
return core.ManagedResult('install-git')
|
||||
|
||||
manager.repo_install = clone
|
||||
|
||||
assert summary(**pinned(REPO_URL, commits[0])) == ['[ INSTALLED ] fixture']
|
||||
assert head(tmp_path / 'fixture') == commits[0]
|
||||
assert (tmp_path / 'fixture/__init__.py').read_text() == 'VERSION = 1'
|
||||
|
||||
|
||||
def test_cloned_registry_pack_is_checked_out_at_the_pinned_commit(core, manager, summary, tmp_path): # noqa: F811
|
||||
commits = repository(tmp_path / 'origin')
|
||||
|
||||
async def install(pack_id, version_spec, **options):
|
||||
subprocess.run(['git', 'clone', '-q', str(tmp_path / 'origin'), tmp_path / pack_id], check=True, capture_output=True)
|
||||
manager.active_nodes[pack_id] = (version_spec, str(tmp_path / pack_id))
|
||||
return core.ManagedResult('install-git')
|
||||
|
||||
manager.repo_cnr_map[REPO_URL] = {'id': 'fixture'}
|
||||
manager.install_by_id = AsyncMock(side_effect=install)
|
||||
|
||||
assert summary(**pinned(REPO_URL, commits[0])) == ['[ INSTALLED ] fixture']
|
||||
assert head(tmp_path / 'fixture') == commits[0]
|
||||
|
||||
|
||||
def test_cloned_pack_that_cannot_be_checked_out_is_reported_as_failed(manager, summary, answer): # noqa: F811
|
||||
manager.repo_install = answer('install-git', True)
|
||||
|
||||
assert summary(**pinned(REPO_URL)) == [f'[ FAILED ] fixture@{COMMIT}']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('disabled, line', [(True, '[ DISABLED ] fixture'), (False, '[ FAILED ] fixture')])
|
||||
def test_disabling_a_git_pack_that_is_not_in_the_snapshot_follows_its_result(manager, summary, answer, tmp_path, disabled, line): # noqa: F811
|
||||
manager.unknown_active_nodes['fixture'] = git_pack(tmp_path / 'fixture', REPO_URL)
|
||||
manager.unified_disable = answer('disable', disabled)
|
||||
|
||||
assert summary() == [line]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('disabled, line', [(True, '[ DISABLED ] fixture'), (False, '[ FAILED ] fixture')])
|
||||
def test_disabling_a_registry_pack_that_is_not_in_the_snapshot_follows_its_result(manager, summary, answer, tmp_path, disabled, line): # noqa: F811
|
||||
manager.active_nodes['fixture'] = ('1.0.0', str(tmp_path / 'fixture'))
|
||||
manager.unified_disable = answer('disable', disabled)
|
||||
|
||||
assert summary() == [line]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('name', ['ComfyUI-Manager', 'comfyui-manager'])
|
||||
def test_the_manager_itself_is_not_listed(manager, summary, answer, tmp_path, name): # noqa: F811
|
||||
manager.unknown_active_nodes[name] = git_pack(tmp_path / name, 'https://github.com/ltdrdata/ComfyUI-Manager')
|
||||
manager.unified_disable = answer('disable', True)
|
||||
|
||||
assert summary() == []
|
||||
assert manager.unified_disable.call_count == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize('enabled, line', [(True, '[ ENABLED ] fixture'), (False, '[ FAILED ] fixture')])
|
||||
def test_enabling_a_git_pack_of_the_snapshot_follows_its_result(core, manager, summary, answer, tmp_path, monkeypatch, enabled, line): # noqa: F811
|
||||
manager.unknown_inactive_nodes['fixture'] = git_pack(tmp_path / '.disabled/fixture', REPO_URL)
|
||||
manager.unified_enable = answer('enable', enabled)
|
||||
manager.unified_enable.return_value.target = str(tmp_path / 'fixture') if enabled else None
|
||||
checkout = Mock(return_value=False)
|
||||
monkeypatch.setattr(core, 'repo_switch_commit', checkout)
|
||||
|
||||
assert summary(**pinned(REPO_URL)) == [line]
|
||||
assert [x.args for x in checkout.call_args_list] == ([(str(tmp_path / 'fixture'), COMMIT)] if enabled else [])
|
||||
|
||||
|
||||
def test_installed_git_pack_the_registry_does_not_know_is_checked_out_at_the_pinned_commit(manager, summary, tmp_path): # noqa: F811
|
||||
commits = repository(tmp_path / 'fixture')
|
||||
subprocess.run(['git', 'remote', 'add', 'origin', REPO_URL], cwd=tmp_path / 'fixture', check=True)
|
||||
manager.unknown_active_nodes['fixture'] = (REPO_URL, str(tmp_path / 'fixture'))
|
||||
|
||||
assert summary(**pinned(REPO_URL, commits[0])) == [f'[ CHECKOUT ] fixture@{commits[0]}']
|
||||
assert head(tmp_path / 'fixture') == commits[0]
|
||||
|
||||
|
||||
NO_COMMIT = pytest.mark.parametrize('entry', [{'hash': 'unknown', 'disabled': False}, {'disabled': False}], ids=['unknown', 'no hash'])
|
||||
|
||||
|
||||
@NO_COMMIT
|
||||
def test_pack_without_a_commit_in_the_snapshot_is_left_where_it_is(manager, summary, tmp_path, entry): # noqa: F811
|
||||
commits = repository(tmp_path / 'fixture')
|
||||
subprocess.run(['git', 'remote', 'add', 'origin', REPO_URL], cwd=tmp_path / 'fixture', check=True)
|
||||
manager.unknown_active_nodes['fixture'] = (REPO_URL, str(tmp_path / 'fixture'))
|
||||
|
||||
assert summary(git_custom_nodes={REPO_URL: entry}) == ['[ SKIPPED ] fixture']
|
||||
assert head(tmp_path / 'fixture') == commits[1]
|
||||
|
||||
|
||||
@CLONES
|
||||
@NO_COMMIT
|
||||
def test_cloned_pack_without_a_commit_in_the_snapshot_is_installed(core, summary, clones, tmp_path, kind, entry): # noqa: F811
|
||||
ran = []
|
||||
clones(kind, lambda path, return_postinstall: core.ManagedResult('install-git').with_postinstall(lambda: ran.append(path) or True))
|
||||
|
||||
assert summary(git_custom_nodes={REPO_URL: entry}) == ['[ INSTALLED ] fixture']
|
||||
assert ran == [str(tmp_path / 'fixture')]
|
||||
|
||||
|
||||
@CLONES
|
||||
@pytest.mark.parametrize('installed, line', [(True, '[ INSTALLED ] fixture'), (False, '[ FAILED ] fixture')])
|
||||
def test_install_script_of_a_cloned_pack_runs_at_the_pinned_commit(core, summary, clones, tmp_path, kind, installed, line): # noqa: F811
|
||||
commits = repository(tmp_path / 'origin')
|
||||
ran_at = []
|
||||
|
||||
def clone(path, return_postinstall):
|
||||
subprocess.run(['git', 'clone', '-q', str(tmp_path / 'origin'), path], check=True, capture_output=True)
|
||||
|
||||
def postinstall():
|
||||
ran_at.append(head(path))
|
||||
return installed
|
||||
|
||||
result = core.ManagedResult('install-git')
|
||||
return result.with_postinstall(postinstall) if return_postinstall else (result if postinstall() else result.fail('install script'))
|
||||
|
||||
clones(kind, clone)
|
||||
|
||||
assert summary(**pinned(REPO_URL, commits[0])) == [line]
|
||||
assert ran_at == [commits[0]]
|
||||
|
||||
|
||||
@CLONES
|
||||
def test_install_script_that_raises_is_reported_as_failed_and_the_restore_goes_on(core, manager, summary, clones, monkeypatch, kind): # noqa: F811
|
||||
def clone(path, return_postinstall):
|
||||
def postinstall():
|
||||
raise subprocess.CalledProcessError(1, ['python', 'install.py'])
|
||||
|
||||
return core.ManagedResult('install-git').with_postinstall(postinstall)
|
||||
|
||||
manager.repo_install = lambda url, path, **options: clone(path, True)
|
||||
clones(kind, clone)
|
||||
monkeypatch.setattr(core, 'repo_switch_commit', Mock(return_value=True))
|
||||
|
||||
assert summary(git_custom_nodes={REPO_URL: {'hash': COMMIT, 'disabled': False},
|
||||
REPO_URL + '-other': {'hash': COMMIT, 'disabled': False}}) == ['[ FAILED ] fixture', '[ FAILED ] fixture-other']
|
||||
|
||||
|
||||
def test_install_script_of_a_cloned_pack_runs_also_when_the_commit_cannot_be_checked_out(core, manager, summary, tmp_path): # noqa: F811
|
||||
ran = []
|
||||
manager.repo_install = lambda url, path, **options: core.ManagedResult('install-git').with_postinstall(lambda: ran.append(path) or True)
|
||||
|
||||
assert summary(**pinned(REPO_URL)) == [f'[ FAILED ] fixture@{COMMIT}']
|
||||
assert ran == [str(tmp_path / 'fixture')]
|
||||
|
||||
|
||||
def test_install_script_of_a_cloned_registry_pack_runs_also_when_the_commit_cannot_be_checked_out(core, manager, summary, tmp_path): # noqa: F811
|
||||
ran = []
|
||||
|
||||
async def install(pack_id, version_spec, **options):
|
||||
manager.active_nodes[pack_id] = (version_spec, str(tmp_path / pack_id))
|
||||
return core.ManagedResult('install-git').with_postinstall(lambda: ran.append(pack_id) or True)
|
||||
|
||||
manager.repo_cnr_map[REPO_URL] = {'id': 'fixture'}
|
||||
manager.install_by_id = AsyncMock(side_effect=install)
|
||||
|
||||
assert summary(**pinned(REPO_URL)) == [f'[ FAILED ] fixture@{COMMIT}']
|
||||
assert ran == ['fixture']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('outcome, line', [(True, '[ INSTALLED ] fixture@1.0.0'), (False, '[ FAILED ] fixture@1.0.0'),
|
||||
(subprocess.CalledProcessError(1, ['python', 'install.py']), '[ FAILED ] fixture@1.0.0')])
|
||||
def test_install_script_of_a_registry_pack_is_run(core, manager, summary, outcome, line): # noqa: F811
|
||||
ran = []
|
||||
|
||||
def postinstall():
|
||||
ran.append('fixture')
|
||||
if isinstance(outcome, Exception):
|
||||
raise outcome
|
||||
return outcome
|
||||
|
||||
manager.install_by_id = AsyncMock(return_value=core.ManagedResult('install-cnr').with_postinstall(postinstall))
|
||||
|
||||
assert summary(cnr_custom_nodes={'fixture': '1.0.0'}) == [line]
|
||||
assert ran == ['fixture']
|
||||
assert manager.install_by_id.await_args.kwargs['return_postinstall'] is True
|
||||
|
||||
|
||||
|
||||
def test_registry_pack_whose_install_raises_is_reported_as_failed_and_the_restore_goes_on(core, manager, summary): # noqa: F811
|
||||
async def install(pack_id, **options):
|
||||
if pack_id == 'fixture':
|
||||
raise ConnectionError('the Registry cannot be reached')
|
||||
return core.ManagedResult('install-cnr')
|
||||
|
||||
manager.install_by_id = AsyncMock(side_effect=install)
|
||||
|
||||
assert summary(cnr_custom_nodes={'fixture': '1.0.0', 'other': '1.0.0'}) == ['[ INSTALLED ] other@1.0.0', '[ FAILED ] fixture@1.0.0']
|
||||
|
||||
|
||||
def test_registry_pack_whose_switch_raises_is_reported_as_failed_and_the_restore_goes_on(core, manager, summary, tmp_path): # noqa: F811
|
||||
manager.active_nodes['fixture'] = ('1.0.0', str(tmp_path / 'fixture'))
|
||||
manager.cnr_switch_version = Mock(side_effect=ConnectionError('the Registry cannot be reached'))
|
||||
manager.install_by_id = AsyncMock(return_value=core.ManagedResult('install-cnr'))
|
||||
|
||||
assert summary(cnr_custom_nodes={'fixture': '2.0.0', 'other': '1.0.0'}) == ['[ INSTALLED ] other@1.0.0', '[ FAILED ] fixture@2.0.0']
|
||||
|
||||
|
||||
def registry_pack(manager, path, name='fixture', url=REPO_URL): # noqa: F811
|
||||
manager.active_nodes[name] = ('1.0.0', str(path / name))
|
||||
|
||||
|
||||
def registry_git_pack(manager, path, name='fixture', url=REPO_URL): # noqa: F811
|
||||
manager.active_nodes[name] = ('nightly', str(path / name))
|
||||
manager.repo_cnr_map[url] = {'id': name}
|
||||
|
||||
|
||||
def disabled_registry_git_pack(manager, path, name='fixture', url=REPO_URL): # noqa: F811
|
||||
manager.nightly_inactive_nodes[name] = git_pack(path / '.disabled' / name, url)[1]
|
||||
manager.repo_cnr_map[url] = {'id': name}
|
||||
|
||||
|
||||
def unknown_git_pack(manager, path, name='fixture', url=REPO_URL): # noqa: F811
|
||||
manager.unknown_active_nodes[name] = git_pack(path / name, url)
|
||||
|
||||
|
||||
def disabled_unknown_git_pack(manager, path, name='fixture', url=REPO_URL): # noqa: F811
|
||||
manager.unknown_inactive_nodes[name] = git_pack(path / '.disabled' / name, url)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('installed, step, in_snapshot', [
|
||||
(registry_pack, 'unified_disable', False),
|
||||
(registry_git_pack, 'unified_disable', False),
|
||||
(unknown_git_pack, 'unified_disable', False),
|
||||
(disabled_registry_git_pack, 'unified_enable', True),
|
||||
(disabled_unknown_git_pack, 'unified_enable', True),
|
||||
])
|
||||
def test_pack_whose_directory_cannot_be_moved_is_reported_as_failed_and_the_restore_goes_on(manager, summary, tmp_path, installed, step, in_snapshot): # noqa: F811
|
||||
"""The second nodepack is the proof that the restore goes on."""
|
||||
packs = {'fixture': REPO_URL, 'second': REPO_URL + '-2'}
|
||||
for name, url in packs.items():
|
||||
installed(manager, tmp_path, name, url)
|
||||
setattr(manager, step, Mock(side_effect=PermissionError(13, 'Permission denied')))
|
||||
snapshot = {url: {'hash': COMMIT, 'disabled': False} for url in packs.values()} if in_snapshot else {}
|
||||
|
||||
assert summary(git_custom_nodes=snapshot) == ['[ FAILED ] fixture', '[ FAILED ] second']
|
||||
assert getattr(manager, step).call_count == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize('installed', [unknown_git_pack, disabled_unknown_git_pack, registry_git_pack, disabled_registry_git_pack])
|
||||
def test_checkout_that_fails_is_reported_as_failed(manager, summary, tmp_path, installed): # noqa: F811
|
||||
installed(manager, tmp_path)
|
||||
|
||||
assert summary(**pinned(REPO_URL)) == [f'[ FAILED ] fixture@{COMMIT}']
|
||||
|
||||
|
||||
def test_pack_that_fails_at_two_steps_is_listed_once(core, manager, summary, answer, tmp_path): # noqa: F811
|
||||
manager.active_nodes['fixture'] = ('1.0.0', str(tmp_path / 'fixture'))
|
||||
in_registry(manager)
|
||||
manager.unified_disable = answer('disable', False)
|
||||
|
||||
async def install(pack_id, version_spec, **options):
|
||||
return core.ManagedResult('install-git').fail('failed')
|
||||
|
||||
manager.install_by_id = install
|
||||
|
||||
assert summary(cnr_custom_nodes={}, **pinned(REPO_URL)) == ['[ FAILED ] fixture']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('pinned_at, line', [(0, '[ CHECKOUT ] fixture@{pinned}'), (1, '[ ENABLED ] fixture')])
|
||||
def test_registry_git_pack_that_is_enabled_is_listed_once(manager, summary, tmp_path, pinned_at, line): # noqa: F811
|
||||
commits = repository(tmp_path / '.disabled/fixture')
|
||||
manager.nightly_inactive_nodes['fixture'] = str(tmp_path / '.disabled/fixture')
|
||||
in_registry(manager)
|
||||
|
||||
assert summary(**pinned(REPO_URL, commits[pinned_at])) == [line.format(pinned=commits[0])]
|
||||
assert head(tmp_path / 'fixture') == commits[pinned_at]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('pinned_at, line', [(0, '[ CHECKOUT ] fixture@{pinned}'), (1, '[ SKIPPED ] fixture')])
|
||||
def test_registry_git_pack_that_is_installed_is_listed_once(manager, summary, tmp_path, pinned_at, line): # noqa: F811
|
||||
commits = repository(tmp_path / 'fixture')
|
||||
manager.active_nodes['fixture'] = ('nightly', str(tmp_path / 'fixture'))
|
||||
in_registry(manager)
|
||||
|
||||
assert summary(**pinned(REPO_URL, commits[pinned_at])) == [line.format(pinned=commits[0])]
|
||||
assert head(tmp_path / 'fixture') == commits[pinned_at]
|
||||
|
||||
|
||||
def packs_that_name(tmp_path, **files):
|
||||
for name in ('first', 'second'):
|
||||
(tmp_path / name).mkdir()
|
||||
for file, text in files.items():
|
||||
(tmp_path / name / file).write_text(text)
|
||||
return str(tmp_path / 'first'), str(tmp_path / 'second')
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def installs(core, monkeypatch): # noqa: F811
|
||||
def installs(*answers):
|
||||
answers, ran = list(answers), []
|
||||
|
||||
def try_install_script(url, repo_path, install_cmd, instant_execution=False):
|
||||
ran.append(os.path.basename(repo_path) + ' ' + install_cmd[-1])
|
||||
return answers.pop(0)
|
||||
|
||||
monkeypatch.setattr(core, 'try_install_script', try_install_script)
|
||||
monkeypatch.setattr(core.manager_util, 'PIPFixer', Mock())
|
||||
monkeypatch.setattr(core.manager_util, 'get_installed_packages', Mock(return_value={}))
|
||||
monkeypatch.setattr(core.cm_global, 'pip_overrides', {}, raising=False)
|
||||
return ran
|
||||
|
||||
return installs
|
||||
|
||||
|
||||
def test_requirement_that_was_not_installed_is_tried_for_the_next_pack(manager, installs, tmp_path): # noqa: F811
|
||||
first, second = packs_that_name(tmp_path, **{'requirements.txt': 'shareddep==1\n'})
|
||||
ran = installs(False, True)
|
||||
|
||||
assert not manager.execute_install_script(None, first)
|
||||
assert manager.execute_install_script(None, second)
|
||||
assert ran == ['first shareddep==1', 'second shareddep==1']
|
||||
|
||||
|
||||
def test_requirement_after_one_that_failed_is_tried_for_the_next_pack(manager, installs, tmp_path): # noqa: F811
|
||||
first, second = packs_that_name(tmp_path, **{'requirements.txt': 'fails==1\nshareddep==1\n'})
|
||||
ran = installs(False, True, True)
|
||||
|
||||
assert not manager.execute_install_script(None, first)
|
||||
assert manager.execute_install_script(None, second)
|
||||
assert ran == ['first fails==1', 'second fails==1', 'second shareddep==1']
|
||||
|
||||
|
||||
def test_requirement_that_was_installed_is_not_installed_twice(manager, installs, tmp_path): # noqa: F811
|
||||
first, second = packs_that_name(tmp_path, **{'requirements.txt': 'shareddep==1\n'})
|
||||
ran = installs(True)
|
||||
|
||||
assert manager.execute_install_script(None, first)
|
||||
assert manager.execute_install_script(None, second)
|
||||
assert ran == ['first shareddep==1']
|
||||
|
||||
|
||||
def test_install_script_that_failed_is_run_when_asked_again(manager, installs, tmp_path): # noqa: F811
|
||||
first, _ = packs_that_name(tmp_path, **{'install.py': ''})
|
||||
ran = installs(False, True)
|
||||
|
||||
assert not manager.execute_install_script(None, first)
|
||||
assert manager.execute_install_script(None, first)
|
||||
assert ran == ['first install.py', 'first install.py']
|
||||
|
||||
|
||||
def test_install_script_not_run_after_a_requirement_failed_is_run_when_asked_again(manager, installs, tmp_path): # noqa: F811
|
||||
first, _ = packs_that_name(tmp_path, **{'requirements.txt': 'fails==1\n', 'install.py': ''})
|
||||
ran = installs(False, True, True)
|
||||
|
||||
assert not manager.execute_install_script(None, first)
|
||||
assert manager.execute_install_script(None, first)
|
||||
assert ran == ['first fails==1', 'first fails==1', 'first install.py']
|
||||
|
||||
|
||||
def test_install_script_of_a_pack_that_is_cloned_where_another_was_installed_is_run(manager, installs, tmp_path, monkeypatch): # noqa: F811
|
||||
first, _ = packs_that_name(tmp_path, **{'install.py': ''})
|
||||
ran = installs(True, True)
|
||||
assert manager.execute_install_script(None, first)
|
||||
os.rename(first, tmp_path / '.disabled')
|
||||
origin = tmp_path / 'origin'
|
||||
origin.mkdir()
|
||||
(origin / 'install.py').write_text('')
|
||||
for args in (['init', '-q'], ['add', '.'], ['-c', 'user.name=test', '-c', 'user.email=test@example.invalid', 'commit', '-q', '-m', 'a pack']):
|
||||
subprocess.run(['git', *args], cwd=origin, check=True, capture_output=True)
|
||||
for name, value in {'GIT_CONFIG_COUNT': '1', 'GIT_CONFIG_KEY_0': f'url.{origin}.insteadOf', 'GIT_CONFIG_VALUE_0': REPO_URL}.items():
|
||||
monkeypatch.setenv(name, value)
|
||||
|
||||
assert manager.repo_install(REPO_URL, first, instant_execution=True).result
|
||||
assert ran == ['first install.py', 'first install.py']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('cloned', [True, False])
|
||||
def test_restore_tells_whether_every_step_was_done(core, manager, answer, tmp_path, monkeypatch, cloned): # noqa: F811
|
||||
manager.repo_install = answer('install-git', cloned)
|
||||
monkeypatch.setattr(core, 'repo_switch_commit', Mock(return_value=True))
|
||||
|
||||
assert restore(core, tmp_path, **pinned(REPO_URL)) is cloned
|
||||
|
||||
|
||||
@pytest.mark.parametrize('not_installed, restored', [([], True), (['alpha==1.0'], False)])
|
||||
def test_restore_tells_whether_every_pip_package_was_installed(core, manager, tmp_path, monkeypatch, not_installed, restored): # noqa: F811
|
||||
monkeypatch.setattr(core.manager_util, 'restore_pip_snapshot', Mock(return_value=not_installed))
|
||||
|
||||
assert restore(core, tmp_path) is restored
|
||||
|
||||
|
||||
class Exit(Exception):
|
||||
def __init__(self, code=0):
|
||||
self.code = code
|
||||
|
||||
|
||||
@pytest.mark.parametrize('restored, code', [(True, None), (False, 1)])
|
||||
def test_cm_cli_ends_with_1_when_a_step_of_the_restore_failed(tmp_path, restored, code):
|
||||
command = next(node for node in ast.parse(CM_CLI.read_text(encoding='utf-8')).body
|
||||
if isinstance(node, ast.FunctionDef) and node.name == 'restore_snapshot')
|
||||
command.decorator_list = []
|
||||
finalize = Mock()
|
||||
scope = {'typer': SimpleNamespace(Option=Mock(), Exit=Exit), 'Optional': Optional, 'Annotated': Annotated, 'os': os, 'asyncio': asyncio,
|
||||
'traceback': traceback, 'cmd_ctx': Mock(), 'comfy_path': '', 'context': Mock(), '_finalize_resolve': finalize,
|
||||
'manager_util': SimpleNamespace(PIPFixer=Mock(), get_installed_packages=Mock()),
|
||||
'core': SimpleNamespace(restore_snapshot=AsyncMock(return_value=restored))}
|
||||
exec(compile(ast.Module(body=[command], type_ignores=[]), str(CM_CLI), 'exec'), scope)
|
||||
snapshot = tmp_path / 'snapshot.json'
|
||||
snapshot.touch()
|
||||
|
||||
ended = None
|
||||
try:
|
||||
scope['restore_snapshot'](str(snapshot), **{arg.arg: None for arg in command.args.args[1:]})
|
||||
except Exit as e:
|
||||
ended = e.code
|
||||
|
||||
assert ended == code
|
||||
finalize.assert_called_once()
|
||||
@@ -0,0 +1,65 @@
|
||||
import ast
|
||||
import os
|
||||
import sys
|
||||
import types
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
PRESTARTUP = Path(__file__).resolve().parent.parent / "comfyui_manager" / "prestartup_script.py"
|
||||
COMFY = os.path.join(os.sep, "opt", "ComfyUI")
|
||||
LAUNCHER = os.path.join(os.sep, "opt", "launcher")
|
||||
BASE = os.path.join(os.sep, "data", "comfy")
|
||||
|
||||
|
||||
def restore(tmp_path, monkeypatch, environ):
|
||||
scheduled = tmp_path / "restore-snapshot.json"
|
||||
scheduled.write_text("{}")
|
||||
block = [node for node in ast.parse(PRESTARTUP.read_text(encoding="utf-8")).body
|
||||
if isinstance(node, ast.If) and ast.unparse(node.test) == "os.path.exists(restore_snapshot_path)"]
|
||||
assert len(block) == 1
|
||||
|
||||
cli_args = types.ModuleType("comfy.cli_args")
|
||||
cli_args.args = types.SimpleNamespace(listen="127.0.0.1")
|
||||
monkeypatch.setitem(sys.modules, "comfy", types.ModuleType("comfy"))
|
||||
monkeypatch.setitem(sys.modules, "comfy.cli_args", cli_args)
|
||||
for name in ("COMFYUI_PATH", "COMFYUI_FOLDERS_BASE_PATH"):
|
||||
monkeypatch.delenv(name, raising=False)
|
||||
for name, value in environ.items():
|
||||
monkeypatch.setenv(name, value)
|
||||
|
||||
started = []
|
||||
|
||||
def process_wrap(cmd, cwd=None, handler=None, env=None):
|
||||
started.append((cmd, cwd, env))
|
||||
return 0
|
||||
|
||||
exec(compile(ast.Module(body=block, type_ignores=[]), str(PRESTARTUP), "exec"), {
|
||||
"os": os, "sys": sys, "restore_snapshot_path": str(scheduled), "comfy_path": LAUNCHER,
|
||||
"custom_nodes_base_path": os.path.join(BASE, "custom_nodes"),
|
||||
"manager_files_path": os.path.join(BASE, "user", "__manager"),
|
||||
"folder_paths": types.SimpleNamespace(__file__=os.path.join(COMFY, "folder_paths.py"),
|
||||
get_user_directory=lambda: os.path.join(BASE, "user")),
|
||||
"default_conf": {}, "manager_security": types.SimpleNamespace(is_loopback_listener=lambda listen: True),
|
||||
"process_wrap": process_wrap,
|
||||
})
|
||||
assert len(started) == 1 and not scheduled.exists()
|
||||
return started[0]
|
||||
|
||||
|
||||
def test_cm_cli_is_given_the_comfyui_path(tmp_path, monkeypatch):
|
||||
_, _, env = restore(tmp_path, monkeypatch, {})
|
||||
assert env.get("COMFYUI_PATH") == COMFY
|
||||
|
||||
|
||||
def test_cm_cli_is_given_the_directories_of_the_server(tmp_path, monkeypatch):
|
||||
cmd, _, _ = restore(tmp_path, monkeypatch, {})
|
||||
assert cmd[1:5] == ["-m", "cm_cli", "restore-snapshot", str(tmp_path / "restore-snapshot.json")]
|
||||
assert cmd[5:] == ["--user-directory", os.path.join(BASE, "user", "__manager"),
|
||||
"--restore-to", os.path.join(BASE, "custom_nodes")]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["COMFYUI_PATH", "COMFYUI_FOLDERS_BASE_PATH"])
|
||||
def test_a_path_set_in_the_environment_is_kept(tmp_path, monkeypatch, name):
|
||||
_, _, env = restore(tmp_path, monkeypatch, {name: os.path.join(os.sep, "elsewhere")})
|
||||
assert env[name] == os.path.join(os.sep, "elsewhere")
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Both servers store only a `db_mode` or an `update_policy` that Manager knows.
|
||||
|
||||
Each case runs the real handler of `legacy/manager_server.py` or of
|
||||
`glob/manager_server.py` with the functions and the lists of values it uses;
|
||||
`core` holds a configuration in memory and counts how often it is written.
|
||||
"""
|
||||
import ast
|
||||
import asyncio
|
||||
import importlib.util
|
||||
import json
|
||||
import logging
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
from aiohttp import web
|
||||
|
||||
from legacy_html_testutil import PACKAGE
|
||||
|
||||
DB_MODE = ("set_db_mode_api", "db_mode", ["cache", "channel", "local", "remote"])
|
||||
UPDATE_POLICY = ("set_update_policy_api", "update_policy", ["stable", "stable-comfyui", "nightly", "nightly-comfyui"])
|
||||
SETTINGS = [DB_MODE, UPDATE_POLICY]
|
||||
HANDLERS = {"set_db_mode_api", "set_update_policy_api"}
|
||||
SETTERS = {"set_db_mode", "set_update_policy"}
|
||||
BEFORE = "the value before the request"
|
||||
|
||||
|
||||
def take(path, names, namespace):
|
||||
"""Define the functions named, and the lists of known values, of the file in the namespace."""
|
||||
nodes = [node for node in ast.parse(path.read_text(encoding="utf-8")).body
|
||||
if (isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in names)
|
||||
or (isinstance(node, ast.Assign) and getattr(node.targets[0], "id", "").startswith("ALLOWED_"))]
|
||||
exec(compile(ast.Module(nodes, []), str(path), "exec"), namespace)
|
||||
return namespace
|
||||
|
||||
|
||||
@pytest.fixture(params=["legacy", "glob"])
|
||||
def post(request):
|
||||
def post(handler, key, body, allowed=True):
|
||||
"""The status the handler answers, the stored value and how often the configuration was written."""
|
||||
config, written = {key: BEFORE}, []
|
||||
core = SimpleNamespace(get_config=lambda: config, write_config=lambda: written.append(dict(config)))
|
||||
namespace = {"web": web, "logging": logging, "json": json, "core": core, "SECURITY_MESSAGE_MIDDLE": "",
|
||||
"routes": SimpleNamespace(post=lambda path: lambda function: function)}
|
||||
if request.param == "legacy":
|
||||
namespace["is_allowed_security_level"] = lambda level: allowed
|
||||
namespace["manager_security"] = SimpleNamespace(reject_non_json_post=lambda request: None)
|
||||
take(PACKAGE / "legacy/manager_server.py", HANDLERS | SETTERS, namespace)
|
||||
else:
|
||||
setters = take(PACKAGE / "glob/utils/environment_utils.py", SETTERS, {"core": core})
|
||||
namespace["environment_utils"] = SimpleNamespace(**{name: setters[name] for name in SETTERS})
|
||||
namespace["security_utils"] = SimpleNamespace(is_allowed_security_level=lambda level: allowed,
|
||||
reject_non_json_post=lambda request: None)
|
||||
take(PACKAGE / "glob/manager_server.py", HANDLERS, namespace)
|
||||
|
||||
async def read():
|
||||
return json.loads(body)
|
||||
|
||||
return asyncio.run(namespace[handler](SimpleNamespace(json=read))).status, config[key], len(written)
|
||||
|
||||
return post
|
||||
|
||||
|
||||
@pytest.mark.parametrize("handler, key, value", [(handler, key, value) for handler, key, values in SETTINGS for value in values])
|
||||
def test_known_value_is_stored(post, handler, key, value):
|
||||
assert post(handler, key, json.dumps({"value": value})) == (200, value, 1)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("handler, key, values", SETTINGS)
|
||||
@pytest.mark.parametrize("value", ['"no-such-value"', '""', '"CACHE"', '"STABLE"', "7", "null", '["cache"]', '["stable"]'])
|
||||
def test_unknown_value_is_refused(post, handler, key, values, value):
|
||||
assert post(handler, key, '{"value": %s}' % value) == (400, BEFORE, 0)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("handler, key, values", SETTINGS)
|
||||
@pytest.mark.parametrize("body", ["{}", "not json", "[]", '"cache"', "7", "null"])
|
||||
def test_request_without_a_value_is_refused(post, handler, key, values, body):
|
||||
assert post(handler, key, body) == (400, BEFORE, 0)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("handler, key, values", SETTINGS)
|
||||
def test_request_is_refused_by_the_security_level(post, handler, key, values):
|
||||
assert post(handler, key, json.dumps({"value": values[0]}), allowed=False) == (403, BEFORE, 0)
|
||||
|
||||
|
||||
def test_enums_hold_the_values_the_servers_use():
|
||||
spec = importlib.util.spec_from_file_location("_enums", PACKAGE / "common/enums.py")
|
||||
enums = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(enums)
|
||||
known = take(PACKAGE / "glob/utils/environment_utils.py", set(), {})
|
||||
openapi = yaml.safe_load((PACKAGE.parent / "openapi.yaml").read_text(encoding="utf-8"))
|
||||
|
||||
assert sorted(mode.value for mode in enums.DBMode) == sorted(known["ALLOWED_DB_MODES"])
|
||||
assert sorted(level.value for level in enums.SecurityLevel) == sorted(openapi["components"]["schemas"]["SecurityLevel"]["enum"])
|
||||
@@ -47,12 +47,13 @@ def load_share_art(package, output_dir, temp_dir, os_module: object = os):
|
||||
async def close(self):
|
||||
pass
|
||||
|
||||
namespace = load_functions(PACKAGE / package / "share_3rdparty.py", {"share_art"}, {
|
||||
namespace = load_functions(PACKAGE / package / "share_3rdparty.py", {"share_art", "is_matrix_org"}, {
|
||||
"PromptServer": SimpleNamespace(instance=SimpleNamespace(routes=web.RouteTableDef())),
|
||||
"folder_paths": SimpleNamespace(get_output_directory=lambda: str(output_dir),
|
||||
get_temp_directory=lambda: str(temp_dir)),
|
||||
"os": os_module, "web": web, "json": json, "mimetypes": mimetypes,
|
||||
"matrix_nio_is_available": True, "set_matrix_auth": lambda matrix_auth: None,
|
||||
"matrix_nio_is_available": True, "get_matrix_auth": lambda: None, "set_matrix_auth": lambda matrix_auth: None,
|
||||
"manager_security": SimpleNamespace(reject_non_json_post=lambda request: None),
|
||||
"AsyncClient": AsyncClient, "LoginResponse": LoginResponse, "UploadResponse": UploadResponse,
|
||||
})
|
||||
return namespace["share_art"], uploads
|
||||
@@ -60,7 +61,7 @@ def load_share_art(package, output_dir, temp_dir, os_module: object = os):
|
||||
|
||||
def share(share_art, output):
|
||||
body = {
|
||||
"matrix_auth": {"homeserver": "matrix.example", "username": "user", "password": "password"},
|
||||
"matrix_auth": {"homeserver": "matrix.org", "username": "user", "password": "password"},
|
||||
"share_destinations": ["matrix"], "credits": "", "title": "", "description": "",
|
||||
"prompt": {"workflow": {}}, "potential_outputs": [output], "selected_output_index": 0,
|
||||
}
|
||||
@@ -107,7 +108,7 @@ def test_a_file_in_the_directory_is_shared(package, dirs, output, content):
|
||||
response = share(share_art, output)
|
||||
|
||||
assert response.status == 200
|
||||
assert uploads[0] == ("https://matrix.example", content)
|
||||
assert uploads[0] == ("https://matrix.org", content)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("output", [
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from test_grid_highlight_escaping import browser # noqa: F401 -- fixture
|
||||
|
||||
JS = Path(os.environ.get("MANAGER_JS_DIR") or (Path(__file__).resolve().parent.parent / "comfyui_manager" / "js"))
|
||||
EXTENSION = "http://manager.test/extensions/comfyui-manager/"
|
||||
|
||||
SAVED = {"homeserver": "matrix.org", "username": "user"}
|
||||
ASK_FOR_ACCOUNT = "Please set your Matrix account details."
|
||||
|
||||
SCRIPTS = {
|
||||
"api.js": """
|
||||
export const api = {
|
||||
addEventListener() {},
|
||||
async fetchApi(path, options) {
|
||||
window.requested.push({path, method: options?.method ?? 'GET', body: options?.body ? JSON.parse(options.body) : null});
|
||||
if(path == '/v2/manager/get_matrix_auth') {
|
||||
if(window.offline) throw new TypeError('Failed to fetch');
|
||||
if(window.saved) return {status: 200, json: async () => window.saved};
|
||||
return {status: 404, json: async () => { throw new SyntaxError('Unexpected end of JSON input'); }};
|
||||
}
|
||||
return {status: 200, json: async () => ({matrix: {success: true}})};
|
||||
}
|
||||
};
|
||||
""",
|
||||
"app.js": """
|
||||
const image = {filename: 'a.png', subfolder: '', type: 'output'};
|
||||
export const app = {
|
||||
graph: {_nodes: [{type: 'SaveImage', id: 1, title: 'Save Image', images: [image]}]},
|
||||
graphToPrompt: async () => ({workflow: {}, output: {}}),
|
||||
ui: {dialog: {element: document.body, show() {}}},
|
||||
};
|
||||
""",
|
||||
"ui.js": """
|
||||
export function $el(tag, props, children) {
|
||||
const names = tag.split('.');
|
||||
const element = document.createElement(names.shift());
|
||||
element.classList.add(...names);
|
||||
const {parent, style, ...rest} = props ?? {};
|
||||
Object.assign(element.style, style);
|
||||
Object.assign(element, rest);
|
||||
element.append(...(children ?? []));
|
||||
parent?.append(element);
|
||||
return element;
|
||||
}
|
||||
export class ComfyDialog {
|
||||
close() { this.element.style.display = 'none'; }
|
||||
}
|
||||
""",
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def page(browser): # noqa: F811
|
||||
page = browser.new_page()
|
||||
|
||||
def route(request):
|
||||
url = request.request.url
|
||||
name = url.rsplit("/", 1)[-1]
|
||||
if url == "http://manager.test/":
|
||||
request.fulfill(body="<body></body>", content_type="text/html")
|
||||
elif url.startswith(EXTENSION) and (JS / name).is_file():
|
||||
request.fulfill(path=str(JS / name), content_type="text/javascript")
|
||||
elif url == "http://manager.test/scripts/" + name and name in SCRIPTS:
|
||||
request.fulfill(body=SCRIPTS[name], content_type="text/javascript")
|
||||
else:
|
||||
request.abort()
|
||||
|
||||
page.route("**/*", route)
|
||||
page.errors = []
|
||||
page.alerts = []
|
||||
page.on("pageerror", lambda error: page.errors.append(str(error)))
|
||||
page.on("dialog", lambda dialog: (page.alerts.append(dialog.message), dialog.dismiss()))
|
||||
page.goto("http://manager.test/")
|
||||
yield page
|
||||
page.close()
|
||||
|
||||
|
||||
def open_dialog(page, saved, offline=False):
|
||||
page.evaluate("""async ({saved, offline, module}) => {
|
||||
window.requested = [];
|
||||
window.saved = saved;
|
||||
window.offline = offline;
|
||||
const { ShareDialog, getPotentialOutputsAndOutputNodes } = await import(module);
|
||||
const { app } = await import('/scripts/app.js');
|
||||
window.dialog = new ShareDialog();
|
||||
window.dialog.show(getPotentialOutputsAndOutputNodes(app.graph._nodes));
|
||||
}""", {"saved": saved, "offline": offline, "module": EXTENSION + "comfyui-share-common.js"})
|
||||
page.wait_for_timeout(200)
|
||||
|
||||
|
||||
def fields(page):
|
||||
return page.evaluate("""() => ({
|
||||
homeserver: dialog.matrix_homeserver_input.value,
|
||||
username: dialog.matrix_username_input.value,
|
||||
password: dialog.matrix_password_input.value,
|
||||
})""")
|
||||
|
||||
|
||||
def share_to_matrix(page, matrix=True, **typed):
|
||||
page.evaluate("""async ({typed, matrix}) => {
|
||||
for(const [name, value] of Object.entries(typed)) {
|
||||
dialog[`matrix_${name}_input`].value = value;
|
||||
}
|
||||
dialog.matrix_destination_checkbox.checked = matrix;
|
||||
await dialog.share_button.onclick();
|
||||
}""", {"typed": typed, "matrix": matrix})
|
||||
page.wait_for_timeout(200)
|
||||
|
||||
|
||||
def shared(page):
|
||||
return [request["body"]["matrix_auth"] for request in page.evaluate("window.requested")
|
||||
if request["path"] == "/v2/manager/share"]
|
||||
|
||||
|
||||
def test_the_saved_account_is_shown_without_its_password(page):
|
||||
open_dialog(page, SAVED)
|
||||
|
||||
assert fields(page) == {**SAVED, "password": ""}
|
||||
assert "Saved password" in page.evaluate("dialog.matrix_password_input.placeholder")
|
||||
assert page.errors == []
|
||||
|
||||
|
||||
def test_the_saved_account_is_shared_with_an_empty_password(page):
|
||||
open_dialog(page, SAVED)
|
||||
|
||||
share_to_matrix(page)
|
||||
|
||||
assert shared(page) == [{**SAVED, "password": ""}]
|
||||
assert page.alerts == []
|
||||
assert page.errors == []
|
||||
|
||||
|
||||
def test_another_account_needs_a_password(page):
|
||||
open_dialog(page, SAVED)
|
||||
|
||||
share_to_matrix(page, username="someone-else")
|
||||
|
||||
assert page.alerts == [ASK_FOR_ACCOUNT]
|
||||
assert shared(page) == []
|
||||
|
||||
|
||||
def test_the_homeserver_cannot_be_typed(page):
|
||||
open_dialog(page, SAVED)
|
||||
|
||||
assert page.evaluate("dialog.matrix_homeserver_input.readOnly") is True
|
||||
assert fields(page)["homeserver"] == "matrix.org"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("homeserver", ["other.example", "https://matrix.org", "", None],
|
||||
ids=["another homeserver", "matrix.org with a scheme", "empty", "null"])
|
||||
def test_a_saved_homeserver_does_not_reach_the_field_or_the_request(page, homeserver):
|
||||
open_dialog(page, {"homeserver": homeserver, "username": "user"})
|
||||
assert fields(page) == {"homeserver": "matrix.org", "username": "user", "password": ""}
|
||||
|
||||
share_to_matrix(page)
|
||||
|
||||
assert shared(page) == [{"homeserver": "matrix.org", "username": "user", "password": ""}]
|
||||
assert page.errors == []
|
||||
|
||||
|
||||
def test_a_typed_password_is_sent(page):
|
||||
open_dialog(page, SAVED)
|
||||
|
||||
share_to_matrix(page, username="someone-else", password="a new password")
|
||||
|
||||
assert shared(page) == [{"homeserver": "matrix.org", "username": "someone-else", "password": "a new password"}]
|
||||
assert page.alerts == []
|
||||
|
||||
|
||||
def test_without_a_saved_account_a_password_is_needed(page):
|
||||
open_dialog(page, None)
|
||||
assert fields(page) == {"homeserver": "matrix.org", "username": "", "password": ""}
|
||||
assert page.evaluate("dialog.matrix_password_input.placeholder") == "Password"
|
||||
|
||||
share_to_matrix(page, username="user")
|
||||
|
||||
assert page.alerts == [ASK_FOR_ACCOUNT]
|
||||
assert shared(page) == []
|
||||
assert page.errors == []
|
||||
|
||||
|
||||
def test_the_account_that_was_shared_is_the_saved_one_afterwards(page):
|
||||
open_dialog(page, SAVED)
|
||||
share_to_matrix(page, username="someone-else", password="a new password")
|
||||
|
||||
share_to_matrix(page, username="user", password="")
|
||||
assert page.alerts == [ASK_FOR_ACCOUNT]
|
||||
|
||||
share_to_matrix(page, username="someone-else", password="")
|
||||
assert shared(page)[1:] == [{"homeserver": "matrix.org", "username": "someone-else", "password": ""}]
|
||||
|
||||
|
||||
def test_a_field_changed_and_changed_back_is_the_saved_account(page):
|
||||
open_dialog(page, SAVED)
|
||||
|
||||
share_to_matrix(page, username="someone-else")
|
||||
share_to_matrix(page, username="user")
|
||||
|
||||
assert page.alerts == [ASK_FOR_ACCOUNT]
|
||||
assert shared(page) == [{**SAVED, "password": ""}]
|
||||
|
||||
|
||||
def test_the_saved_account_that_cannot_be_read_is_no_saved_account(page):
|
||||
open_dialog(page, SAVED, offline=True)
|
||||
assert fields(page) == {"homeserver": "matrix.org", "username": "", "password": ""}
|
||||
|
||||
share_to_matrix(page, username="user")
|
||||
|
||||
assert page.alerts == [ASK_FOR_ACCOUNT]
|
||||
assert shared(page) == []
|
||||
assert page.errors == []
|
||||
|
||||
|
||||
def test_sharing_without_matrix_needs_no_account(page):
|
||||
open_dialog(page, None)
|
||||
|
||||
share_to_matrix(page, matrix=False)
|
||||
|
||||
assert page.alerts == []
|
||||
assert page.evaluate("window.requested.at(-1).body.share_destinations") == []
|
||||
@@ -0,0 +1,118 @@
|
||||
import ast
|
||||
import asyncio
|
||||
import json
|
||||
import re
|
||||
from types import SimpleNamespace
|
||||
from typing import Optional
|
||||
|
||||
import pytest
|
||||
from aiohttp import web
|
||||
|
||||
from legacy_html_testutil import PACKAGE, load_functions
|
||||
|
||||
MENU = PACKAGE / "js" / "comfyui-manager.js"
|
||||
CHOICES = ["all", "none", "youml", "matrix"]
|
||||
ROUTE = "/v2/manager/share_option"
|
||||
|
||||
|
||||
@pytest.fixture(params=["glob", "legacy"])
|
||||
def route(request):
|
||||
source = (PACKAGE / request.param / "share_3rdparty.py").read_text(encoding="utf-8")
|
||||
nodes = [node for node in ast.parse(source).body
|
||||
if isinstance(node, ast.AsyncFunctionDef) and node.name in ("share_option", "set_share_option")
|
||||
or isinstance(node, ast.Assign) and ast.unparse(node.targets[0]) == "SHARE_OPTIONS"]
|
||||
assert len(nodes) == 3
|
||||
check = load_functions(PACKAGE / "common/manager_security.py", {"reject_non_json_post"}, {"web": web, "Optional": Optional})["reject_non_json_post"]
|
||||
routes = web.RouteTableDef()
|
||||
config, written, read = {"share_option": "all"}, [], []
|
||||
namespace = {
|
||||
"PromptServer": SimpleNamespace(instance=SimpleNamespace(routes=routes)), "web": web, "json": json,
|
||||
"manager_security": SimpleNamespace(reject_non_json_post=check),
|
||||
"core": SimpleNamespace(get_config=lambda: config, write_config=lambda: written.append(dict(config))),
|
||||
}
|
||||
exec(compile(ast.Module(body=nodes, type_ignores=[]), "share_3rdparty.py", "exec"), namespace)
|
||||
|
||||
def get(query):
|
||||
response = asyncio.run(namespace["share_option"](SimpleNamespace(rel_url=SimpleNamespace(query=query))))
|
||||
return response.status, response.text
|
||||
|
||||
def post(body, content_type="application/json"):
|
||||
async def read_json():
|
||||
read.append(True)
|
||||
return json.loads(body)
|
||||
|
||||
return asyncio.run(namespace["set_share_option"](SimpleNamespace(content_type=content_type, json=read_json))).status
|
||||
|
||||
return SimpleNamespace(get=get, post=post, config=config, written=written, read=read, choices=namespace["SHARE_OPTIONS"],
|
||||
methods=sorted((entry.method, entry.path) for entry in routes))
|
||||
|
||||
|
||||
def test_the_choices_are_those_of_the_share_menu(route):
|
||||
menu = re.search(r"const share_options = \[(.*?)\];", MENU.read_text(encoding="utf-8"), re.S).group(1)
|
||||
|
||||
assert sorted(route.choices) == sorted(re.findall(r"\['(\w+)',", menu)) == sorted(CHOICES)
|
||||
|
||||
|
||||
def test_the_option_is_read_with_get_and_saved_with_post(route):
|
||||
assert route.methods == [("GET", ROUTE), ("POST", ROUTE)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("saved", CHOICES)
|
||||
@pytest.mark.parametrize("value", CHOICES)
|
||||
def test_a_choice_of_the_menu_is_saved(route, saved, value):
|
||||
route.config["share_option"] = saved
|
||||
|
||||
assert route.post(json.dumps({"value": value})) == 200
|
||||
assert route.written == [{"share_option": value}]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", [
|
||||
"", " ", "ALL", "All", "all ", " all", "all,none", "none\n", "openart", "comfyworkflows", "true", "<b>all</b>", "all\x00",
|
||||
"a" * 5000, None, 0, 1, True, ["all"], {"all": "none"},
|
||||
], ids=repr)
|
||||
@pytest.mark.parametrize("saved", ["all", "none"])
|
||||
def test_any_other_value_is_refused_and_nothing_is_saved(route, saved, value):
|
||||
route.config["share_option"] = saved
|
||||
|
||||
assert route.post(json.dumps({"value": value})) == 400
|
||||
assert route.config == {"share_option": saved}
|
||||
assert route.written == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("body", ['{}', '{"other": "none"}', '[]', '["value"]', '"none"', 'null', '1', '', '{"value": "none"', 'value=none',
|
||||
b'{"value": "\xff"}', b'\xff\xfe'], ids=repr)
|
||||
def test_a_body_without_a_value_is_refused_and_nothing_is_saved(route, body):
|
||||
assert route.post(body) == 400
|
||||
assert route.config == {"share_option": "all"}
|
||||
assert route.written == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("content_type", ["text/plain", "application/x-www-form-urlencoded", "multipart/form-data",
|
||||
"application/octet-stream"])
|
||||
def test_a_value_that_is_not_sent_as_json_is_refused_before_the_body_is_read(route, content_type):
|
||||
assert route.post(json.dumps({"value": "none"}), content_type) == 400
|
||||
assert route.read == []
|
||||
assert route.written == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("saved", [*CHOICES, "openart", ""], ids=lambda saved: saved or "empty")
|
||||
def test_get_answers_the_saved_option_as_it_is(route, saved):
|
||||
route.config["share_option"] = saved
|
||||
|
||||
assert route.get({}) == (200, saved)
|
||||
assert route.written == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", [*CHOICES, "openart"])
|
||||
def test_get_saves_nothing_whatever_it_is_given(route, value):
|
||||
assert route.get({"value": value}) == (200, "all")
|
||||
assert route.config == {"share_option": "all"}
|
||||
assert route.written == []
|
||||
|
||||
|
||||
def test_the_menu_saves_the_option_with_a_json_post():
|
||||
source = MENU.read_text(encoding="utf-8")
|
||||
|
||||
assert "share_option?value=" not in source
|
||||
assert re.search(r"fetchApi\(\s*'/v2/manager/share_option'\s*,\s*\{[^;]*?\bmethod:\s*'POST'[^;]*?\bbody:\s*JSON\.stringify\(\{\s*value\s*\}\)",
|
||||
source)
|
||||
@@ -0,0 +1,95 @@
|
||||
import asyncio
|
||||
import importlib.util
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from aiohttp import web
|
||||
|
||||
from legacy_html_testutil import PACKAGE, load_functions
|
||||
|
||||
LEVELS = ["strong", "normal", "normal-", "weak"]
|
||||
LISTENERS = ["loopback", "personal_cloud", "public"]
|
||||
IS_LOOPBACK = {"glob": load_functions(PACKAGE / "common/manager_security.py", {"is_loopback"})["is_loopback"],
|
||||
"legacy": load_functions(PACKAGE / "legacy/manager_server.py", {"is_loopback"})["is_loopback"]}
|
||||
|
||||
|
||||
def restore_allowed(security_level, listener):
|
||||
return security_level == "weak" and listener != "public" or security_level == "normal-" and listener == "loopback"
|
||||
|
||||
|
||||
@pytest.fixture(params=["glob", "legacy"])
|
||||
def server(request, monkeypatch, tmp_path):
|
||||
snapshot = tmp_path / "snapshots" / "saved.json"
|
||||
snapshot.parent.mkdir()
|
||||
snapshot.write_text("{}", encoding="utf-8")
|
||||
scheduled = tmp_path / "startup-scripts" / "restore-snapshot.json"
|
||||
package = PACKAGE / request.param
|
||||
|
||||
def restore(security_level, listener, query={"target": "saved.json"}, listen=None):
|
||||
if listen is None:
|
||||
listen = "127.0.0.1" if listener == "loopback" else "0.0.0.0"
|
||||
core = SimpleNamespace(get_config=lambda: {
|
||||
"security_level": security_level,
|
||||
"network_mode": "personal_cloud" if listener == "personal_cloud" else "public"})
|
||||
files = SimpleNamespace(
|
||||
reject_non_json_post=lambda request: None,
|
||||
get_safe_file_path=lambda target, base: os.path.join(base, target) if target == "saved.json" else None)
|
||||
namespace = {
|
||||
"routes": web.RouteTableDef(), "web": web, "logging": logging, "os": os, "shutil": shutil, "core": core,
|
||||
"context": SimpleNamespace(manager_snapshot_path=str(snapshot.parent),
|
||||
manager_startup_script_path=str(scheduled.parent)),
|
||||
"SECURITY_MESSAGE_HIGH_P": "",
|
||||
}
|
||||
if request.param == "glob":
|
||||
spec = importlib.util.spec_from_file_location("_generated_models", PACKAGE / "data_models/generated_models.py")
|
||||
models = importlib.util.module_from_spec(spec)
|
||||
monkeypatch.setitem(sys.modules, spec.name, models)
|
||||
spec.loader.exec_module(models)
|
||||
security = load_functions(package / "utils/security_utils.py", {"is_allowed_security_level"}, {
|
||||
"core": core, "args": SimpleNamespace(listen=listen), "is_loopback": IS_LOOPBACK["glob"],
|
||||
"SecurityLevel": models.SecurityLevel, "RiskLevel": models.RiskLevel,
|
||||
})
|
||||
namespace["security_utils"] = SimpleNamespace(**vars(files), **security)
|
||||
names = {"restore_snapshot"}
|
||||
else:
|
||||
namespace.update(manager_security=files, is_local_mode=IS_LOOPBACK["legacy"](listen))
|
||||
names = {"restore_snapshot", "is_allowed_security_level"}
|
||||
load_functions(package / "manager_server.py", names, namespace)
|
||||
|
||||
response = asyncio.run(namespace["restore_snapshot"](SimpleNamespace(rel_url=SimpleNamespace(query=query))))
|
||||
return response.status, scheduled.exists()
|
||||
|
||||
return restore
|
||||
|
||||
|
||||
@pytest.mark.parametrize("listener", LISTENERS)
|
||||
@pytest.mark.parametrize("security_level", LEVELS)
|
||||
def test_a_restore_needs_the_level_of_the_switch_route(server, security_level, listener):
|
||||
status, scheduled = server(security_level, listener)
|
||||
|
||||
if restore_allowed(security_level, listener):
|
||||
assert (status, scheduled) == (200, True)
|
||||
else:
|
||||
assert (status, scheduled) == (403, False)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("listener", LISTENERS)
|
||||
@pytest.mark.parametrize("security_level", LEVELS)
|
||||
@pytest.mark.parametrize("query", [{"target": "another.json"}, {"target": ""}, {}],
|
||||
ids=["a snapshot that does not exist", "an empty name", "no target"])
|
||||
def test_a_request_for_no_snapshot_schedules_nothing_at_any_level(server, security_level, listener, query):
|
||||
status, scheduled = server(security_level, listener, query)
|
||||
|
||||
assert status == (400 if restore_allowed(security_level, listener) else 403)
|
||||
assert scheduled is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize("listen, loopback", [
|
||||
("127.0.0.1", True), ("127.0.0.2", True), ("::1", True), ("0.0.0.0", False), ("::", False), ("192.168.0.10", False),
|
||||
("localhost", False), ("127.0.0.1,::1", False), ("", False)])
|
||||
def test_the_listener_is_loopback_only_by_one_loopback_address_given_to_listen(server, listen, loopback):
|
||||
assert server("normal-", "public", listen=listen) == ((200, True) if loopback else (403, False))
|
||||
@@ -28,7 +28,7 @@ def git(path, *args):
|
||||
def core(request, monkeypatch, tmp_path):
|
||||
core = import_reader(request.param)
|
||||
monkeypatch.setattr(core, 'get_default_custom_nodes_path', lambda: str(tmp_path))
|
||||
monkeypatch.setattr(core.manager_util, 'restore_pip_snapshot', Mock())
|
||||
monkeypatch.setattr(core.manager_util, 'restore_pip_snapshot', Mock(return_value=[]))
|
||||
return core
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ def manager(core, monkeypatch):
|
||||
def restore(core, tmp_path, **snapshot):
|
||||
path = tmp_path / 'snapshot.json'
|
||||
path.write_text(json.dumps({'cnr_custom_nodes': {}, 'git_custom_nodes': {}, 'file_custom_nodes': [], **snapshot}))
|
||||
asyncio.run(core.restore_snapshot(str(path)))
|
||||
return asyncio.run(core.restore_snapshot(str(path)))
|
||||
|
||||
|
||||
@pytest.mark.parametrize('head, 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
|
||||
|
||||
JS = JsSource(Path(os.environ.get("MANAGER_JS_DIR") or (Path(__file__).resolve().parent.parent / "comfyui_manager" / "js")))
|
||||
|
||||
pytestmark = pytest.mark.skipif(NODE is None, reason="node is required to execute the lifted production JS")
|
||||
|
||||
|
||||
def switch(version, status, versions_status=200):
|
||||
script = """
|
||||
const shown = [], requested = [];
|
||||
const api = {clientId: 'client', fetchApi: async (path, options) => {
|
||||
if(path == '/v2/comfyui_manager/comfyui_versions') {
|
||||
return {status: %s, json: async () => ({versions: ['nightly', 'v0.3.60'], current: 'v0.3.59'})};
|
||||
}
|
||||
requested.push({path, body: JSON.parse(options.body)});
|
||||
return {status: path == '/v2/comfyui_manager/comfyui_switch_version' ? %s : 200};
|
||||
}};
|
||||
const switch_comfyui_button = {style: {}};
|
||||
const update_policy_combo = {value: 'unchanged'};
|
||||
let update_policy_chosen = false;
|
||||
let chosen;
|
||||
const showVersionSelectorDialog = (versions, current, onSelect) => { chosen = onSelect(%s); };
|
||||
const infoToast = (text) => shown.push('toast: ' + text);
|
||||
const customAlert = (text) => shown.push('alert: ' + text);
|
||||
%s
|
||||
await switchComfyUI();
|
||||
await chosen;
|
||||
console.log(JSON.stringify({shown, requested, update_policy: update_policy_combo.value, update_policy_chosen,
|
||||
button_disabled: switch_comfyui_button.disabled}));
|
||||
""" % (json.dumps(versions_status), json.dumps(status), json.dumps(version),
|
||||
slice_braced(JS.text("comfyui-manager.js"), "async function switchComfyUI()"))
|
||||
return run_node(script)
|
||||
|
||||
|
||||
def switch_request(version):
|
||||
return {"path": "/v2/comfyui_manager/comfyui_switch_version",
|
||||
"body": {"ver": version, "client_id": "client", "ui_id": "client"}}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("version, update_policy", [("nightly", "nightly-comfyui"), ("v0.3.60", "stable-comfyui")])
|
||||
def test_a_switch_that_was_accepted_sets_the_update_policy_of_the_version(version, update_policy):
|
||||
did = switch(version, 200)
|
||||
|
||||
assert did["requested"] == [switch_request(version), {"path": "/v2/manager/policy/update", "body": {"value": update_policy}}]
|
||||
assert did["update_policy"] == update_policy
|
||||
assert did["update_policy_chosen"] is True
|
||||
assert did["shown"] == ["toast: ComfyUI version is switched to " + version]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("version", ["nightly", "v0.3.60"])
|
||||
@pytest.mark.parametrize("status, shown", [
|
||||
(403, "alert: This action is not allowed with this security level configuration."),
|
||||
(400, "alert: Failed to switch ComfyUI version."),
|
||||
(500, "alert: Failed to switch ComfyUI version."),
|
||||
])
|
||||
def test_a_switch_that_did_not_happen_leaves_the_update_policy(version, status, shown):
|
||||
did = switch(version, status)
|
||||
|
||||
assert did["requested"] == [switch_request(version)]
|
||||
assert did["update_policy"] == "unchanged"
|
||||
assert did["update_policy_chosen"] is False
|
||||
assert did["shown"] == [shown]
|
||||
|
||||
|
||||
def test_without_the_list_of_versions_nothing_is_switched():
|
||||
did = switch("v0.3.60", 200, versions_status=400)
|
||||
|
||||
assert did["requested"] == []
|
||||
assert did["shown"] == ["alert: Failed to fetch ComfyUI versions."]
|
||||
assert did["button_disabled"] is False
|
||||
@@ -0,0 +1,70 @@
|
||||
"""The update route queues the ComfyUI update that `update_policy` names.
|
||||
|
||||
Each case runs the real `update_comfyui` of `glob/manager_server.py` with the
|
||||
real request models; `core` and the task queue are replaced, so nothing is
|
||||
updated.
|
||||
"""
|
||||
import asyncio
|
||||
import importlib.util
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from aiohttp import web
|
||||
from pydantic import ValidationError
|
||||
|
||||
from legacy_html_testutil import PACKAGE, load_functions
|
||||
|
||||
SERVER = PACKAGE / "glob/manager_server.py"
|
||||
|
||||
|
||||
def module(path):
|
||||
spec = importlib.util.spec_from_file_location("_" + path.stem, path)
|
||||
loaded = importlib.util.module_from_spec(spec)
|
||||
sys.modules[spec.name] = loaded # pydantic resolves the models' annotations through it
|
||||
spec.loader.exec_module(loaded)
|
||||
return loaded
|
||||
|
||||
|
||||
def update(policy, **query):
|
||||
"""The status the route answers, and whether the update it queued is the stable one."""
|
||||
models = module(PACKAGE / "data_models/generated_models.py")
|
||||
queued = []
|
||||
route = lambda path: lambda handler: handler # noqa: E731
|
||||
handler = load_functions(SERVER, {"update_comfyui"}, {
|
||||
"web": web, "ValidationError": ValidationError,
|
||||
"routes": SimpleNamespace(post=route),
|
||||
"security_utils": module(PACKAGE / "common/manager_security.py"),
|
||||
"core": SimpleNamespace(get_config=lambda: {"update_policy": policy}),
|
||||
"UpdateComfyUIQueryParams": models.UpdateComfyUIQueryParams,
|
||||
"UpdateComfyUIParams": models.UpdateComfyUIParams,
|
||||
"QueueTaskItem": models.QueueTaskItem, "OperationType": models.OperationType,
|
||||
"task_queue": SimpleNamespace(put=queued.append),
|
||||
})["update_comfyui"]
|
||||
request = SimpleNamespace(content_type="application/json", rel_url=SimpleNamespace(query=query))
|
||||
status = asyncio.run(handler(request)).status
|
||||
return status, [task.params.is_stable for task in queued]
|
||||
|
||||
|
||||
WHO = {"client_id": "c", "ui_id": "u"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("policy, stable", [("stable-comfyui", True), ("stable", True),
|
||||
("nightly-comfyui", False), ("nightly", False)])
|
||||
def test_request_without_stable_follows_the_policy(policy, stable):
|
||||
assert update(policy, **WHO) == (200, [stable])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("policy", ["stable-comfyui", "nightly-comfyui"])
|
||||
@pytest.mark.parametrize("given, stable", [("true", True), ("false", False)])
|
||||
@pytest.mark.parametrize("name", ["stable", "is_stable"])
|
||||
def test_request_that_names_the_version_line_decides_itself(name, policy, given, stable):
|
||||
assert update(policy, **{name: given}, **WHO) == (200, [stable])
|
||||
|
||||
|
||||
def test_stable_is_read_before_is_stable():
|
||||
assert update("stable-comfyui", stable="false", is_stable="true", **WHO) == (200, [False])
|
||||
|
||||
|
||||
def test_request_without_a_client_is_refused():
|
||||
assert update("stable-comfyui", ui_id="u") == (400, [])
|
||||
@@ -0,0 +1,487 @@
|
||||
import ast
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import types
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
|
||||
from _install_flags_testutil import import_reader
|
||||
from test_snapshot_restore_pins import core # noqa: F401
|
||||
|
||||
OTHER_ENCODING = {'LC_ALL': 'C', 'PYTHONUTF8': '0', 'PYTHONCOERCECLOCALE': '0'}
|
||||
CHILD = (f'import pathlib, sys; sys.path[:0] = [{str(Path(__file__).parents[1])!r}, {str(Path(__file__).parent)!r}]\n'
|
||||
'from _install_flags_testutil import import_reader\n'
|
||||
'import test_version_switch_old_files as cases\n')
|
||||
|
||||
|
||||
def download_url(url, directory, name, member='__init__.py'):
|
||||
with zipfile.ZipFile(os.path.join(directory, name), 'w') as archive:
|
||||
archive.writestr(member, 'VERSION = 2')
|
||||
|
||||
|
||||
def download_with_another_name(url, directory, name):
|
||||
"""`./__init__.py` is extracted to the same file as `__init__.py`."""
|
||||
download_url(url, directory, name, './__init__.py')
|
||||
|
||||
|
||||
def download_that_is_not_a_zip(url, directory, name):
|
||||
with open(os.path.join(directory, name), 'w') as file:
|
||||
file.write('<html></html>')
|
||||
|
||||
|
||||
def startup_functions(set_module, download=download_url, **module_globals):
|
||||
"""Importing prestartup_script would run the start-up."""
|
||||
cli_args = types.ModuleType('comfy.cli_args')
|
||||
cli_args.args = types.SimpleNamespace(listen='127.0.0.1')
|
||||
set_module('comfy', types.ModuleType('comfy'))
|
||||
set_module('comfy.cli_args', cli_args)
|
||||
|
||||
manager_util = import_reader('glob').manager_util
|
||||
source = Path(manager_util.__file__).parents[1] / 'prestartup_script.py'
|
||||
functions = [node for node in ast.parse(source.read_text(encoding='utf-8')).body
|
||||
if isinstance(node, ast.FunctionDef) and node.name in ('execute_lazy_cnr_switch', 'execute_lazy_install_script', 'execute_startup_script')]
|
||||
scope = {'os': os, 'ast': ast, 'logging': logging, 'default_conf': {}, 'manager_util': manager_util, 'manager_files_path': None,
|
||||
'manager_security': types.SimpleNamespace(is_cnr_install_allowed=lambda *args, **options: True),
|
||||
'manager_downloader': types.SimpleNamespace(download_url=download), **module_globals}
|
||||
exec(compile(ast.Module(body=functions, type_ignores=[]), str(source), 'exec'), scope)
|
||||
return scope
|
||||
|
||||
|
||||
def reserved_switch(set_module, download=download_url):
|
||||
return startup_functions(set_module, download)['execute_lazy_cnr_switch']
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def switch(monkeypatch):
|
||||
return reserved_switch(lambda name, module: monkeypatch.setitem(sys.modules, name, module))
|
||||
|
||||
|
||||
def switch_at_once(core, custom_nodes, set_attribute, download=download_url): # noqa: F811
|
||||
set_attribute(core, 'get_default_custom_nodes_path', lambda: str(custom_nodes))
|
||||
set_attribute(core.manager_downloader, 'basic_download_url', download)
|
||||
manager = core.UnifiedManager()
|
||||
manager.active_nodes['fixture'] = ('1.0.0', str(custom_nodes / 'fixture'))
|
||||
manager.execute_install_script = Mock(return_value=True)
|
||||
version = types.SimpleNamespace(version='2.0.0', download_url='https://example.invalid/fixture.zip', status='NodeVersionStatusActive')
|
||||
return manager._cnr_switch_version('fixture', version, instant_execution=True, no_deps=True).result
|
||||
|
||||
|
||||
def old_version(custom_nodes, directory, *tracked):
|
||||
old = custom_nodes / directory
|
||||
old.mkdir(parents=True)
|
||||
for name in ('__init__.py', 'removed.py'):
|
||||
(old / name).write_text('VERSION = 1')
|
||||
(old / '.tracking').write_text('\n'.join(('__init__.py', *tracked)), encoding='utf-8')
|
||||
(custom_nodes / 'removed.py').write_text('a file that is not of the nodepack')
|
||||
return old
|
||||
|
||||
|
||||
def test_files_that_the_new_version_lacks_are_removed_from_the_pack(switch, tmp_path):
|
||||
custom_nodes = tmp_path / 'custom_nodes'
|
||||
old, new = old_version(custom_nodes, 'fixture@1_0_0', 'removed.py'), custom_nodes / 'fixture@2_0_0'
|
||||
|
||||
assert switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
|
||||
|
||||
assert (custom_nodes / 'removed.py').exists()
|
||||
assert sorted(os.listdir(new)) == ['.tracking', '__init__.py']
|
||||
assert (new / '__init__.py').read_text() == 'VERSION = 2'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('name', ['../removed.py', '{custom_nodes}/removed.py'])
|
||||
def test_reserved_switch_leaves_a_file_outside_the_pack(switch, tmp_path, name):
|
||||
custom_nodes = tmp_path / 'custom_nodes'
|
||||
old, new = old_version(custom_nodes, 'fixture@1_0_0', name.format(custom_nodes=custom_nodes)), custom_nodes / 'fixture@2_0_0'
|
||||
|
||||
assert switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
|
||||
|
||||
assert (custom_nodes / 'removed.py').exists()
|
||||
assert sorted(os.listdir(new)) == ['.tracking', '__init__.py', 'removed.py']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('name, inside', [
|
||||
('removed.py', True), ('nodes/removed.py', True), ('nodes/', True), ('nodes/../removed.py', True), ('', True),
|
||||
('..', False), ('../removed.py', False), ('nodes/../../removed.py', False), ('{pack}/../removed.py', False),
|
||||
('{pack}/removed.py', True), ('{pack}@2/removed.py', False),
|
||||
])
|
||||
def test_name_of_a_file_of_the_pack(tmp_path, name, inside):
|
||||
pack = tmp_path / 'custom_nodes/fixture'
|
||||
pack.mkdir(parents=True)
|
||||
|
||||
assert import_reader('glob').manager_util.is_inside(str(pack), name.format(pack=pack)) is inside
|
||||
|
||||
|
||||
@pytest.mark.parametrize('name', ['removed.py', '../removed.py', '{custom_nodes}/removed.py'])
|
||||
def test_switch_at_once_removes_the_files_of_the_pack_alone(core, monkeypatch, tmp_path, name): # noqa: F811
|
||||
custom_nodes = tmp_path / 'custom_nodes'
|
||||
pack = old_version(custom_nodes, 'fixture', name.format(custom_nodes=custom_nodes))
|
||||
|
||||
assert switch_at_once(core, custom_nodes, monkeypatch.setattr)
|
||||
|
||||
assert (custom_nodes / 'removed.py').exists()
|
||||
assert sorted(os.listdir(pack)) == (['.tracking', '__init__.py'] if name == 'removed.py' else ['.tracking', '__init__.py', 'removed.py'])
|
||||
|
||||
|
||||
def test_reserved_switch_keeps_a_file_that_the_new_archive_names_in_another_way(monkeypatch, tmp_path):
|
||||
custom_nodes = tmp_path / 'custom_nodes'
|
||||
old, new = old_version(custom_nodes, 'fixture@1_0_0', 'removed.py'), custom_nodes / 'fixture@2_0_0'
|
||||
switch = reserved_switch(lambda name, module: monkeypatch.setitem(sys.modules, name, module), download_with_another_name)
|
||||
|
||||
assert switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
|
||||
|
||||
assert (new / '__init__.py').read_text() == 'VERSION = 2'
|
||||
assert sorted(os.listdir(new)) == ['.tracking', '__init__.py']
|
||||
|
||||
|
||||
def test_switch_at_once_keeps_a_file_that_the_new_archive_names_in_another_way(core, monkeypatch, tmp_path): # noqa: F811
|
||||
custom_nodes = tmp_path / 'custom_nodes'
|
||||
pack = old_version(custom_nodes, 'fixture', 'removed.py')
|
||||
|
||||
assert switch_at_once(core, custom_nodes, monkeypatch.setattr, download_with_another_name)
|
||||
|
||||
assert (pack / '__init__.py').read_text() == 'VERSION = 2'
|
||||
assert sorted(os.listdir(pack)) == ['.tracking', '__init__.py']
|
||||
|
||||
|
||||
def two_names_of_one_file(pack):
|
||||
try:
|
||||
(pack / 'alias').symlink_to('.', target_is_directory=True)
|
||||
except OSError:
|
||||
pytest.skip('a link cannot be made here')
|
||||
|
||||
|
||||
def test_reserved_switch_keeps_a_file_that_the_old_list_names_in_a_way_of_its_own(switch, tmp_path):
|
||||
custom_nodes = tmp_path / 'custom_nodes'
|
||||
old, new = old_version(custom_nodes, 'fixture@1_0_0', 'alias/__init__.py'), custom_nodes / 'fixture@2_0_0'
|
||||
two_names_of_one_file(old)
|
||||
|
||||
assert switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
|
||||
|
||||
assert (new / '__init__.py').read_text() == 'VERSION = 2'
|
||||
|
||||
|
||||
def test_switch_at_once_keeps_a_file_that_the_old_list_names_in_a_way_of_its_own(core, monkeypatch, tmp_path): # noqa: F811
|
||||
custom_nodes = tmp_path / 'custom_nodes'
|
||||
pack = old_version(custom_nodes, 'fixture', 'alias/__init__.py')
|
||||
two_names_of_one_file(pack)
|
||||
|
||||
assert switch_at_once(core, custom_nodes, monkeypatch.setattr)
|
||||
|
||||
assert (pack / '__init__.py').read_text() == 'VERSION = 2'
|
||||
|
||||
|
||||
def test_reserved_switch_removes_a_folder_that_the_new_version_lacks(switch, tmp_path):
|
||||
custom_nodes = tmp_path / 'custom_nodes'
|
||||
old, new = old_version(custom_nodes, 'fixture@1_0_0', 'olddir/', 'olddir/old.py', 'removed.py'), custom_nodes / 'fixture@2_0_0'
|
||||
(old / 'olddir').mkdir()
|
||||
(old / 'olddir/old.py').write_text('VERSION = 1')
|
||||
|
||||
assert switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
|
||||
|
||||
assert sorted(os.listdir(new)) == ['.tracking', '__init__.py']
|
||||
|
||||
|
||||
def modules_that_were_imported(pack):
|
||||
"""`olddir/a/b/c/d/old.py`, and what Python and numba write beside a module that is imported, which no list names."""
|
||||
(pack / 'olddir/a/b/c/d/__pycache__').mkdir(parents=True)
|
||||
(pack / 'olddir/__pycache__').mkdir()
|
||||
(pack / 'olddir/a/b/c/d/old.py').write_text('VERSION = 1')
|
||||
for cache in (pack / 'olddir/a/b/c/d/__pycache__', pack / 'olddir/__pycache__'):
|
||||
for name in ('old.cpython-312.pyc', 'old.run-3.py312.nbi', 'old.run-3.py312.1.nbc'):
|
||||
(cache / name).write_bytes(b'')
|
||||
|
||||
|
||||
TRACKED = pytest.mark.parametrize('tracked', [
|
||||
('olddir/a/b/c/d/old.py',),
|
||||
('olddir/', 'olddir/a/', 'olddir/a/b/', 'olddir/a/b/c/', 'olddir/a/b/c/d/', 'olddir/a/b/c/d/old.py'),
|
||||
], ids=['the list names the files alone', 'the list names the folders as well'])
|
||||
|
||||
|
||||
@TRACKED
|
||||
def test_reserved_switch_removes_the_folders_that_the_old_files_leave_empty(switch, tmp_path, tracked):
|
||||
custom_nodes = tmp_path / 'custom_nodes'
|
||||
old, new = old_version(custom_nodes, 'fixture@1_0_0', *tracked, 'removed.py'), custom_nodes / 'fixture@2_0_0'
|
||||
modules_that_were_imported(old)
|
||||
|
||||
assert switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
|
||||
|
||||
assert sorted(os.listdir(new)) == ['.tracking', '__init__.py']
|
||||
|
||||
|
||||
@TRACKED
|
||||
def test_reserved_switch_puts_a_file_where_the_old_version_has_a_folder(monkeypatch, tmp_path, tracked):
|
||||
custom_nodes = tmp_path / 'custom_nodes'
|
||||
old, new = old_version(custom_nodes, 'fixture@1_0_0', *tracked), custom_nodes / 'fixture@2_0_0'
|
||||
modules_that_were_imported(old)
|
||||
switch = reserved_switch(lambda name, module: monkeypatch.setitem(sys.modules, name, module),
|
||||
lambda url, directory, name: download_url(url, directory, name, member='olddir'))
|
||||
|
||||
assert switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
|
||||
|
||||
assert (new / 'olddir').read_text() == 'VERSION = 2'
|
||||
|
||||
|
||||
def test_reserved_switch_keeps_a_folder_with_a_file_that_is_not_of_the_old_version(switch, tmp_path):
|
||||
custom_nodes = tmp_path / 'custom_nodes'
|
||||
old, new = old_version(custom_nodes, 'fixture@1_0_0', 'olddir/a/old.py', 'removed.py'), custom_nodes / 'fixture@2_0_0'
|
||||
(old / 'olddir/a').mkdir(parents=True)
|
||||
(old / 'olddir/a/old.py').write_text('VERSION = 1')
|
||||
(old / 'olddir/made by the user.txt').write_text('kept')
|
||||
|
||||
assert switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
|
||||
|
||||
assert sorted(os.listdir(new / 'olddir')) == ['made by the user.txt']
|
||||
|
||||
|
||||
def test_reserved_switch_removes_an_empty_folder_that_the_list_names(switch, tmp_path):
|
||||
custom_nodes = tmp_path / 'custom_nodes'
|
||||
old, new = old_version(custom_nodes, 'fixture@1_0_0', 'olddir/', 'removed.py'), custom_nodes / 'fixture@2_0_0'
|
||||
(old / 'olddir').mkdir()
|
||||
|
||||
assert switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
|
||||
|
||||
assert sorted(os.listdir(new)) == ['.tracking', '__init__.py']
|
||||
|
||||
|
||||
def test_reserved_switch_keeps_a_folder_that_is_in_the_cache(switch, tmp_path):
|
||||
custom_nodes = tmp_path / 'custom_nodes'
|
||||
old, new = old_version(custom_nodes, 'fixture@1_0_0', 'olddir/old.py', 'removed.py'), custom_nodes / 'fixture@2_0_0'
|
||||
(old / 'olddir/__pycache__/made by the user').mkdir(parents=True)
|
||||
(old / 'olddir/old.py').write_text('VERSION = 1')
|
||||
(old / 'olddir/__pycache__/made by the user/kept.txt').write_text('kept')
|
||||
|
||||
assert switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
|
||||
|
||||
assert (new / 'olddir/__pycache__/made by the user/kept.txt').read_text() == 'kept'
|
||||
|
||||
|
||||
def link_of_a_folder(link, target, junction):
|
||||
"""A symbolic link, or a junction, which Windows makes without a privilege."""
|
||||
if junction:
|
||||
subprocess.run(['cmd', '/c', 'mklink', '/J', str(link), str(target)], check=True, capture_output=True)
|
||||
return
|
||||
try:
|
||||
link.symlink_to(target, target_is_directory=True)
|
||||
except OSError:
|
||||
pytest.skip('a link cannot be made here')
|
||||
|
||||
|
||||
@pytest.mark.parametrize('junction', [False, pytest.param(True, marks=pytest.mark.skipif(os.name != 'nt', reason='a junction is of Windows'))],
|
||||
ids=['symbolic link', 'junction'])
|
||||
@pytest.mark.parametrize('link, cache', [('olddir', 'olddir/__pycache__'), ('olddir/__pycache__', 'olddir/__pycache__'), ('olddir', 'olddir/a/__pycache__')],
|
||||
ids=['the folder is a link', 'the cache is a link', 'the folder is behind a link'])
|
||||
def test_reserved_switch_leaves_the_cache_behind_a_link(switch, tmp_path, link, cache, junction):
|
||||
custom_nodes = tmp_path / 'custom_nodes'
|
||||
old, new = old_version(custom_nodes, 'fixture@1_0_0', os.path.dirname(cache) + '/old.py', 'removed.py'), custom_nodes / 'fixture@2_0_0'
|
||||
kept = tmp_path / 'elsewhere' / cache[len(link) + 1:] / 'other.cpython-312.pyc'
|
||||
kept.parent.mkdir(parents=True)
|
||||
kept.write_bytes(b'')
|
||||
(old / link).parent.mkdir(exist_ok=True)
|
||||
link_of_a_folder(old / link, tmp_path / 'elsewhere', junction)
|
||||
|
||||
assert switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
|
||||
|
||||
assert kept.exists()
|
||||
assert (new / link).is_dir()
|
||||
|
||||
|
||||
def test_reserved_switch_leaves_a_folder_behind_a_link(switch, tmp_path):
|
||||
custom_nodes = tmp_path / 'custom_nodes'
|
||||
old, new = old_version(custom_nodes, 'fixture@1_0_0', 'olddir/a/old.py', 'removed.py'), custom_nodes / 'fixture@2_0_0'
|
||||
(tmp_path / 'elsewhere/a').mkdir(parents=True)
|
||||
(tmp_path / 'elsewhere/a/old.py').write_text('VERSION = 1')
|
||||
link_of_a_folder(old / 'olddir', tmp_path / 'elsewhere', False)
|
||||
|
||||
assert switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
|
||||
|
||||
assert (tmp_path / 'elsewhere/a').is_dir()
|
||||
|
||||
|
||||
def test_reserved_switch_removes_the_folders_of_a_pack_that_is_reached_through_a_link(switch, tmp_path):
|
||||
custom_nodes = tmp_path / 'custom_nodes'
|
||||
(tmp_path / 'elsewhere').mkdir()
|
||||
link_of_a_folder(custom_nodes, tmp_path / 'elsewhere', False)
|
||||
old, new = old_version(custom_nodes, 'fixture@1_0_0', 'olddir/a/b/c/d/old.py', 'removed.py'), custom_nodes / 'fixture@2_0_0'
|
||||
modules_that_were_imported(old)
|
||||
|
||||
assert switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
|
||||
|
||||
assert sorted(os.listdir(new)) == ['.tracking', '__init__.py']
|
||||
|
||||
|
||||
def file_that_cannot_be_removed(pack):
|
||||
(pack / 'olddir').mkdir()
|
||||
(pack / 'olddir/old.py').write_text('VERSION = 1')
|
||||
(pack / 'olddir').chmod(0o555)
|
||||
if os.access(pack / 'olddir', os.W_OK):
|
||||
pytest.skip('the file can be removed here, as by root or on Windows')
|
||||
|
||||
|
||||
def archives(custom_nodes):
|
||||
return [name for name in os.listdir(custom_nodes) if name.endswith('.zip')]
|
||||
|
||||
|
||||
def test_reserved_switch_goes_on_past_a_file_that_cannot_be_removed(switch, tmp_path):
|
||||
custom_nodes = tmp_path / 'custom_nodes'
|
||||
old, new = old_version(custom_nodes, 'fixture@1_0_0', 'olddir/old.py', 'removed.py'), custom_nodes / 'fixture@2_0_0'
|
||||
file_that_cannot_be_removed(old)
|
||||
|
||||
assert switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
|
||||
|
||||
assert sorted(os.listdir(new)) == ['.tracking', '__init__.py', 'olddir']
|
||||
assert (new / '__init__.py').read_text() == 'VERSION = 2'
|
||||
assert archives(custom_nodes) == []
|
||||
|
||||
|
||||
def test_switch_at_once_goes_on_past_a_file_that_cannot_be_removed(core, monkeypatch, tmp_path): # noqa: F811
|
||||
custom_nodes = tmp_path / 'custom_nodes'
|
||||
pack = old_version(custom_nodes, 'fixture', 'olddir/old.py', 'removed.py')
|
||||
file_that_cannot_be_removed(pack)
|
||||
|
||||
assert switch_at_once(core, custom_nodes, monkeypatch.setattr)
|
||||
|
||||
assert sorted(os.listdir(pack)) == ['.tracking', '__init__.py', 'olddir']
|
||||
assert (pack / '__init__.py').read_text() == 'VERSION = 2'
|
||||
assert archives(custom_nodes) == []
|
||||
|
||||
|
||||
def test_reserved_switch_goes_on_past_a_folder_that_cannot_be_removed(switch, tmp_path):
|
||||
custom_nodes = tmp_path / 'custom_nodes'
|
||||
old, new = old_version(custom_nodes, 'fixture@1_0_0', 'olddir/', 'removed.py'), custom_nodes / 'fixture@2_0_0'
|
||||
(old / 'olddir').mkdir(mode=0)
|
||||
if os.access(old / 'olddir', os.R_OK):
|
||||
pytest.skip('the folder can be read here, as by root or on Windows')
|
||||
|
||||
try:
|
||||
assert switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
|
||||
|
||||
assert sorted(os.listdir(new)) == ['.tracking', '__init__.py', 'olddir']
|
||||
assert (new / '__init__.py').read_text() == 'VERSION = 2'
|
||||
finally:
|
||||
(next(pack for pack in (new, old) if pack.exists()) / 'olddir').chmod(0o700)
|
||||
|
||||
|
||||
def test_reserved_switch_does_not_move_a_pack_that_keeps_its_directory(switch, monkeypatch, tmp_path):
|
||||
def move(source, target):
|
||||
raise PermissionError(13, 'Access is denied', source, 5, target)
|
||||
|
||||
monkeypatch.setattr(shutil, 'move', move)
|
||||
custom_nodes = tmp_path / 'custom_nodes'
|
||||
pack = old_version(custom_nodes, 'fixture', 'removed.py')
|
||||
|
||||
assert switch('fixture', 'https://example.invalid/fixture.zip', str(pack), str(pack), False, str(custom_nodes), 'NodeVersionStatusActive')
|
||||
|
||||
assert sorted(os.listdir(pack)) == ['.tracking', '__init__.py']
|
||||
assert (pack / '.tracking').read_text() == '__init__.py'
|
||||
|
||||
|
||||
def test_install_script_of_a_reserved_switch_runs_where_the_pack_was_moved_to(monkeypatch, tmp_path):
|
||||
custom_nodes = tmp_path / 'custom_nodes'
|
||||
old, new = old_version(custom_nodes, 'fixture@1_0_0', 'removed.py'), custom_nodes / 'fixture'
|
||||
commands = []
|
||||
startup = startup_functions(lambda name, module: monkeypatch.setitem(sys.modules, name, module),
|
||||
lambda url, directory, name: download_url(url, directory, name, 'install.py'),
|
||||
script_list_path=str(tmp_path / 'install-scripts.txt'), processed_install=set(), comfy_path=str(tmp_path),
|
||||
process_wrap=lambda command, cwd=None, **options: commands.append((command, cwd)) or 0)
|
||||
(tmp_path / 'install-scripts.txt').write_text(repr(
|
||||
['fixture', '#LAZY-CNR-SWITCH-SCRIPT', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'python', 'NodeVersionStatusActive']))
|
||||
|
||||
startup['execute_startup_script']()
|
||||
|
||||
assert commands == [(['python', 'install.py'], str(new))]
|
||||
|
||||
|
||||
def test_reserved_switch_that_fails_leaves_no_archive(switch, tmp_path):
|
||||
custom_nodes = tmp_path / 'custom_nodes'
|
||||
old, new = old_version(custom_nodes, 'fixture@1_0_0'), custom_nodes / 'fixture@2_0_0'
|
||||
(old / '.tracking').unlink()
|
||||
|
||||
with pytest.raises(FileNotFoundError):
|
||||
switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
|
||||
|
||||
assert archives(custom_nodes) == []
|
||||
|
||||
|
||||
def test_switch_at_once_that_fails_leaves_no_archive(core, monkeypatch, tmp_path): # noqa: F811
|
||||
custom_nodes = tmp_path / 'custom_nodes'
|
||||
(old_version(custom_nodes, 'fixture') / '.tracking').unlink()
|
||||
|
||||
with pytest.raises(FileNotFoundError):
|
||||
switch_at_once(core, custom_nodes, monkeypatch.setattr)
|
||||
|
||||
assert archives(custom_nodes) == []
|
||||
|
||||
|
||||
def test_reserved_switch_to_a_download_that_is_not_a_zip_leaves_the_pack_as_it_is(monkeypatch, tmp_path):
|
||||
custom_nodes = tmp_path / 'custom_nodes'
|
||||
old, new = old_version(custom_nodes, 'fixture@1_0_0', 'removed.py'), custom_nodes / 'fixture@2_0_0'
|
||||
switch = reserved_switch(lambda name, module: monkeypatch.setitem(sys.modules, name, module), download_that_is_not_a_zip)
|
||||
|
||||
assert switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive') is False
|
||||
|
||||
assert not new.exists()
|
||||
assert sorted(os.listdir(old)) == ['.tracking', '__init__.py', 'removed.py']
|
||||
assert (old / '__init__.py').read_text() == 'VERSION = 1'
|
||||
assert archives(custom_nodes) == []
|
||||
|
||||
|
||||
def test_switch_at_once_to_a_download_that_is_not_a_zip_leaves_the_pack_as_it_is(core, monkeypatch, tmp_path): # noqa: F811
|
||||
custom_nodes = tmp_path / 'custom_nodes'
|
||||
pack = old_version(custom_nodes, 'fixture', 'removed.py')
|
||||
|
||||
assert switch_at_once(core, custom_nodes, monkeypatch.setattr, download_that_is_not_a_zip) is False
|
||||
|
||||
assert sorted(os.listdir(pack)) == ['.tracking', '__init__.py', 'removed.py']
|
||||
assert (pack / '__init__.py').read_text() == 'VERSION = 1'
|
||||
assert archives(custom_nodes) == []
|
||||
|
||||
|
||||
def test_reserved_switch_reads_the_list_as_it_is_written(tmp_path):
|
||||
"""The file with the Korean name is not there: the file system of the child cannot name it."""
|
||||
custom_nodes = tmp_path / 'custom_nodes'
|
||||
old, new = old_version(custom_nodes, 'fixture@1_0_0', '예제 사용자.json', 'removed.py'), custom_nodes / 'fixture@2_0_0'
|
||||
call = ('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
|
||||
script = CHILD + f'sys.exit(not cases.reserved_switch(sys.modules.__setitem__)(*{call!r}))\n'
|
||||
|
||||
child = subprocess.run([sys.executable, '-c', script], capture_output=True, text=True, env={**os.environ, **OTHER_ENCODING})
|
||||
|
||||
assert child.returncode == 0, child.stderr[-600:]
|
||||
assert sorted(os.listdir(new)) == ['.tracking', '__init__.py']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('reader', ['glob', 'legacy'])
|
||||
def test_switch_at_once_reads_the_list_as_it_is_written(tmp_path, reader):
|
||||
custom_nodes = tmp_path / 'custom_nodes'
|
||||
pack = old_version(custom_nodes, 'fixture', '예제 사용자.json', 'removed.py')
|
||||
script = CHILD + f'sys.exit(not cases.switch_at_once(import_reader({reader!r}), pathlib.Path({str(custom_nodes)!r}), setattr))\n'
|
||||
|
||||
child = subprocess.run([sys.executable, '-c', script], capture_output=True, text=True, env={**os.environ, **OTHER_ENCODING})
|
||||
|
||||
assert child.returncode == 0, child.stderr[-600:]
|
||||
assert sorted(os.listdir(pack)) == ['.tracking', '__init__.py']
|
||||
|
||||
|
||||
def test_reserved_switch_reads_a_name_with_a_space_at_its_start_as_it_is_written(switch, tmp_path):
|
||||
"""`removed.py` is not in the list: it is a file that someone put into the nodepack."""
|
||||
custom_nodes = tmp_path / 'custom_nodes'
|
||||
old, new = old_version(custom_nodes, 'fixture@1_0_0', ' removed.py'), custom_nodes / 'fixture@2_0_0'
|
||||
(old / ' removed.py').write_text('VERSION = 1')
|
||||
|
||||
assert switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
|
||||
|
||||
assert sorted(os.listdir(new)) == ['.tracking', '__init__.py', 'removed.py']
|
||||
|
||||
|
||||
def test_switch_at_once_reads_a_name_with_a_space_at_its_start_as_it_is_written(core, monkeypatch, tmp_path): # noqa: F811
|
||||
custom_nodes = tmp_path / 'custom_nodes'
|
||||
pack = old_version(custom_nodes, 'fixture', ' removed.py')
|
||||
(pack / ' removed.py').write_text('VERSION = 1')
|
||||
|
||||
assert switch_at_once(core, custom_nodes, monkeypatch.setattr)
|
||||
|
||||
assert sorted(os.listdir(pack)) == ['.tracking', '__init__.py', 'removed.py']
|
||||
@@ -0,0 +1,50 @@
|
||||
import ast
|
||||
|
||||
import pytest
|
||||
|
||||
from legacy_html_testutil import PACKAGE
|
||||
from test_grid_highlight_escaping import browser # noqa: F401 -- fixture
|
||||
from test_share_dialog_matrix_password import EXTENSION, page # noqa: F401 -- fixture
|
||||
|
||||
|
||||
@pytest.mark.parametrize("package", ["glob", "legacy"])
|
||||
def test_the_server_has_no_route_for_the_token(package):
|
||||
source = (PACKAGE / package / "share_3rdparty.py").read_text(encoding="utf-8")
|
||||
paths = [decorator.args[0].value for node in ast.parse(source).body
|
||||
if isinstance(node, ast.AsyncFunctionDef) for decorator in node.decorator_list]
|
||||
|
||||
assert "/v2/manager/share" in paths
|
||||
assert [path for path in paths if "youml" in path] == []
|
||||
|
||||
|
||||
def open_dialog(page, stored): # noqa: F811
|
||||
page.evaluate("""async ({stored, module}) => {
|
||||
window.requested = [];
|
||||
localStorage.clear();
|
||||
if(stored !== null) localStorage.setItem('youml_token', stored);
|
||||
const { YouMLShareDialog } = await import(module);
|
||||
window.dialog = new YouMLShareDialog();
|
||||
await window.dialog.show([], []);
|
||||
}""", {"stored": stored, "module": EXTENSION + "comfyui-share-youml.js"})
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stored, shown", [(None, ""), ("", ""), ("the token", "the token")],
|
||||
ids=["nothing stored", "an empty token", "a token"])
|
||||
def test_the_dialog_opens_with_the_stored_token(page, stored, shown): # noqa: F811
|
||||
open_dialog(page, stored)
|
||||
|
||||
assert page.evaluate("dialog.apiTokenInput.value") == shown
|
||||
assert page.evaluate("window.requested") == []
|
||||
assert page.errors == []
|
||||
|
||||
|
||||
def test_sharing_stores_the_token_in_the_browser(page): # noqa: F811
|
||||
open_dialog(page, "an old token")
|
||||
|
||||
page.evaluate("""async () => {
|
||||
dialog.apiTokenInput.value = 'a new token';
|
||||
await dialog.handleShareButtonClick();
|
||||
}""")
|
||||
|
||||
assert page.evaluate("localStorage.getItem('youml_token')") == "a new token"
|
||||
assert [request for request in page.evaluate("window.requested") if "youml" in request["path"]] == []
|
||||
Reference in New Issue
Block a user