Welcome to mirror list, hosted at ThFree Co, Russian Federation.

blendfile_path_remap.py « blend « bam « blender_bam-1.1.7-py3-none-any.whl « io_blend_utils - git.blender.org/blender-addons.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 3b792c3a6bbbd6cea657d1552dd8577f938097f5 (plain)
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
#!/usr/bin/env python3

# ***** BEGIN GPL LICENSE BLOCK *****
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
# ***** END GPL LICENCE BLOCK *****

"""
Module for remapping paths from one directory to another.
"""

import os


# ----------------------------------------------------------------------------
# private utility functions

def _is_blend(f):
    return f.lower().endswith(b'.blend')


def _warn__ascii(msg):
    print("  warning: %s" % msg)


def _info__ascii(msg):
    print(msg)


def _warn__json(msg):
    import json
    print(json.dumps(("warning", msg)), end=",\n")

def _info__json(msg):
    import json
    print(json.dumps(("info", msg)), end=",\n")


def _uuid_from_file(fn, block_size=1 << 20):
    with open(fn, 'rb') as f:
        # first get the size
        f.seek(0, os.SEEK_END)
        size = f.tell()
        f.seek(0, os.SEEK_SET)
        # done!

        import hashlib
        sha1 = hashlib.new('sha512')
        while True:
            data = f.read(block_size)
            if not data:
                break
            sha1.update(data)
        return (hex(size)[2:] + sha1.hexdigest()).encode()


def _iter_files(paths, check_ext=None):
    # note, sorting isn't needed
    # just gives predictable output
    for p in paths:
        p = os.path.abspath(p)
        for dirpath, dirnames, filenames in sorted(os.walk(p)):
            # skip '.svn'
            if dirpath.startswith(b'.') and dirpath != b'.':
                continue

            for filename in sorted(filenames):
                if check_ext is None or check_ext(filename):
                    filepath = os.path.join(dirpath, filename)
                    yield filepath


# ----------------------------------------------------------------------------
# Public Functions

def start(
        paths,
        is_quiet=False,
        dry_run=False,
        use_json=False,
        ):

    if use_json:
        warn = _warn__json
        info = _info__json
    else:
        warn = _warn__ascii
        info = _info__ascii

    if use_json:
        print("[")

    # {(sha1, length): "filepath"}
    remap_uuid = {}

    # relative paths which don't exist,
    # don't complain when they're missing on remap.
    # {f_src: [relative path deps, ...]}
    remap_lost = {}

    # all files we need to map
    # absolute paths
    files_to_map = set()

    # TODO, validate paths aren't nested! ["/foo", "/foo/bar"]
    # it will cause problems touching files twice!

    # ------------------------------------------------------------------------
    # First walk over all blends
    from bam.blend import blendfile_path_walker

    for blendfile_src in _iter_files(paths, check_ext=_is_blend):
        if not is_quiet:
            info("blend read: %r" % blendfile_src)

        remap_lost[blendfile_src] = remap_lost_blendfile_src = set()

        for fp, (rootdir, fp_blend_basename) in blendfile_path_walker.FilePath.visit_from_blend(
                blendfile_src,
                readonly=True,
                recursive=False,
                ):
            # TODO. warn when referencing files outside 'paths'

            # so we can update the reference
            f_abs = fp.filepath_absolute
            f_abs = os.path.normpath(f_abs)
            if os.path.exists(f_abs):
                files_to_map.add(f_abs)
            else:
                if not is_quiet:
                    warn("file %r not found!" % f_abs)

                # don't complain about this file being missing on remap
                remap_lost_blendfile_src.add(fp.filepath)

        # so we can know where its moved to
        files_to_map.add(blendfile_src)
    del blendfile_path_walker

    # ------------------------------------------------------------------------
    # Store UUID
    #
    # note, sorting is only to give predictable warnings/behavior
    for f in sorted(files_to_map):
        f_uuid = _uuid_from_file(f)

        f_match = remap_uuid.get(f_uuid)
        if f_match is not None:
            if not is_quiet:
                warn("duplicate file found! (%r, %r)" % (f_match, f))

        remap_uuid[f_uuid] = f

    # now find all deps
    remap_data_args = (
            remap_uuid,
            remap_lost,
            )

    if use_json:
        if not remap_uuid:
            print("\"nothing to remap!\"")
        else:
            print("\"complete\"")
        print("]")
    else:
        if not remap_uuid:
            print("Nothing to remap!")

    return remap_data_args


def finish(
        paths, remap_data_args,
        is_quiet=False,
        force_relative=False,
        dry_run=False,
        use_json=False,
        ):

    if use_json:
        warn = _warn__json
        info = _info__json
    else:
        warn = _warn__ascii
        info = _info__ascii

    if use_json:
        print("[")

    (remap_uuid,
     remap_lost,
     ) = remap_data_args

    remap_src_to_dst = {}
    remap_dst_to_src = {}

    for f_dst in _iter_files(paths):
        f_uuid = _uuid_from_file(f_dst)
        f_src = remap_uuid.get(f_uuid)
        if f_src is not None:
            remap_src_to_dst[f_src] = f_dst
            remap_dst_to_src[f_dst] = f_src

    # now the fun begins, remap _all_ paths
    from bam.blend import blendfile_path_walker

    for blendfile_dst in _iter_files(paths, check_ext=_is_blend):
        blendfile_src = remap_dst_to_src.get(blendfile_dst)
        if blendfile_src is None:
            if not is_quiet:
                warn("new blendfile added since beginning 'remap': %r" % blendfile_dst)
            continue

        # not essential, just so we can give more meaningful errors
        remap_lost_blendfile_src = remap_lost[blendfile_src]

        if not is_quiet:
            info("blend write: %r -> %r" % (blendfile_src, blendfile_dst))

        blendfile_src_basedir = os.path.dirname(blendfile_src)
        blendfile_dst_basedir = os.path.dirname(blendfile_dst)
        for fp, (rootdir, fp_blend_basename) in blendfile_path_walker.FilePath.visit_from_blend(
                blendfile_dst,
                readonly=False,
                recursive=False,
                ):
            # TODO. warn when referencing files outside 'paths'

            # so we can update the reference
            f_src_orig = fp.filepath

            if f_src_orig in remap_lost_blendfile_src:
                # this file never existed, so we can't remap it
                continue

            is_relative = f_src_orig.startswith(b'//')
            if is_relative:
                f_src_abs = fp.filepath_absolute_resolve(basedir=blendfile_src_basedir)
            else:
                f_src_abs = f_src_orig

            f_src_abs = os.path.normpath(f_src_abs)
            f_dst_abs = remap_src_to_dst.get(f_src_abs)

            if f_dst_abs is None:
                if not is_quiet:
                    warn("file %r not found in map!" % f_src_abs)
                continue

            # now remap!
            if is_relative or force_relative:
                f_dst_final = b'//' + os.path.relpath(f_dst_abs, blendfile_dst_basedir)
            else:
                f_dst_final = f_dst_abs

            if f_dst_final != f_src_orig:
                if not dry_run:
                    fp.filepath = f_dst_final
                if not is_quiet:
                    info("remap %r -> %r" % (f_src_abs, f_dst_abs))

    del blendfile_path_walker

    if use_json:
        print("\"complete\"\n]")