19 Commits
Author SHA1 Message Date
github-actions 2a51f56787 release: 0.4.1 [skip ci] 2024-08-19 09:43:32 +00:00
kaa 66772ffcca fix: resolve for opened file with revert before sync force (#8) 2024-08-19 11:39:12 +02:00
kaamaurice aca00ffd03 fix: re match patterns adjustment 2024-08-01 14:42:08 +02:00
github-actions 5a80af56a7 release: 0.4.0 [skip ci] 2024-08-01 08:57:23 +00:00
kaa fb5f548f0a feat: resolve sync button to force resync in popup warning (#6) 2024-08-01 10:56:05 +02:00
github-actions 6c9746a307 release: 0.3.0 [skip ci] 2024-07-26 10:15:14 +00:00
kaa c1b259c906 feat: Add popup message on sync error or warning (#3) 2024-07-26 11:43:20 +02:00
jeremy-bepoix df7381f679 fix: err typos missing 2024-07-12 17:47:31 +02:00
jeremy-bepoix 649f605a27 fix: err typos missing 2024-07-12 17:38:12 +02:00
jeremy-bepoix f1706ed0ac fix: protected branch 2024-07-12 17:36:10 +02:00
jeremy-bepoix da6af24e82 fix: protected branch 2024-07-12 17:28:36 +02:00
jeremy-bepoix ddfda458b8 fix: err typos missing 2024-07-10 11:48:35 +02:00
jeremy-bepoix 5a71a1da1f fix: add token to bypass release 2024-07-10 11:44:33 +02:00
github-actions f62f0df8ee release: 0.2.0 [skip ci] 2024-07-10 09:03:56 +00:00
Sébastien Albert a153501e0e feat: version update (#1) 2024-07-10 10:53:07 +02:00
Sebastien Albert eb6dd693b7 feat: Move import OpenPype to Ayon 2024-07-10 10:33:16 +02:00
Sébastien Albert 17ddd6178b docs: update readme.md 2024-03-25 23:31:04 +01:00
Sébastien Albert 9bfe2582c0 Update README.md 2024-03-25 22:57:51 +01:00
kaamaurice 915b4d4f85 docs: update readme 2024-03-25 09:23:40 +01:00
10 changed files with 354 additions and 52 deletions

No files matched your search

+1
View File
@@ -18,6 +18,7 @@ jobs:
- uses: actions/checkout@v4
with:
fetch-depth: 0
persist-credentials: false
- name: Python Semantic Release
id: release
uses: python-semantic-release/python-semantic-release@master
+50
View File
@@ -1,6 +1,56 @@
# CHANGELOG
## v0.4.1 (2024-08-19)
### Fix
* fix: resolve for opened file with revert before sync force (#8) ([`66772ff`](https://github.com/LoopsCreativeStudio/ayon-perforce/commit/66772ffcca326ce99e219b6596013ede248b3029))
* fix: re match patterns adjustment ([`aca00ff`](https://github.com/LoopsCreativeStudio/ayon-perforce/commit/aca00ffd032975a05812d43cc13b5561ff81c468))
## v0.4.0 (2024-08-01)
### Feature
* feat: resolve sync button to force resync in popup warning (#6) ([`fb5f548`](https://github.com/LoopsCreativeStudio/ayon-perforce/commit/fb5f548f0af47e8eb89b14e8a862921cd52983f8))
## v0.3.0 (2024-07-26)
### Feature
* feat: Add popup message on sync error or warning (#3) ([`c1b259c`](https://github.com/LoopsCreativeStudio/ayon-perforce/commit/c1b259c90649b3d4bd775880305f3e7f3f2f8bc6))
### Fix
* fix: err typos missing ([`df7381f`](https://github.com/LoopsCreativeStudio/ayon-perforce/commit/df7381f679097064dc06430c35abd633b4506976))
* fix: err typos missing ([`649f605`](https://github.com/LoopsCreativeStudio/ayon-perforce/commit/649f605a27c2626d3d2faa4297be25f1c7f3d512))
* fix: protected branch ([`f1706ed`](https://github.com/LoopsCreativeStudio/ayon-perforce/commit/f1706ed0ac6c88a17dc95a0ae107d6fc4a465b02))
* fix: protected branch ([`da6af24`](https://github.com/LoopsCreativeStudio/ayon-perforce/commit/da6af24e82ac96359013c5b30cdc227e1d79c2d3))
* fix: err typos missing ([`ddfda45`](https://github.com/LoopsCreativeStudio/ayon-perforce/commit/ddfda458b81ddfeb20f68f454dfaea3553596bd8))
* fix: add token to bypass release ([`5a71a1d`](https://github.com/LoopsCreativeStudio/ayon-perforce/commit/5a71a1da1f0bddc7c195fcc4879ac13c38d1802c))
## v0.2.0 (2024-07-10)
### Documentation
* docs: update readme.md ([`17ddd61`](https://github.com/LoopsCreativeStudio/ayon-perforce/commit/17ddd6178bc1c50aca249a62dc43fa821b571aff))
* docs: update readme ([`915b4d4`](https://github.com/LoopsCreativeStudio/ayon-perforce/commit/915b4d4f853fede50c6e74f5bb0126c207b1e6a4))
### Feature
* feat: version update (#1) ([`a153501`](https://github.com/LoopsCreativeStudio/ayon-perforce/commit/a153501e0e6afbc1312f440a2770ec16e4f7b8a3))
* feat: Move import OpenPype to Ayon ([`eb6dd69`](https://github.com/LoopsCreativeStudio/ayon-perforce/commit/eb6dd693b77edd2cda4ecbc3151f95b8a953cf9c))
### Unknown
* Update README.md ([`9bfe258`](https://github.com/LoopsCreativeStudio/ayon-perforce/commit/9bfe2582c0b50c44db89f0b653058eeda06c55f6))
## v0.1.0 (2024-03-19)
+30 -1
View File
@@ -1,7 +1,36 @@
# ayon-perforce
# Perforce integration for AYON
[![Release](https://github.com/LoopsCreativeStudio/ayon-perforce/actions/workflows/release.yml/badge.svg?branch=main)](https://github.com/LoopsCreativeStudio/ayon-perforce/actions/workflows/release.yml)
This adds integration to [Perforce Version Control](https://www.perforce.com/products/helix-core).
The project provides two elements to manage Perforce synchronisation for your AYON pipeline:
* client - The AYON desktop integration.
* server - The AYON backend Addon.
## Client
This contains Perforce client integration used in AYON launchee which acts as a prelaunch hook to perform a Perforce synchronisation before opening applications.
## Server
Once loaded into the backend, restart your server to update addons and start to config your perforce addon settings.
### Settings
Settings let you define the client behavior by overrriding following P4 config variables:
* P4PORT
* P4CLIENT
* P4USER
![image](https://github.com/LoopsCreativeStudio/ayon-perforce/assets/89812691/4f708fb9-b5a0-4657-bd94-f4b31c341bc9)
In order to execute the synchronization in your pipeline, you have to add hosts that use Perforce remote service like Unreal Editor.
This settings can be set at studio level or projects level in your projects settings.
Currently, you have te configure first your Perforce remote server and client user and workspace folder.
Make sure you have the Perforce folder with p4 executables in your PATH environment variable.
### Versioning
-1
View File
@@ -1 +0,0 @@
# Perforce Addon
+10 -6
View File
@@ -1,24 +1,28 @@
"""Perforce Addon Client Module."""
import os
from openpype.modules import OpenPypeModule, ILaunchHookPaths
from ayon_core.addon import AYONAddon
from .version import __version__
PERFORCE_MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
class PerforceAddon(OpenPypeModule, ILaunchHookPaths):
class PerforceAddon(AYONAddon):
"""Perfrorce Addon
"""
name = "perforce"
version = __version__
label = "Perforce"
def initialize(self, module_settings):
def initialize(self, settings) -> None:
"""Initialization of addon attributes.
Args:
settings (dict[str, Any]): Settings.
"""
self.enabled = True
def get_launch_hook_paths(self, app):
def get_launch_hook_paths(self) -> str:
"""Implementation for applications launch hooks.
Returns:
+255 -37
View File
@@ -1,71 +1,222 @@
"""Perforce Sync PreLaunch Hook."""
import re
import subprocess
from typing import Optional, Union, Dict
from openpype.lib.applications import (
from qtpy.QtWidgets import QApplication, QLabel, QPushButton
from qtpy.QtGui import QIcon
from qtpy.QtCore import Qt
from ayon_core.lib import Logger
from ayon_core.resources import get_ayon_icon_filepath
from ayon_core.style import load_stylesheet
from ayon_core.tools.utils import ErrorMessageBox
from ayon_applications import (
PreLaunchHook, LaunchTypes, ApplicationLaunchFailed
)
class PerforceErrorMessageBox(ErrorMessageBox):
"""Perforce Error Message Box."""
def __init__(
self,
p4settings: Dict[str, Union[str, bool]],
exc_msg: str,
msg_type: str = "ERROR",
) -> None:
self._p4settings = p4settings
self._exc_msg = exc_msg
self._msg_type = msg_type
self.log = Logger.get_logger("PerforceResolve")
super().__init__(
f"Perforce {self._msg_type}", QApplication.activeWindow(),
)
self.setModal(True)
self.setWindowIcon(QIcon(get_ayon_icon_filepath()))
self.setStyleSheet(load_stylesheet())
# get ok button
footer_layout = self._footer_widget.layout()
self.ok_btn = footer_layout.itemAt(2).widget()
self.ok_btn.setText("Skip")
# create resolve button
self.resolve_btn = QPushButton("Resolve", self)
self.resolve_btn.clicked.connect(self.resolve_warning)
self.resolve_btn.hide()
footer_layout.addWidget(self.resolve_btn, 0)
if msg_type == "Warning":
self.ok_btn.setText("Skip")
self.resolve_btn.show()
def _create_top_widget(self, parent_widget) -> QLabel:
label_widget = QLabel(parent_widget)
top_msg = (
"Perforce failed to perform sync:"
if self._msg_type == "ERROR"
else "Perforce complete sync with warning messages:"
)
label_widget.setText(f"<span style='font-size:16pt;'>{top_msg}</span>")
return label_widget
def _create_content(self, content_layout) -> None:
content_layout.addWidget(self._create_line())
content_html = [
f"<span style='font-weight:bold;'>{key}:</span> {value}"
for key, value in self._p4settings.items()
if key != "bypass" and (key != "P4USER" or value is not None)
]
content_html.append(
f"<br>{self.convert_text_for_html(self._exc_msg)}"
)
content_label = QLabel("<br>".join(content_html), self)
content_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
content_label.setCursor(Qt.IBeamCursor)
content_layout.addWidget(content_label)
def revert_file(self, depot_file:str) -> subprocess.CompletedProcess:
"""Do a Perforce revert for the give depot file.
Args:
depot_file (str): the depot file to revert.
Returns:
subprocess.CompletedProcess: The process result.
"""
return subprocess.run(
['p4', 'revert', depot_file],
shell=True,
text=True,
check=False,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
errors='replace',
)
def force_sync(self, depot_file:str) -> subprocess.CompletedProcess:
"""Force Perforce sync for the give depot file.
Args:
depot_file (str): the depot file to update.
Returns:
subprocess.CompletedProcess: The process result.
"""
return subprocess.run(
['p4', 'sync', '-f', f'{depot_file}#head'],
shell=True,
text=True,
check=False,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
errors='replace',
)
def resolve_warning(self) -> None:
"""Resolve Perforce sync warning.
"""
result_html = ["<span style='font-size:14pt;'>Resolve Result:</span>"]
result_failed = False
for line in self._exc_msg.splitlines():
wrn_match = re.match(
r"(?P<depotfile>\/\/.*)#\d+"
r" - (?P<opened>is opened for add and )?can't "
r"(overwrite existing file|update modified file|be replaced)"
r"(?P<localfile>.*)$",
line,
)
if not wrn_match:
continue
depot_file = wrn_match.group("depotfile")
# revert if needed
if wrn_match.group("opened"):
self.log.info(f"p4 revert {depot_file}")
revert_result = self.revert_file(depot_file)
self.log.info(f">>> {revert_result.stdout.strip()}")
# force sync
self.log.info(f"p4 sync -f {depot_file}")
result = self.force_sync(depot_file)
stdout_result = result.stdout.strip()
# check sync result
if re.match(r".+ - (refreshing|updating|added) .+", stdout_result):
self.log.info(f">>> {stdout_result}")
color_result = "YellowGreen"
else:
self.log.info(f"!!! {stdout_result}")
color_result = "Orange"
result_failed = True
result_html.append(
f"<span style='color:{color_result};'>"
f"{self.convert_text_for_html(stdout_result)}</span>"
)
resolve_label = QLabel("<br>".join(result_html), self)
resolve_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
resolve_label.setCursor(Qt.IBeamCursor)
content_layout = self._content_widget.layout()
content_layout.insertWidget(2, self._create_line())
content_layout.insertWidget(3, resolve_label)
if not result_failed:
self.resolve_btn.hide()
self.ok_btn.setText("Ok")
else:
self.resolve_btn.setDisabled(True)
class PerforceSync(PreLaunchHook):
"""Run Perforce Sync for the given project config.
"""
order = -1
launch_types = {LaunchTypes.local}
def execute(self, *args, **kwargs):
def _get_p4settings(self) -> Optional[Dict[str, Union[str, bool]]]:
perforce_settings = self.data["project_settings"]["perforce"]
perforce_hosts = {
host["name"]: host["bypass"]
for host in perforce_settings["hosts"]
}
if self.host_name not in perforce_hosts:
return
return None
host_bypass = perforce_hosts[self.host_name]
p4_port = (
p4port = (
perforce_settings.get("p4port")
or self.data["env"].get("P4PORT")
)
p4_client = (
p4client = (
perforce_settings.get("p4client")
or self.data["env"].get("P4CLIENT")
or "{project_name}_{COMPUTERNAME}_{USERNAME}"
)
p4_user = (
p4user = (
perforce_settings.get("p4user")
or self.data["env"].get("P4USER")
)
if p4_client.count("{") == p4_client.count("}") > 0:
p4_client = p4_client.format(
if p4client.count("{") == p4client.count("}") > 0:
p4client = p4client.format(
project_name=self.data["project_name"],
**self.data["env"]
)
if perforce_settings.get("p4client_lower"):
p4_client = p4_client.lower()
p4client = p4client.lower()
self.log.info(f"P4PORT={p4_port or None}")
self.log.info(f"P4CLIENT={p4_client or None}")
self.log.info(f"P4USER={p4_user or None}")
return {
"P4PORT": p4port or None,
"P4CLIENT": p4client or None,
"P4USER": p4user or None,
"bypass": perforce_hosts.get(self.host_name, False)
}
if not p4_port or not p4_client:
self.log.warning("incomplete p4 configuration: skip sync !")
if not host_bypass:
raise ApplicationLaunchFailed(
"Couldn't run the application! Perforce config error!"
)
def run_perforce_sync(
self, p4settings: Dict[str, Union[str, bool]]
) -> None:
"""Run Perforce Sync using the given settings.
subprocess.run(["p4", "set", f"P4PORT={p4_port}"], check=True)
subprocess.run(["p4", "set", f"P4CLIENT={p4_client}"], check=True)
if p4_user:
subprocess.run(["p4", "set", f"P4USER={p4_user}"], check=True)
# start sync
Args:
p4settings (Dict[str, Union[str, bool]]): The perforce settings.
"""
self.log.info("[SYNC PERFORCE PROJECT]")
with subprocess.Popen(
['p4', '-I', 'sync', '-s', '-q'],
@@ -76,21 +227,88 @@ class PerforceSync(PreLaunchHook):
bufsize=0,
errors='replace',
) as process:
complete_log = ""
capture_log = ""
last_percent = None
while process.poll() is None:
capture_log += process.stdout.read(1)
percent_match = re.search(r"\d{1,3}%|finishing", capture_log)
read_log = None
while True:
read_log = process.stdout.read(1)
if read_log == "" and not process.poll() is None:
break
capture_log += read_log
percent_match = re.search(r"(\d{1,3}%|finishing)", capture_log)
warning_match = re.search(
r"(\/\/.+ can't (overwrite|update|be replaced).*)\n",
capture_log,
re.M,
)
if percent_match:
current_percent = percent_match.group(0)
current_percent = percent_match.group(1)
if last_percent != current_percent:
self.log.info(f"sync {current_percent}")
last_percent = current_percent
capture_log = ""
elif warning_match:
warning_message = warning_match.group(1).strip()
self.log.info(f"*** WRN: {warning_message}")
complete_log += warning_message + "\n"
capture_log = ""
elif capture_log.endswith("\n"):
if capture_log.strip():
complete_log += capture_log.strip() + "\n"
capture_log = ""
elif capture_log == "sync ":
capture_log = ""
if process.returncode != 0:
self.log.info(capture_log + process.stdout.read())
self.log.warning("sync error !")
if not host_bypass:
error_msg = (
"Perforce sync process return non-zero code: "
f"{process.returncode}"
)
self.log.error(error_msg)
box = PerforceErrorMessageBox(
p4settings, f"{complete_log}\n{error_msg}"
)
box.exec_()
if not p4settings["bypass"]:
raise ApplicationLaunchFailed(
"Couldn't run the application! Perforce sync failed!"
)
elif complete_log:
box = PerforceErrorMessageBox(
p4settings,
complete_log,
"Warning",
)
box.exec_()
def execute(self, *_args, **_kwargs) -> None:
"""Execute prelaunch hook process."""
p4settings = self._get_p4settings()
if p4settings is None:
return
for key, value in p4settings.items():
self.log.info(f"{key}={value}")
if not p4settings["P4PORT"] or not p4settings["P4CLIENT"]:
error_msg = "Incomplete p4 configuration: skip sync!"
self.log.error(error_msg)
if not p4settings["bypass"]:
raise ApplicationLaunchFailed(
"Couldn't run the application! Perforce config error!"
)
box = PerforceErrorMessageBox(p4settings, error_msg)
box.exec_()
return
for p4env in ("P4PORT", "P4CLIENT", "P4USER"):
if p4settings[p4env] is not None:
subprocess.run(
["p4", "set", f"{p4env}={p4settings[p4env]}"], check=True
)
self.run_perforce_sync(p4settings)
+1 -1
View File
@@ -1,3 +1,3 @@
# -*- coding: utf-8 -*-
"""Package declaring addon version."""
__version__ = "0.1.0"
__version__ = "0.2.0"
+1 -1
View File
@@ -1,7 +1,7 @@
[tool.poetry]
name = "ayon-perforce"
description = "perforce addon for ayon"
version = "0.1.0"
version = "0.4.1"
authors = ["LoopsCreativeStudio <tech@loopscreativestudio.com>"]
license = "Apache-2.0"
readme = "README.md"
+5 -4
View File
@@ -1,4 +1,4 @@
"""Perforce Addon Settings Module."""
from typing import List
from ayon_server.settings import BaseSettingsModel, SettingsField
@@ -13,14 +13,15 @@ DEFAULT_VALUES = {
class HostItemModel(BaseSettingsModel):
"""Host item model for Perforce settings."""
_layout = "compact"
name: str = SettingsField(title="Host name")
bypass: bool = SettingsField(title="Bypass permission")
name: str = SettingsField("", title="Host name")
bypass: bool = SettingsField(False, title="Bypass permission")
class PerforceSettings(BaseSettingsModel):
"""Perforce project settings."""
enabled: bool = SettingsField(default=True)
enabled: bool = SettingsField(True)
hosts: List[HostItemModel] = SettingsField(
default_factory=list,
title="Hosts",
+1 -1
View File
@@ -1,3 +1,3 @@
# -*- coding: utf-8 -*-
"""Package declaring addon version."""
__version__ = "0.1.0"
__version__ = "0.4.1"