davinci-resolve-mcp 5.0.8 → 5.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +38 -0
- package/README.md +6 -1
- package/README.zh-CN.md +6 -2
- package/docs/SKILL.md +15 -0
- package/docs/guides/film-cues.md +57 -0
- package/docs/guides/film-picture-changes.md +196 -0
- package/docs/guides/film-workflow.md +145 -0
- package/docs/reference/typed-api-search.md +22 -10
- package/install.py +1 -1
- package/package.json +1 -1
- package/src/granular/common.py +1 -1
- package/src/granular/resolve_control.py +23 -9
- package/src/server.py +89 -12
- package/src/utils/destructive_hook.py +11 -0
- package/src/utils/execution_lifecycle.py +37 -0
- package/src/utils/film_cues.py +85 -0
- package/src/utils/film_picture_changes.py +381 -0
- package/src/utils/film_preflight.py +162 -0
- package/src/utils/film_stem_return.py +224 -0
- package/src/utils/operation_result.py +14 -0
- package/src/utils/timeline_versioning.py +16 -1
- package/src/utils/typed_api_search.py +98 -21
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
"""Verified film-stems/v1 return into new Resolve audio tracks."""
|
|
2
|
+
from fractions import Fraction
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
import math
|
|
6
|
+
import os
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
import re
|
|
9
|
+
import wave
|
|
10
|
+
|
|
11
|
+
from .film_cues import _rate
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def digest(value):
|
|
15
|
+
return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(',', ':'),
|
|
16
|
+
allow_nan=False).encode()).hexdigest()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def file_hash(path):
|
|
20
|
+
result = hashlib.sha256()
|
|
21
|
+
with open(path, 'rb') as stream:
|
|
22
|
+
for block in iter(lambda: stream.read(1024*1024), b''): result.update(block)
|
|
23
|
+
return result.hexdigest()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def integer(value, name, minimum=0):
|
|
27
|
+
if type(value) is not int or value < minimum or value > 2**53:
|
|
28
|
+
raise ValueError(f'{name} must be an integer in [{minimum}, 2**53]')
|
|
29
|
+
return value
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _round(value):
|
|
33
|
+
return (2*value.numerator + value.denominator)//(2*value.denominator)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def audit_package(delivery_dir):
|
|
37
|
+
"""Read-only independent manifest, PCM WAV and SHA verification."""
|
|
38
|
+
root = Path(delivery_dir).resolve(strict=True)
|
|
39
|
+
path = root/'manifest.json'
|
|
40
|
+
with path.open('rb') as stream: raw = stream.read(8*1024*1024+1)
|
|
41
|
+
if len(raw) > 8*1024*1024: raise ValueError('Manifest too large')
|
|
42
|
+
m = json.loads(raw)
|
|
43
|
+
if not isinstance(m, dict) or m.get('schema') != 'film-stems/v1' or m.get('subtype') != 'PCM_24':
|
|
44
|
+
raise ValueError('Expected film-stems/v1 PCM_24 manifest')
|
|
45
|
+
rate = m.get('frame_rate')
|
|
46
|
+
if not isinstance(rate, dict): raise ValueError('Invalid frame_rate')
|
|
47
|
+
fps = Fraction(integer(rate.get('numerator'), 'numerator', 1),
|
|
48
|
+
integer(rate.get('denominator'), 'denominator', 1))
|
|
49
|
+
if not 1 <= fps <= 240: raise ValueError('Unsupported frame rate')
|
|
50
|
+
start, end, tail = (integer(m.get(k), k) for k in ('start_frame','end_frame','tail_frames'))
|
|
51
|
+
sr = integer(m.get('sample_rate'), 'sample_rate', 8000)
|
|
52
|
+
if end <= start or sr > 384000: raise ValueError('Invalid range/sample rate')
|
|
53
|
+
a, b, c = (_round(Fraction(frame*sr, 1)/fps) for frame in (start,end,end+tail))
|
|
54
|
+
expected = dict(start_sample=a, end_sample=c, sample_count=c-a,
|
|
55
|
+
body_sample_count=b-a, tail_sample_count=c-b)
|
|
56
|
+
for key, value in expected.items():
|
|
57
|
+
if integer(m.get(key), key) != value: raise ValueError(f'Clock mismatch: {key}')
|
|
58
|
+
stems = m.get('stems')
|
|
59
|
+
if not isinstance(stems, list) or not 1 <= len(stems) <= 64: raise ValueError('Expected 1-64 stems')
|
|
60
|
+
seen, rows = set(), []
|
|
61
|
+
for stem in stems:
|
|
62
|
+
if not isinstance(stem, dict): raise ValueError('Stem must be an object')
|
|
63
|
+
name = stem.get('name')
|
|
64
|
+
if not isinstance(name, str) or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_-]{0,79}', name):
|
|
65
|
+
raise ValueError('Invalid stem name')
|
|
66
|
+
if name.casefold() in seen or stem.get('file') != name+'.wav': raise ValueError('Duplicate or unsafe filename')
|
|
67
|
+
seen.add(name.casefold())
|
|
68
|
+
target = root/stem['file']
|
|
69
|
+
if target.is_symlink() or target.resolve(strict=True).parent != root or target.is_reserved():
|
|
70
|
+
raise ValueError('Stem path escapes delivery directory')
|
|
71
|
+
sha = file_hash(target)
|
|
72
|
+
if sha != stem.get('sha256'): raise ValueError(f'{name}: SHA-256 mismatch')
|
|
73
|
+
with wave.open(str(target), 'rb') as wav:
|
|
74
|
+
channels = integer(stem.get('channels'), 'channels', 1)
|
|
75
|
+
if (channels not in (1,2) or wav.getnchannels() != channels or wav.getsampwidth()!=3
|
|
76
|
+
or wav.getframerate()!=sr or wav.getnframes()!=c-a or wav.getcomptype()!='NONE'):
|
|
77
|
+
raise ValueError(f'{name}: WAV format/count mismatch')
|
|
78
|
+
left = c-a
|
|
79
|
+
while left:
|
|
80
|
+
count = min(left,65536)
|
|
81
|
+
if len(wav.readframes(count)) != count*channels*3: raise ValueError('Truncated WAV')
|
|
82
|
+
left -= count
|
|
83
|
+
if file_hash(target) != sha: raise ValueError('Stem changed during audit')
|
|
84
|
+
rows.append({'name':name,'path':str(target),'channels':channels,'sha256':sha,
|
|
85
|
+
'tail_not_quiet':stem.get('tail_not_quiet')})
|
|
86
|
+
return {'schema':'film-stem-audit/v1','status':'passed','package_id':digest(m),
|
|
87
|
+
'manifest':m,'stems':rows,'delivery_dir':str(root),
|
|
88
|
+
'capture_alignment_verified':False}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _path(value):
|
|
92
|
+
# realpath, not abspath: audit_package resolves the delivery root, so stem
|
|
93
|
+
# paths come back with symlinks resolved (/private/var/... on macOS), while
|
|
94
|
+
# Resolve reports the path it was handed (/var/...). Comparing unresolved
|
|
95
|
+
# forms never matched, so a previous import went undetected.
|
|
96
|
+
return os.path.normcase(os.path.realpath(value)) if value else ''
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _number(value):
|
|
100
|
+
if isinstance(value,bool) or not isinstance(value,(float,int)) or not math.isfinite(value):
|
|
101
|
+
raise ValueError('Unreadable timeline coordinate')
|
|
102
|
+
return value
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _snapshot(tl):
|
|
106
|
+
identity = tl.GetUniqueId()
|
|
107
|
+
if not isinstance(identity,str) or not identity: raise ValueError('Timeline identity unavailable')
|
|
108
|
+
tracks = []
|
|
109
|
+
count = integer(tl.GetTrackCount('audio'),'audio tracks')
|
|
110
|
+
for index in range(1,count+1):
|
|
111
|
+
items = tl.GetItemListInTrack('audio',index)
|
|
112
|
+
if not isinstance(items,list): raise ValueError('Audio track enumeration unavailable')
|
|
113
|
+
rows = []
|
|
114
|
+
for item in items:
|
|
115
|
+
media = item.GetMediaPoolItem()
|
|
116
|
+
rows.append({'id':item.GetUniqueId(),'path':_path(media.GetClipProperty('File Path')) if media else '',
|
|
117
|
+
'start':_number(item.GetStart(True)), 'duration':_number(item.GetDuration(True))})
|
|
118
|
+
tracks.append({'index':index,'name':tl.GetTrackName('audio',index),'items':rows})
|
|
119
|
+
return {'id':identity,'name':tl.GetName(),'start_frame':integer(tl.GetStartFrame(),'timeline start'),
|
|
120
|
+
'fps':str(_rate(tl.GetSetting('timelineFrameRate'))),'tracks':tracks}
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def prepare_return(project, delivery_dir, preview=True, expected_timeline_id=None,
|
|
124
|
+
expected_fingerprint=None):
|
|
125
|
+
if type(preview) is not bool: raise ValueError('preview must be boolean')
|
|
126
|
+
if not preview and (not expected_timeline_id or not expected_fingerprint):
|
|
127
|
+
raise ValueError('Apply requires expected_timeline_id and preview fingerprint')
|
|
128
|
+
audit = audit_package(delivery_dir)
|
|
129
|
+
m = audit['manifest']; tl = project.GetCurrentTimeline()
|
|
130
|
+
if not tl: raise ValueError('No current timeline')
|
|
131
|
+
snapshot = _snapshot(tl)
|
|
132
|
+
fps = Fraction(m['frame_rate']['numerator'],m['frame_rate']['denominator'])
|
|
133
|
+
if Fraction(snapshot['fps']) != fps: raise ValueError('Delivery/timeline frame rate mismatch')
|
|
134
|
+
record = snapshot['start_frame']+m['start_frame']
|
|
135
|
+
duration = m['end_frame']+m['tail_frames']-m['start_frame']
|
|
136
|
+
tolerance = float(fps/m['sample_rate']) + 1e-8
|
|
137
|
+
names = [f"FILM_{audit['package_id'][:12]}_{s['name']}" for s in audit['stems']]
|
|
138
|
+
present = []
|
|
139
|
+
for stem,name in zip(audit['stems'],names):
|
|
140
|
+
matches = [(track,item) for track in snapshot['tracks'] for item in track['items']
|
|
141
|
+
if item['path']==_path(stem['path'])]
|
|
142
|
+
if matches:
|
|
143
|
+
if len(matches)!=1: raise ValueError('Duplicate stem instances; manual review required')
|
|
144
|
+
track,item = matches[0]
|
|
145
|
+
if (track['name']!=name or abs(item['start']-record)>tolerance
|
|
146
|
+
or abs(item['duration']-duration)>tolerance):
|
|
147
|
+
raise ValueError('Existing stem has conflicting placement or track')
|
|
148
|
+
present.append(name)
|
|
149
|
+
elif any(t['name']==name for t in snapshot['tracks']):
|
|
150
|
+
raise ValueError('Target track name already exists without matching stem')
|
|
151
|
+
if present and len(present)!=len(names): raise ValueError('Partial previous import; manual review required')
|
|
152
|
+
result = {'status':'already_present' if present else 'preview',
|
|
153
|
+
'schema':'film-stem-return/v1','timeline_id':snapshot['id'],
|
|
154
|
+
'package_id':audit['package_id'],'record_frame':record,'duration_frames':duration,
|
|
155
|
+
'track_names':names,'fingerprint':digest({'audit':audit,'timeline':snapshot}),
|
|
156
|
+
'sample_boundary_rounding':'nearest sample; timeline placement at the requested picture frame',
|
|
157
|
+
'capture_alignment_verified':False}
|
|
158
|
+
if not preview and (snapshot['id']!=expected_timeline_id or result['fingerprint']!=expected_fingerprint):
|
|
159
|
+
raise ValueError('Preview is stale or target timeline changed; preview again')
|
|
160
|
+
if preview or present: return result
|
|
161
|
+
created, imported = [], []
|
|
162
|
+
partially_created_unknown = False
|
|
163
|
+
def same_target():
|
|
164
|
+
current = project.GetCurrentTimeline()
|
|
165
|
+
if not current or current.GetUniqueId()!=snapshot['id']: raise ValueError('Active timeline changed')
|
|
166
|
+
try:
|
|
167
|
+
same_target()
|
|
168
|
+
pool = project.GetMediaPool()
|
|
169
|
+
# ImportMedia may mutate the pool before raising or returning partial handles.
|
|
170
|
+
# Keep every readable receipt; an empty receipt list does not prove no import.
|
|
171
|
+
partially_created_unknown = True
|
|
172
|
+
media = pool.ImportMedia([s['path'] for s in audit['stems']])
|
|
173
|
+
by_path = {}
|
|
174
|
+
if isinstance(media, list):
|
|
175
|
+
for item in media:
|
|
176
|
+
try:
|
|
177
|
+
path = item.GetClipProperty('File Path')
|
|
178
|
+
if not isinstance(path, str) or not path:
|
|
179
|
+
continue
|
|
180
|
+
imported.append(path)
|
|
181
|
+
by_path[_path(path)] = item
|
|
182
|
+
except Exception:
|
|
183
|
+
# One unusable handle must not hide receipts for other imports.
|
|
184
|
+
continue
|
|
185
|
+
if not isinstance(media,list) or len(media)!=len(names): raise ValueError('Media import incomplete')
|
|
186
|
+
if len(by_path)!=len(media): raise ValueError('Media import receipts incomplete')
|
|
187
|
+
partially_created_unknown = False
|
|
188
|
+
source_rates = {}
|
|
189
|
+
for stem in audit['stems']:
|
|
190
|
+
item = by_path.get(_path(stem['path']))
|
|
191
|
+
if not item: raise ValueError('Imported media paths differ from package')
|
|
192
|
+
source_rates[stem['path']] = _rate(item.GetClipProperty('FPS'))
|
|
193
|
+
if _snapshot(tl)!=snapshot: raise ValueError('Timeline changed during media import')
|
|
194
|
+
for stem,name in zip(audit['stems'],names):
|
|
195
|
+
same_target()
|
|
196
|
+
if file_hash(stem['path'])!=stem['sha256']: raise ValueError('Stem changed after preview')
|
|
197
|
+
index = tl.GetTrackCount('audio')+1
|
|
198
|
+
if not tl.AddTrack('audio',{'audioType':'mono' if stem['channels']==1 else 'stereo'}):
|
|
199
|
+
raise ValueError('AddTrack failed')
|
|
200
|
+
created.append({'index':index,'name':name})
|
|
201
|
+
if tl.GetTrackCount('audio')!=index or tl.GetItemListInTrack('audio',index):
|
|
202
|
+
raise ValueError('New track was not empty or track list changed')
|
|
203
|
+
if not tl.SetTrackName('audio',index,name): raise ValueError('SetTrackName failed')
|
|
204
|
+
same_target()
|
|
205
|
+
# WAV source coordinates use the media item's imported FPS, not the timeline FPS.
|
|
206
|
+
source_duration = Fraction(duration,1)/fps * source_rates[stem['path']]
|
|
207
|
+
# Audio endFrame is an exclusive endpoint on the verified Resolve build.
|
|
208
|
+
# Video's common inclusive-end convention would lose one source frame.
|
|
209
|
+
returned = pool.AppendToTimeline([{'mediaPoolItem':by_path[_path(stem['path'])],
|
|
210
|
+
'startFrame':0,'endFrame':float(source_duration),'recordFrame':record,
|
|
211
|
+
'trackIndex':index,'mediaType':2}])
|
|
212
|
+
if not returned: raise ValueError('AppendToTimeline returned no items')
|
|
213
|
+
readback = _snapshot(tl)['tracks'][index-1]
|
|
214
|
+
if readback['name']!=name or len(readback['items'])!=1: raise ValueError('Track readback mismatch')
|
|
215
|
+
row = readback['items'][0]
|
|
216
|
+
if (row['path']!=_path(stem['path']) or abs(row['start']-record)>tolerance
|
|
217
|
+
or abs(row['duration']-duration)>tolerance): raise ValueError('Placement readback mismatch')
|
|
218
|
+
same_target()
|
|
219
|
+
return {**result,'status':'imported','created_tracks':created,'verified':True}
|
|
220
|
+
except Exception as exc:
|
|
221
|
+
return {**result,'status':'partial_failure','error':str(exc),'created_tracks':created,
|
|
222
|
+
'imported_media':imported,'rollback_attempted':False,
|
|
223
|
+
'partially_created_unknown':partially_created_unknown,
|
|
224
|
+
'warning':'Inspect created tracks/media before retrying; nothing automatically deleted.'}
|
|
@@ -110,6 +110,20 @@ def normalize_status(raw: Any) -> str:
|
|
|
110
110
|
if raw.get("status") == "confirmation_required" or raw.get("confirmation_required") is True:
|
|
111
111
|
return "blocked"
|
|
112
112
|
|
|
113
|
+
# These film schemas define report outcomes, including partial mutations
|
|
114
|
+
# accompanied by an error. Do not infer these meanings for other schemas.
|
|
115
|
+
if raw.get("schema") == "film-preflight/v1":
|
|
116
|
+
film_statuses = {
|
|
117
|
+
"failed": "failed", "incomplete": "blocked",
|
|
118
|
+
"warnings": "partial", "passed": "success",
|
|
119
|
+
}
|
|
120
|
+
status = raw.get("status")
|
|
121
|
+
if isinstance(status, str) and status in film_statuses:
|
|
122
|
+
return film_statuses[status]
|
|
123
|
+
if (raw.get("schema") == "film-stem-return/v1"
|
|
124
|
+
and raw.get("status") == "partial_failure"):
|
|
125
|
+
return "partial"
|
|
126
|
+
|
|
113
127
|
if raw.get("error"):
|
|
114
128
|
return "failed"
|
|
115
129
|
if raw.get("success") is False:
|
|
@@ -156,11 +156,26 @@ def archive_current_timeline(
|
|
|
156
156
|
|
|
157
157
|
# Resolve duplication must happen on the live timeline; pin current folder
|
|
158
158
|
# to Archive bin first so the duplicate lands there directly.
|
|
159
|
+
# The caller's current bin is restored afterwards: the destructive action
|
|
160
|
+
# that runs next may import media (timeline.film_stems_return does), and
|
|
161
|
+
# ImportMedia lands in the CURRENT bin, i.e. the Archive bin if left there.
|
|
162
|
+
try:
|
|
163
|
+
prior_folder = media_pool.GetCurrentFolder()
|
|
164
|
+
except Exception:
|
|
165
|
+
prior_folder = None
|
|
159
166
|
archive_bin = _ensure_archive_bin(media_pool)
|
|
160
167
|
if not media_pool.SetCurrentFolder(archive_bin):
|
|
161
168
|
return {"success": False, "error": "Failed to set Archive as current bin"}
|
|
162
169
|
|
|
163
|
-
|
|
170
|
+
try:
|
|
171
|
+
dup = tl.DuplicateTimeline(archived_name)
|
|
172
|
+
finally:
|
|
173
|
+
if prior_folder is not None:
|
|
174
|
+
try:
|
|
175
|
+
if not media_pool.SetCurrentFolder(prior_folder):
|
|
176
|
+
logger.warning("could not restore the current bin after archiving")
|
|
177
|
+
except Exception as exc:
|
|
178
|
+
logger.warning("could not restore the current bin after archiving: %s", exc)
|
|
164
179
|
if dup is None:
|
|
165
180
|
return {"success": False, "error": f"DuplicateTimeline('{archived_name}') failed"}
|
|
166
181
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"""Query the
|
|
1
|
+
"""Query the Resolve typed stub from inside the server.
|
|
2
2
|
|
|
3
3
|
PR #205 landed Blackmagic's `DaVinciResolveScript.pyi` in `docs/reference/`, and
|
|
4
4
|
`scripts/audit_typed_api.py` can turn it into a full inventory — but only from a
|
|
@@ -25,14 +25,70 @@ from typing import Any, Dict, List, Optional
|
|
|
25
25
|
|
|
26
26
|
STUB_RELATIVE = os.path.join("docs", "reference", "DaVinciResolveScript.pyi")
|
|
27
27
|
MAX_RESULTS = 200
|
|
28
|
+
STUB_SOURCES = ("auto", "shipped", "installed")
|
|
28
29
|
|
|
29
30
|
|
|
30
31
|
class TypedApiError(ValueError):
|
|
31
32
|
"""The stub is missing, unparseable, or the query was unusable."""
|
|
32
33
|
|
|
33
34
|
|
|
34
|
-
def
|
|
35
|
-
|
|
35
|
+
def installed_stub_path() -> Optional[str]:
|
|
36
|
+
"""The stub the installed Resolve writes next to its scripting API.
|
|
37
|
+
|
|
38
|
+
The copy in `docs/reference` is a snapshot of the build it was pinned at.
|
|
39
|
+
Resolve installs its own stub alongside the scripting API and refreshes it
|
|
40
|
+
with the build, so on a newer Resolve that file is the accurate inventory.
|
|
41
|
+
Reading it is what stops a 21.2 server from reporting 21.2 methods as
|
|
42
|
+
nonexistent — a wrong answer rather than an error, which is the worse
|
|
43
|
+
failure mode. An explicit RESOLVE_SCRIPT_API wins over the platform
|
|
44
|
+
default, same as everywhere else in this server.
|
|
45
|
+
|
|
46
|
+
Best effort: a broken or absent install must not take down the query path,
|
|
47
|
+
and the shipped copy still works without one.
|
|
48
|
+
"""
|
|
49
|
+
try:
|
|
50
|
+
from .platform import get_resolve_paths
|
|
51
|
+
|
|
52
|
+
api_path = (get_resolve_paths() or {}).get("api_path")
|
|
53
|
+
if api_path:
|
|
54
|
+
candidate = os.path.join(api_path, "DaVinciResolveScript.pyi")
|
|
55
|
+
if os.path.isfile(candidate):
|
|
56
|
+
return candidate
|
|
57
|
+
except Exception:
|
|
58
|
+
return None
|
|
59
|
+
return None
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def stub_path(project_dir: str, source: str = "auto") -> Optional[str]:
|
|
63
|
+
"""Resolve which stub to read.
|
|
64
|
+
|
|
65
|
+
`auto` prefers the installed build's stub and falls back to the shipped
|
|
66
|
+
copy. `shipped` forces the pinned file — the inventory tests use it,
|
|
67
|
+
because they assert the 21.1 revision and would otherwise flip their
|
|
68
|
+
expected counts on any machine with a newer Resolve installed. `installed`
|
|
69
|
+
refuses instead of silently falling back, for callers that specifically
|
|
70
|
+
want the live build's inventory.
|
|
71
|
+
|
|
72
|
+
Returns None when the requested stub is not there; `load` turns that into
|
|
73
|
+
one error message naming both locations.
|
|
74
|
+
"""
|
|
75
|
+
if source not in STUB_SOURCES:
|
|
76
|
+
raise TypedApiError(
|
|
77
|
+
f"source must be one of {', '.join(STUB_SOURCES)}, not {source!r}"
|
|
78
|
+
)
|
|
79
|
+
if source in ("auto", "installed"):
|
|
80
|
+
installed = installed_stub_path()
|
|
81
|
+
if installed:
|
|
82
|
+
return installed
|
|
83
|
+
if source == "installed":
|
|
84
|
+
raise TypedApiError(
|
|
85
|
+
"No installed Resolve typed stub found. Resolve writes "
|
|
86
|
+
"DaVinciResolveScript.pyi next to its scripting API; set "
|
|
87
|
+
"RESOLVE_SCRIPT_API to that Scripting directory if this install "
|
|
88
|
+
"keeps it elsewhere."
|
|
89
|
+
)
|
|
90
|
+
shipped = os.path.join(project_dir, STUB_RELATIVE)
|
|
91
|
+
return shipped if os.path.isfile(shipped) else None
|
|
36
92
|
|
|
37
93
|
|
|
38
94
|
@lru_cache(maxsize=4)
|
|
@@ -78,14 +134,29 @@ def _inventory(path: str, mtime: float) -> Dict[str, Any]:
|
|
|
78
134
|
return {"methods": methods, "option_types": option_types}
|
|
79
135
|
|
|
80
136
|
|
|
81
|
-
def load(project_dir: str) -> Dict[str, Any]:
|
|
82
|
-
|
|
83
|
-
|
|
137
|
+
def load(project_dir: str, source: str = "auto") -> Dict[str, Any]:
|
|
138
|
+
"""Parse the stub, and say which copy answered.
|
|
139
|
+
|
|
140
|
+
`stub` and `stub_source` are added to the parsed inventory so every caller
|
|
141
|
+
can report them. The parsed inventory itself is cached and shared, so this
|
|
142
|
+
returns a copy rather than mutating it.
|
|
143
|
+
"""
|
|
144
|
+
path = stub_path(project_dir, source)
|
|
145
|
+
if path is None:
|
|
146
|
+
shipped = os.path.join(project_dir, STUB_RELATIVE)
|
|
84
147
|
raise TypedApiError(
|
|
85
|
-
|
|
86
|
-
"
|
|
148
|
+
"Typed API stub not found. Checked the installed Resolve stub "
|
|
149
|
+
"(none found) and the shipped copy at "
|
|
150
|
+
f"{shipped}. Run from a source checkout with the shipped stub, "
|
|
151
|
+
"install Resolve so its own stub exists, or set RESOLVE_SCRIPT_API "
|
|
152
|
+
"to the Scripting directory."
|
|
87
153
|
)
|
|
88
|
-
|
|
154
|
+
inventory = _inventory(path, os.path.getmtime(path))
|
|
155
|
+
return {
|
|
156
|
+
**inventory,
|
|
157
|
+
"stub": path,
|
|
158
|
+
"stub_source": "installed" if path == installed_stub_path() else "shipped",
|
|
159
|
+
}
|
|
89
160
|
|
|
90
161
|
|
|
91
162
|
@lru_cache(maxsize=4)
|
|
@@ -139,7 +210,7 @@ def _source_fingerprint(project_dir: str) -> str:
|
|
|
139
210
|
|
|
140
211
|
|
|
141
212
|
def search(project_dir: str, pattern: str, *, kind: str = "all",
|
|
142
|
-
limit: int = 50) -> Dict[str, Any]:
|
|
213
|
+
limit: int = 50, source: str = "auto") -> Dict[str, Any]:
|
|
143
214
|
"""Case-insensitive regex over method names, signatures, types and docs."""
|
|
144
215
|
if not isinstance(pattern, str) or not pattern.strip():
|
|
145
216
|
raise TypedApiError("pattern is required")
|
|
@@ -154,7 +225,7 @@ def search(project_dir: str, pattern: str, *, kind: str = "all",
|
|
|
154
225
|
except (TypeError, ValueError):
|
|
155
226
|
raise TypedApiError("limit must be an integer")
|
|
156
227
|
|
|
157
|
-
inventory = load(project_dir)
|
|
228
|
+
inventory = load(project_dir, source)
|
|
158
229
|
wrapped = _wrapped_names(project_dir, _source_fingerprint(project_dir))
|
|
159
230
|
|
|
160
231
|
methods: List[Dict[str, Any]] = []
|
|
@@ -199,23 +270,25 @@ def search(project_dir: str, pattern: str, *, kind: str = "all",
|
|
|
199
270
|
"truncated": total > limit,
|
|
200
271
|
"methods": methods[:limit],
|
|
201
272
|
"option_types": options[:limit],
|
|
202
|
-
"stub":
|
|
273
|
+
"stub": inventory["stub"],
|
|
274
|
+
"stub_source": inventory["stub_source"],
|
|
203
275
|
"note": ("referenced_in_this_server is executable syntax only — a name that "
|
|
204
276
|
"appears solely in a docstring or comment is not counted."),
|
|
205
277
|
}
|
|
206
278
|
|
|
207
279
|
|
|
208
|
-
def describe(project_dir: str, symbol: str) -> Dict[str, Any]:
|
|
280
|
+
def describe(project_dir: str, symbol: str, source: str = "auto") -> Dict[str, Any]:
|
|
209
281
|
"""Full detail for one `Class.Method` or one TypedDict name."""
|
|
210
282
|
if not isinstance(symbol, str) or not symbol.strip():
|
|
211
283
|
raise TypedApiError("symbol is required")
|
|
212
|
-
inventory = load(project_dir)
|
|
284
|
+
inventory = load(project_dir, source)
|
|
213
285
|
key = symbol.strip()
|
|
214
286
|
|
|
215
287
|
if key in inventory["option_types"]:
|
|
216
288
|
fields = inventory["option_types"][key]
|
|
217
289
|
return {"symbol": key, "kind": "option_type", "field_count": len(fields),
|
|
218
|
-
"fields": fields, "stub":
|
|
290
|
+
"fields": fields, "stub": inventory["stub"],
|
|
291
|
+
"stub_source": inventory["stub_source"]}
|
|
219
292
|
|
|
220
293
|
row = inventory["methods"].get(key)
|
|
221
294
|
if row is None:
|
|
@@ -229,8 +302,10 @@ def describe(project_dir: str, symbol: str) -> Dict[str, Any]:
|
|
|
229
302
|
)
|
|
230
303
|
else:
|
|
231
304
|
raise TypedApiError(
|
|
232
|
-
f"{symbol!r} is not in the
|
|
233
|
-
"find the right name
|
|
305
|
+
f"{symbol!r} is not in the typed stub that answered ({inventory['stub']}, "
|
|
306
|
+
f"source={inventory['stub_source']}). Use search to find the right name; "
|
|
307
|
+
"pass source='installed' to read the running build's inventory instead "
|
|
308
|
+
"of the shipped copy."
|
|
234
309
|
)
|
|
235
310
|
|
|
236
311
|
wrapped = _wrapped_names(project_dir, _source_fingerprint(project_dir))
|
|
@@ -244,15 +319,17 @@ def describe(project_dir: str, symbol: str) -> Dict[str, Any]:
|
|
|
244
319
|
"description": row["description"],
|
|
245
320
|
"referenced_in_this_server": bool(references),
|
|
246
321
|
"source_files": references,
|
|
247
|
-
"stub":
|
|
322
|
+
"stub": inventory["stub"],
|
|
323
|
+
"stub_source": inventory["stub_source"],
|
|
248
324
|
}
|
|
249
325
|
|
|
250
326
|
|
|
251
|
-
def summary(project_dir: str) -> Dict[str, Any]:
|
|
252
|
-
inventory = load(project_dir)
|
|
327
|
+
def summary(project_dir: str, source: str = "auto") -> Dict[str, Any]:
|
|
328
|
+
inventory = load(project_dir, source)
|
|
253
329
|
field_total = sum(len(fields) for fields in inventory["option_types"].values())
|
|
254
330
|
return {
|
|
255
|
-
"stub":
|
|
331
|
+
"stub": inventory["stub"],
|
|
332
|
+
"stub_source": inventory["stub_source"],
|
|
256
333
|
"methods": len(inventory["methods"]),
|
|
257
334
|
"option_types": len(inventory["option_types"]),
|
|
258
335
|
"option_fields": field_total,
|