-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
publish_session.py
458 lines (355 loc) · 16.3 KB
/
publish_session.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
# ----------------------------------------------------------------------------
# Copyright (c) 2021, Diego Garcia Huerta.
#
# Your use of this software as distributed in this GitHub repository, is
# governed by the MIT License
#
# Your use of the Shotgun Pipeline Toolkit is governed by the applicable
# license agreement between you and Autodesk / Shotgun.
#
# The full license is in the file LICENSE, distributed with this software.
# ----------------------------------------------------------------------------
import os
import itertools
import sgtk
from sgtk.util.filesystem import ensure_folder_exists
import GafferUI
import GafferScene
import GafferImage
from GafferUI.FileMenu import __pathAndBookmarks
__author__ = "Diego Garcia Huerta"
__contact__ = "https://www.linkedin.com/in/diegogh/"
HookBaseClass = sgtk.get_hook_baseclass()
class GafferSessionPublishPlugin(HookBaseClass):
"""
Plugin for publishing an open gaffer session.
This hook relies on functionality found in the base file publisher hook in
the publish2 app and should inherit from it in the configuration. The hook
setting for this plugin should look something like this::
hook: "{self}/publish_file.py:{engine}/tk-multi-publish2/basic/publish_session.py"
"""
# NOTE: The plugin icon and name are defined by the base file plugin.
@property
def description(self):
"""
Verbose, multi-line description of what the plugin does. This can
contain simple html for formatting.
"""
loader_url = "https://support.shotgunsoftware.com/hc/en-us/articles/219033078"
return """
Publishes the file to Shotgun. A <b>Publish</b> entry will be
created in Shotgun which will include a reference to the file's current
path on disk. If a publish template is configured, a copy of the
current session will be copied to the publish template path which
will be the file that is published. Other users will be able to access
the published file via the <b><a href='%s'>Loader</a></b> so long as
they have access to the file's location on disk.
If the session has not been saved, validation will fail and a button
will be provided in the logging output to save the file.
<h3>File versioning</h3>
If the filename contains a version number, the process will bump the
file to the next version after publishing.
The <code>version</code> field of the resulting <b>Publish</b> in
Shotgun will also reflect the version number identified in the filename.
The basic worklfow recognizes the following version formats by default:
<ul>
<li><code>filename.v###.ext</code></li>
<li><code>filename_v###.ext</code></li>
<li><code>filename-v###.ext</code></li>
</ul>
After publishing, if a version number is detected in the work file, the
work file will automatically be saved to the next incremental version
number. For example, <code>filename.v001.ext</code> will be published
and copied to <code>filename.v002.ext</code>
If the next incremental version of the file already exists on disk, the
validation step will produce a warning, and a button will be provided in
the logging output which will allow saving the session to the next
available version number prior to publishing.
<br><br><i>NOTE: any amount of version number padding is supported. for
non-template based workflows.</i>
<h3>Overwriting an existing publish</h3>
In non-template workflows, a file can be published multiple times,
however only the most recent publish will be available to other users.
Warnings will be provided during validation if there are previous
publishes.
""" % (
loader_url,
)
@property
def settings(self):
"""
Dictionary defining the settings that this plugin expects to receive
through the settings parameter in the accept, validate, publish and
finalize methods.
A dictionary on the following form::
{
"Settings Name": {
"type": "settings_type",
"default": "default_value",
"description": "One line description of the setting"
}
The type string should be one of the data types that toolkit accepts as
part of its environment configuration.
"""
# inherit the settings from the base publish plugin
base_settings = super(GafferSessionPublishPlugin, self).settings or {}
# settings specific to this class
gaffer_publish_settings = {
"Publish Template": {
"type": "template",
"default": None,
"description": "Template path for published work files. Should"
"correspond to a template defined in "
"templates.yml.",
}
}
# update the base settings
base_settings.update(gaffer_publish_settings)
return base_settings
@property
def item_filters(self):
"""
List of item types that this plugin is interested in.
Only items matching entries in this list will be presented to the
accept() method. Strings can contain glob patters such as *, for example
["gaffer.*", "file.gaffer"]
"""
return ["gaffer.session"]
def accept(self, settings, item):
"""
Method called by the publisher to determine if an item is of any
interest to this plugin. Only items matching the filters defined via the
item_filters property will be presented to this method.
A publish task will be generated for each item accepted here. Returns a
dictionary with the following booleans:
- accepted: Indicates if the plugin is interested in this value at
all. Required.
- enabled: If True, the plugin will be enabled in the UI, otherwise
it will be disabled. Optional, True by default.
- visible: If True, the plugin will be visible in the UI, otherwise
it will be hidden. Optional, True by default.
- checked: If True, the plugin will be checked in the UI, otherwise
it will be unchecked. Optional, True by default.
:param settings: Dictionary of Settings. The keys are strings, matching
the keys returned in the settings property. The values are `Setting`
instances.
:param item: Item to process
:returns: dictionary with boolean keys accepted, required and enabled
"""
# if a publish template is configured, disable context change. This
# is a temporary measure until the publisher handles context switching
# natively.
if settings.get("Publish Template").value:
item.context_change_allowed = False
path = _session_path()
if not path:
# the session has not been saved before (no path determined).
# provide a save button. the session will need to be saved before
# validation will succeed.
self.logger.warn(
"The Gaffer session has not been saved.", extra=_get_save_as_action()
)
self.logger.info(
"Gaffer '%s' plugin accepted the current Gaffer session." % (self.name,)
)
return {"accepted": True, "checked": True}
def validate(self, settings, item):
"""
Validates the given item to check that it is ok to publish. Returns a
boolean to indicate validity.
:param settings: Dictionary of Settings. The keys are strings, matching
the keys returned in the settings property. The values are `Setting`
instances.
:param item: Item to process
:returns: True if item is valid, False otherwise.
"""
publisher = self.parent
path = _session_path()
# ---- ensure the session has been saved
if not path:
# the session still requires saving. provide a save button.
# validation fails.
error_msg = "The Gaffer session has not been saved."
self.logger.error(error_msg, extra=_get_save_as_action())
raise Exception(error_msg)
# ---- check the session against any attached work template
# get the path in a normalized state. no trailing separator,
# separators are appropriate for current os, no double separators,
# etc.
path = sgtk.util.ShotgunPath.normalize(path)
# if the session item has a known work template, see if the path
# matches. if not, warn the user and provide a way to save the file to
# a different path
work_template = item.properties.get("work_template")
if work_template:
if not work_template.validate(path):
self.logger.warning(
"The current session does not match the configured work "
"file template.",
extra={
"action_button": {
"label": "Save File",
"tooltip": "Save the current Gaffer session to a "
"different file name",
# will launch wf2 if configured
"callback": _get_save_as_action(),
}
},
)
else:
self.logger.debug("Work template configured and matches session file.")
else:
self.logger.debug("No work template configured.")
# ---- see if the version can be bumped post-publish
# check to see if the next version of the work file already exists on
# disk. if so, warn the user and provide the ability to jump to save
# to that version now
(next_version_path, version) = self._get_next_version_info(path, item)
if next_version_path and os.path.exists(next_version_path):
# determine the next available version_number. just keep asking for
# the next one until we get one that doesn't exist.
while os.path.exists(next_version_path):
(next_version_path, version) = self._get_next_version_info(
next_version_path, item
)
error_msg = "The next version of this file already exists on disk."
self.logger.error(
error_msg,
extra={
"action_button": {
"label": "Save to v%s" % (version,),
"tooltip": "Save to the next available version number, "
"v%s" % (version,),
"callback": lambda: _save_session(next_version_path),
}
},
)
raise Exception(error_msg)
# ---- populate the necessary properties and call base class validation
# populate the publish template on the item if found
publish_template_setting = settings.get("Publish Template")
publish_template = publisher.engine.get_template_by_name(
publish_template_setting.value
)
if publish_template:
item.properties["publish_template"] = publish_template
# set the session path on the item for use by the base plugin validation
# step. NOTE: this path could change prior to the publish phase.
item.properties["path"] = path
# run the base class validation
return super(GafferSessionPublishPlugin, self).validate(settings, item)
def publish(self, settings, item):
"""
Executes the publish logic for the given item and settings.
:param settings: Dictionary of Settings. The keys are strings, matching
the keys returned in the settings property. The values are `Setting`
instances.
:param item: Item to process
"""
# get the path in a normalized state. no trailing separator, separators
# are appropriate for current os, no double separators, etc.
path = sgtk.util.ShotgunPath.normalize(_session_path())
# ensure the session is saved
_save_session(path)
# update the item with the saved session path
item.properties["path"] = path
# add dependencies for the base class to register when publishing
item.properties[
"publish_dependencies"
] = _gaffer_find_additional_session_dependencies()
# let the base class register the publish
super(GafferSessionPublishPlugin, self).publish(settings, item)
def finalize(self, settings, item):
"""
Execute the finalization pass. This pass executes once all the publish
tasks have completed, and can for example be used to version up files.
:param settings: Dictionary of Settings. The keys are strings, matching
the keys returned in the settings property. The values are `Setting`
instances.
:param item: Item to process
"""
# do the base class finalization
super(GafferSessionPublishPlugin, self).finalize(settings, item)
# bump the session file to the next version
self._save_to_next_version(item.properties["path"], item, _save_session)
def nodes_of_type(node_type, node=None, result=None):
if result is None:
result = []
if isinstance(node, node_type):
result.append(node)
for child in node.children():
nodes_of_type(node_type, node=child, result=result)
return result
def _gaffer_find_additional_session_dependencies():
"""
Find additional dependencies from the session
"""
# Figure out what read nodes are known to the engine and use them
# as dependencies
ref_paths = set()
engine = sgtk.platform.current_engine()
scene_reader_nodes = nodes_of_type(GafferScene.SceneReader, node=engine.script)
image_reader_nodes = nodes_of_type(GafferImage.ImageReader, node=engine.script)
for node in itertools.chain(scene_reader_nodes, image_reader_nodes):
ref_path = node["fileName"].getValue()
ref_path = ref_path.replace("/", os.path.sep)
ref_paths.add(ref_path)
return list(ref_paths)
def _session_path():
"""
Return the path to the current session
:return:
"""
engine = sgtk.platform.current_engine()
current_script_filename = engine.script["fileName"].getValue()
return current_script_filename
def _save_session(path):
"""
Save the current session to the supplied path.
"""
# Ensure that the folder is created when saving
folder = os.path.dirname(path)
ensure_folder_exists(folder)
engine = sgtk.platform.current_engine()
script = engine.script
script["fileName"].setValue(path)
with GafferUI.ErrorDialogue.ErrorHandler(
title="Error Saving File", parentWindow=engine.script_window
):
script.serialiseToFile(path)
# TODO: method duplicated in all the gaffer hooks
def _get_save_as_action():
"""
Simple helper for returning a log action dict for saving the session
"""
engine = sgtk.platform.current_engine()
callback = _save_as
# if workfiles2 is configured, use that for file save
if "tk-multi-workfiles2" in engine.apps:
app = engine.apps["tk-multi-workfiles2"]
if hasattr(app, "show_file_save_dlg"):
callback = app.show_file_save_dlg
return {
"action_button": {
"label": "Save As...",
"tooltip": "Save the current session",
"callback": callback,
}
}
def _save_as():
engine = sgtk.platform.current_engine()
path, bookmarks = __pathAndBookmarks(engine.script_window)
dialogue = GafferUI.PathChooserDialogue(
path, title="Save script", confirmLabel="Save", leaf=True, bookmarks=bookmarks
)
path = dialogue.waitForPath(parentWindow=engine.script_window)
if not path:
return
path = str(path)
if not path.endswith(".gfr"):
path += ".gfr"
engine.script["fileName"].setValue(path)
with GafferUI.ErrorDialogue.ErrorHandler(
title="Error Saving File", parentWindow=engine.script_windowWindow
):
engine.script.save()