[Notes] [Git][BuildStream/buildstream][jonathan/pickle-yaml] 5 commits: source.py: Fix re-instantiation



Title: GitLab

Jonathan Maw pushed to branch jonathan/pickle-yaml at BuildStream / buildstream

Commits:

7 changed files:

Changes:

  • buildstream/_loader/loadelement.py
    ... ... @@ -185,6 +185,6 @@ def _extract_depends_from_node(node, *, key=None):
    185 185
             output_deps.append(dependency)
    
    186 186
     
    
    187 187
         # Now delete the field, we dont want it anymore
    
    188
    -    del node[key]
    
    188
    +    node.pop(key, None)
    
    189 189
     
    
    190 190
         return output_deps

  • buildstream/_loader/loader.py
    ... ... @@ -30,6 +30,7 @@ from ..element import Element
    30 30
     from .._profile import Topics, profile_start, profile_end
    
    31 31
     from .._platform import Platform
    
    32 32
     from .._includes import Includes
    
    33
    +from .._yamlcache import YamlCache
    
    33 34
     
    
    34 35
     from .types import Symbol, Dependency
    
    35 36
     from .loadelement import LoadElement
    
    ... ... @@ -113,7 +114,8 @@ class Loader():
    113 114
                 profile_start(Topics.LOAD_PROJECT, target)
    
    114 115
                 junction, name, loader = self._parse_name(target, rewritable, ticker,
    
    115 116
                                                           fetch_subprojects=fetch_subprojects)
    
    116
    -            loader._load_file(name, rewritable, ticker, fetch_subprojects)
    
    117
    +            with YamlCache.open(self._context) as yaml_cache:
    
    118
    +                loader._load_file(name, rewritable, ticker, fetch_subprojects, yaml_cache)
    
    117 119
                 deps.append(Dependency(name, junction=junction))
    
    118 120
                 profile_end(Topics.LOAD_PROJECT, target)
    
    119 121
     
    
    ... ... @@ -202,11 +204,12 @@ class Loader():
    202 204
         #    rewritable (bool): Whether we should load in round trippable mode
    
    203 205
         #    ticker (callable): A callback to report loaded filenames to the frontend
    
    204 206
         #    fetch_subprojects (bool): Whether to fetch subprojects while loading
    
    207
    +    #    yaml_cache (YamlCache): A yaml cache
    
    205 208
         #
    
    206 209
         # Returns:
    
    207 210
         #    (LoadElement): A loaded LoadElement
    
    208 211
         #
    
    209
    -    def _load_file(self, filename, rewritable, ticker, fetch_subprojects):
    
    212
    +    def _load_file(self, filename, rewritable, ticker, fetch_subprojects, yaml_cache=None):
    
    210 213
     
    
    211 214
             # Silently ignore already loaded files
    
    212 215
             if filename in self._elements:
    
    ... ... @@ -219,7 +222,8 @@ class Loader():
    219 222
             # Load the data and process any conditional statements therein
    
    220 223
             fullpath = os.path.join(self._basedir, filename)
    
    221 224
             try:
    
    222
    -            node = _yaml.load(fullpath, shortname=filename, copy_tree=rewritable, project=self.project)
    
    225
    +            node = _yaml.load(fullpath, shortname=filename, copy_tree=rewritable,
    
    226
    +                              project=self.project, yaml_cache=yaml_cache)
    
    223 227
             except LoadError as e:
    
    224 228
                 if e.reason == LoadErrorReason.MISSING_FILE:
    
    225 229
                     # If we can't find the file, try to suggest plausible
    
    ... ... @@ -262,13 +266,13 @@ class Loader():
    262 266
             # Load all dependency files for the new LoadElement
    
    263 267
             for dep in element.deps:
    
    264 268
                 if dep.junction:
    
    265
    -                self._load_file(dep.junction, rewritable, ticker, fetch_subprojects)
    
    269
    +                self._load_file(dep.junction, rewritable, ticker, fetch_subprojects, yaml_cache)
    
    266 270
                     loader = self._get_loader(dep.junction, rewritable=rewritable, ticker=ticker,
    
    267 271
                                               fetch_subprojects=fetch_subprojects)
    
    268 272
                 else:
    
    269 273
                     loader = self
    
    270 274
     
    
    271
    -            dep_element = loader._load_file(dep.name, rewritable, ticker, fetch_subprojects)
    
    275
    +            dep_element = loader._load_file(dep.name, rewritable, ticker, fetch_subprojects, yaml_cache)
    
    272 276
     
    
    273 277
                 if _yaml.node_get(dep_element.node, str, Symbol.KIND) == 'junction':
    
    274 278
                     raise LoadError(LoadErrorReason.INVALID_DATA,
    

  • buildstream/_project.py
    ... ... @@ -19,6 +19,7 @@
    19 19
     #        Tiago Gomes <tiago gomes codethink co uk>
    
    20 20
     
    
    21 21
     import os
    
    22
    +import hashlib
    
    22 23
     from collections import Mapping, OrderedDict
    
    23 24
     from pluginbase import PluginBase
    
    24 25
     from . import utils
    

  • buildstream/_yaml.py
    ... ... @@ -183,20 +183,35 @@ class CompositeTypeError(CompositeError):
    183 183
     #    shortname (str): The filename in shorthand for error reporting (or None)
    
    184 184
     #    copy_tree (bool): Whether to make a copy, preserving the original toplevels
    
    185 185
     #                      for later serialization
    
    186
    +#    yaml_cache (YamlCache): A yaml cache to consult rather than parsing
    
    186 187
     #
    
    187 188
     # Returns (dict): A loaded copy of the YAML file with provenance information
    
    188 189
     #
    
    189 190
     # Raises: LoadError
    
    190 191
     #
    
    191
    -def load(filename, shortname=None, copy_tree=False, *, project=None):
    
    192
    +def load(filename, shortname=None, copy_tree=False, *, project=None, yaml_cache=None):
    
    192 193
         if not shortname:
    
    193 194
             shortname = filename
    
    194 195
     
    
    195 196
         file = ProvenanceFile(filename, shortname, project)
    
    196 197
     
    
    197 198
         try:
    
    199
    +        data = None
    
    198 200
             with open(filename) as f:
    
    199
    -            return load_data(f, file, copy_tree=copy_tree)
    
    201
    +            contents = f.read()
    
    202
    +        if yaml_cache:
    
    203
    +            assert project
    
    204
    +            key = yaml_cache.calculate_key(contents, copy_tree)
    
    205
    +            data = yaml_cache.get(project, filename, key)
    
    206
    +
    
    207
    +        if not data:
    
    208
    +            data = load_data(contents, file, copy_tree=copy_tree)
    
    209
    +
    
    210
    +        if yaml_cache:
    
    211
    +            assert project
    
    212
    +            yaml_cache.put(project, filename, key, data)
    
    213
    +
    
    214
    +        return data
    
    200 215
         except FileNotFoundError as e:
    
    201 216
             raise LoadError(LoadErrorReason.MISSING_FILE,
    
    202 217
                             "Could not find file at {}".format(filename)) from e
    

  • buildstream/_yamlcache.py
    1
    +#
    
    2
    +#  Copyright 2018 Bloomberg Finance LP
    
    3
    +#
    
    4
    +#  This program is free software; you can redistribute it and/or
    
    5
    +#  modify it under the terms of the GNU Lesser General Public
    
    6
    +#  License as published by the Free Software Foundation; either
    
    7
    +#  version 2 of the License, or (at your option) any later version.
    
    8
    +#
    
    9
    +#  This library is distributed in the hope that it will be useful,
    
    10
    +#  but WITHOUT ANY WARRANTY; without even the implied warranty of
    
    11
    +#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    
    12
    +#  Lesser General Public License for more details.
    
    13
    +#
    
    14
    +#  You should have received a copy of the GNU Lesser General Public
    
    15
    +#  License along with this library. If not, see <http://www.gnu.org/licenses/>.
    
    16
    +#
    
    17
    +#  Authors:
    
    18
    +#        Jonathan Maw <jonathan maw codethink co uk>
    
    19
    +
    
    20
    +import os
    
    21
    +import pickle
    
    22
    +import hashlib
    
    23
    +import io
    
    24
    +
    
    25
    +import sys
    
    26
    +
    
    27
    +from contextlib import contextmanager
    
    28
    +from collections import namedtuple
    
    29
    +
    
    30
    +from ._cachekey import generate_key
    
    31
    +from ._context import Context
    
    32
    +from . import utils, _yaml
    
    33
    +
    
    34
    +
    
    35
    +YAML_CACHE_FILENAME = "yaml_cache.pickle"
    
    36
    +
    
    37
    +
    
    38
    +# YamlCache()
    
    39
    +#
    
    40
    +# A cache that wraps around the loading of yaml in projects.
    
    41
    +#
    
    42
    +# The recommended way to use a YamlCache is:
    
    43
    +#   with YamlCache.open(context) as yamlcache:
    
    44
    +#     # Load all the yaml
    
    45
    +#     ...
    
    46
    +#
    
    47
    +# Args:
    
    48
    +#    context (Context): The invocation Context
    
    49
    +#
    
    50
    +class YamlCache():
    
    51
    +
    
    52
    +    def __init__(self, context):
    
    53
    +        self._project_caches = {}
    
    54
    +        self._context = context
    
    55
    +
    
    56
    +    # Writes the yaml cache to the specified path.
    
    57
    +    def write(self):
    
    58
    +        path = self._get_cache_file(self._context)
    
    59
    +        parent_dir = os.path.dirname(path)
    
    60
    +        os.makedirs(parent_dir, exist_ok=True)
    
    61
    +        with open(path, "wb") as f:
    
    62
    +            BstPickler(f).dump(self)
    
    63
    +
    
    64
    +    # Gets a parsed file from the cache.
    
    65
    +    #
    
    66
    +    # Args:
    
    67
    +    #    project (Project): The project this file is in.
    
    68
    +    #    filepath (str): The path to the file.
    
    69
    +    #    key (str): The key to the file within the cache. Typically, this is the
    
    70
    +    #               value of `calculate_key()` with the file's unparsed contents
    
    71
    +    #               and any relevant metadata passed in.
    
    72
    +    #
    
    73
    +    # Returns:
    
    74
    +    #    (decorated dict): The parsed yaml from the cache, or None if the file isn't in the cache.
    
    75
    +    def get(self, project, filepath, key):
    
    76
    +        cache_path = self._get_filepath(project, filepath)
    
    77
    +        project_name = project.name if project else ""
    
    78
    +        try:
    
    79
    +            project_cache = self._project_caches[project_name]
    
    80
    +            try:
    
    81
    +                cachedyaml = project_cache.elements[cache_path]
    
    82
    +                if cachedyaml._key == key:
    
    83
    +                    # We've unpickled the YamlCache, but not the specific file
    
    84
    +                    if cachedyaml._contents is None:
    
    85
    +                        cachedyaml._contents = BstUnpickler.loads(cachedyaml._pickled_contents, self._context)
    
    86
    +                    return cachedyaml._contents
    
    87
    +            except KeyError:
    
    88
    +                pass
    
    89
    +        except KeyError:
    
    90
    +            pass
    
    91
    +        return None
    
    92
    +
    
    93
    +    # Put a parsed file into the cache.
    
    94
    +    #
    
    95
    +    # Args:
    
    96
    +    #    project (Project): The project this file is in.
    
    97
    +    #    filepath (str): The path to the file.
    
    98
    +    #    key (str): The key to the file within the cache. Typically, this is the
    
    99
    +    #               value of `calculate_key()` with the file's unparsed contents
    
    100
    +    #               and any relevant metadata passed in.
    
    101
    +    #    value (decorated dict): The data to put into the cache.
    
    102
    +    def put(self, project, filepath, key, value):
    
    103
    +        cache_path = self._get_filepath(project, filepath)
    
    104
    +        project_name = project.name if project else ""
    
    105
    +        try:
    
    106
    +            project_cache = self._project_caches[project_name]
    
    107
    +        except KeyError:
    
    108
    +            project_cache = self._project_caches[project_name] = CachedProject({})
    
    109
    +
    
    110
    +        project_cache.elements[cache_path] = CachedYaml(key, value)
    
    111
    +
    
    112
    +    # Checks whether a file is cached
    
    113
    +    # Args:
    
    114
    +    #    project (Project): The project this file is in.
    
    115
    +    #    filepath (str): The path to the file, *relative to the project's directory*.
    
    116
    +    #
    
    117
    +    # Returns:
    
    118
    +    #    (bool): Whether the file is cached
    
    119
    +    def is_cached(self, project, filepath):
    
    120
    +        cache_path = self._get_filepath(project, filepath)
    
    121
    +        project_name = project.name if project else ""
    
    122
    +        try:
    
    123
    +            project_cache = self._project_caches[project_name]
    
    124
    +            if cache_path in project_cache.elements:
    
    125
    +                return True
    
    126
    +        except KeyError:
    
    127
    +            pass
    
    128
    +        return False
    
    129
    +
    
    130
    +    def _get_filepath(self, project, full_path):
    
    131
    +        if project:
    
    132
    +            assert full_path.startswith(project.directory)
    
    133
    +            filepath = os.path.relpath(full_path, project.directory)
    
    134
    +        else:
    
    135
    +            filepath = full_path
    
    136
    +        return full_path
    
    137
    +
    
    138
    +    # Return an instance of the YamlCache which writes to disk when it leaves scope.
    
    139
    +    #
    
    140
    +    # Args:
    
    141
    +    #    context (Context): The context.
    
    142
    +    #
    
    143
    +    # Returns:
    
    144
    +    #    (YamlCache): A YamlCache.
    
    145
    +    @staticmethod
    
    146
    +    @contextmanager
    
    147
    +    def open(context):
    
    148
    +        # Try to load from disk first
    
    149
    +        cachefile = YamlCache._get_cache_file(context)
    
    150
    +        cache = None
    
    151
    +        if os.path.exists(cachefile):
    
    152
    +            try:
    
    153
    +                with open(cachefile, "rb") as f:
    
    154
    +                    cache = BstUnpickler(f, context).load()
    
    155
    +            except pickle.UnpicklingError as e:
    
    156
    +                sys.stderr.write("Failed to load YamlCache, {}\n".format(e))
    
    157
    +
    
    158
    +        if not cache:
    
    159
    +            cache = YamlCache(context)
    
    160
    +
    
    161
    +        yield cache
    
    162
    +
    
    163
    +        cache.write()
    
    164
    +
    
    165
    +    # Calculates a key for putting into the cache.
    
    166
    +    @staticmethod
    
    167
    +    def calculate_key(*args):
    
    168
    +        string = pickle.dumps(args)
    
    169
    +        return hashlib.sha1(string).hexdigest()
    
    170
    +
    
    171
    +    # Retrieves a path to the yaml cache file.
    
    172
    +    @staticmethod
    
    173
    +    def _get_cache_file(context):
    
    174
    +        toplevel_project = context.get_toplevel_project()
    
    175
    +        return os.path.join(toplevel_project.directory, ".bst", YAML_CACHE_FILENAME)
    
    176
    +
    
    177
    +
    
    178
    +CachedProject = namedtuple('CachedProject', ['elements'])
    
    179
    +
    
    180
    +
    
    181
    +class CachedYaml():
    
    182
    +    def __init__(self, key, contents):
    
    183
    +        self._key = key
    
    184
    +        self.set_contents(contents)
    
    185
    +
    
    186
    +    # Sets the contents of the CachedYaml.
    
    187
    +    #
    
    188
    +    # Args:
    
    189
    +    #    contents (provenanced dict): The contents to put in the cache.
    
    190
    +    #
    
    191
    +    def set_contents(self, contents):
    
    192
    +        self._contents = contents
    
    193
    +        self._pickled_contents = BstPickler.dumps(contents)
    
    194
    +
    
    195
    +    # Pickling helper method, prevents 'contents' from being serialised
    
    196
    +    def __getstate__(self):
    
    197
    +        data = self.__dict__.copy()
    
    198
    +        data['_contents'] = None
    
    199
    +        return data
    
    200
    +
    
    201
    +
    
    202
    +# In _yaml.load, we have a ProvenanceFile that stores the project the file
    
    203
    +# came from. Projects can't be pickled, but it's always going to be the same
    
    204
    +# project between invocations (unless the entire project is moved but the
    
    205
    +# file stayed in the same place)
    
    206
    +class BstPickler(pickle.Pickler):
    
    207
    +    def persistent_id(self, obj):
    
    208
    +        if isinstance(obj, _yaml.ProvenanceFile):
    
    209
    +            if obj.project:
    
    210
    +                # ProvenanceFile's project object cannot be stored as it is.
    
    211
    +                project_tag = obj.project.name
    
    212
    +                # ProvenanceFile's filename must be stored relative to the
    
    213
    +                # project, as the project dir may move.
    
    214
    +                name = os.path.relpath(obj.name, obj.project.directory)
    
    215
    +            else:
    
    216
    +                project_tag = None
    
    217
    +                name = obj.name
    
    218
    +            return ("ProvenanceFile", name, obj.shortname, project_tag)
    
    219
    +        elif isinstance(obj, Context):
    
    220
    +            return ("Context",)
    
    221
    +        else:
    
    222
    +            return None
    
    223
    +
    
    224
    +    @staticmethod
    
    225
    +    def dumps(obj):
    
    226
    +        stream = io.BytesIO()
    
    227
    +        BstPickler(stream).dump(obj)
    
    228
    +        stream.seek(0)
    
    229
    +        return stream.read()
    
    230
    +
    
    231
    +
    
    232
    +class BstUnpickler(pickle.Unpickler):
    
    233
    +    def __init__(self, file, context):
    
    234
    +        super().__init__(file)
    
    235
    +        self._context = context
    
    236
    +
    
    237
    +    def persistent_load(self, pid):
    
    238
    +        if pid[0] == "ProvenanceFile":
    
    239
    +            _, tagged_name, shortname, project_tag = pid
    
    240
    +
    
    241
    +            if project_tag is not None:
    
    242
    +                for p in self._context.get_projects():
    
    243
    +                    if project_tag == p.name:
    
    244
    +                        project = p
    
    245
    +                        break
    
    246
    +
    
    247
    +                name = os.path.join(project.directory, tagged_name)
    
    248
    +
    
    249
    +                if not project:
    
    250
    +                    projects = [p.name for p in self._context.get_projects()]
    
    251
    +                    raise pickle.UnpicklingError("No project with name {} found in {}"
    
    252
    +                                                 .format(key_id, projects))
    
    253
    +            else:
    
    254
    +                project = None
    
    255
    +                name = tagged_name
    
    256
    +
    
    257
    +            return _yaml.ProvenanceFile(name, shortname, project)
    
    258
    +        elif pid[0] == "Context":
    
    259
    +            return self._context
    
    260
    +        else:
    
    261
    +            raise pickle.UnpicklingError("Unsupported persistent object, {}".format(pid))
    
    262
    +
    
    263
    +    @staticmethod
    
    264
    +    def loads(text, context):
    
    265
    +        stream = io.BytesIO()
    
    266
    +        stream.write(bytes(text))
    
    267
    +        stream.seek(0)
    
    268
    +        return BstUnpickler(stream, context).load()

  • buildstream/source.py
    ... ... @@ -930,6 +930,38 @@ class Source(Plugin):
    930 930
         #                   Local Private Methods                   #
    
    931 931
         #############################################################
    
    932 932
     
    
    933
    +    # __clone_for_uri()
    
    934
    +    #
    
    935
    +    # Clone the source with an alternative URI setup for the alias
    
    936
    +    # which this source uses.
    
    937
    +    #
    
    938
    +    # This is used for iteration over source mirrors.
    
    939
    +    #
    
    940
    +    # Args:
    
    941
    +    #    uri (str): The alternative URI for this source's alias
    
    942
    +    #
    
    943
    +    # Returns:
    
    944
    +    #    (Source): A new clone of this Source, with the specified URI
    
    945
    +    #              as the value of the alias this Source has marked as
    
    946
    +    #              primary with either mark_download_url() or
    
    947
    +    #              translate_url().
    
    948
    +    #
    
    949
    +    def __clone_for_uri(self, uri):
    
    950
    +        project = self._get_project()
    
    951
    +        context = self._get_context()
    
    952
    +        alias = self._get_alias()
    
    953
    +        source_kind = type(self)
    
    954
    +
    
    955
    +        clone = source_kind(context, project, self.__meta, alias_override=(alias, uri))
    
    956
    +
    
    957
    +        # Do the necessary post instantiation routines here
    
    958
    +        #
    
    959
    +        clone._preflight()
    
    960
    +        clone._load_ref()
    
    961
    +        clone._update_state()
    
    962
    +
    
    963
    +        return clone
    
    964
    +
    
    933 965
         # Tries to call fetch for every mirror, stopping once it succeeds
    
    934 966
         def __do_fetch(self, **kwargs):
    
    935 967
             project = self._get_project()
    
    ... ... @@ -968,12 +1000,8 @@ class Source(Plugin):
    968 1000
                     self.fetch(**kwargs)
    
    969 1001
                     return
    
    970 1002
     
    
    971
    -            context = self._get_context()
    
    972
    -            source_kind = type(self)
    
    973 1003
                 for uri in project.get_alias_uris(alias, first_pass=self.__first_pass):
    
    974
    -                new_source = source_kind(context, project, self.__meta,
    
    975
    -                                         alias_override=(alias, uri))
    
    976
    -                new_source._preflight()
    
    1004
    +                new_source = self.__clone_for_uri(uri)
    
    977 1005
                     try:
    
    978 1006
                         new_source.fetch(**kwargs)
    
    979 1007
                     # FIXME: Need to consider temporary vs. permanent failures,
    
    ... ... @@ -1006,9 +1034,7 @@ class Source(Plugin):
    1006 1034
             # NOTE: We are assuming here that tracking only requires substituting the
    
    1007 1035
             #       first alias used
    
    1008 1036
             for uri in reversed(project.get_alias_uris(alias, first_pass=self.__first_pass)):
    
    1009
    -            new_source = source_kind(context, project, self.__meta,
    
    1010
    -                                     alias_override=(alias, uri))
    
    1011
    -            new_source._preflight()
    
    1037
    +            new_source = self.__clone_for_uri(uri)
    
    1012 1038
                 try:
    
    1013 1039
                     ref = new_source.track(**kwargs)
    
    1014 1040
                 # FIXME: Need to consider temporary vs. permanent failures,
    

  • tests/frontend/yamlcache.py
    1
    +import os
    
    2
    +import pytest
    
    3
    +import hashlib
    
    4
    +import tempfile
    
    5
    +from ruamel import yaml
    
    6
    +
    
    7
    +from tests.testutils import cli, generate_junction, create_element_size, create_repo
    
    8
    +from buildstream import _yaml
    
    9
    +from buildstream._yamlcache import YamlCache
    
    10
    +from buildstream._project import Project
    
    11
    +from buildstream._context import Context
    
    12
    +from contextlib import contextmanager
    
    13
    +
    
    14
    +
    
    15
    +def generate_project(tmpdir, ref_storage, with_junction, name="test"):
    
    16
    +    if with_junction == 'junction':
    
    17
    +        subproject_dir = generate_project(
    
    18
    +            tmpdir, ref_storage,
    
    19
    +            'no-junction', name='test-subproject'
    
    20
    +        )
    
    21
    +
    
    22
    +    project_dir = os.path.join(tmpdir, name)
    
    23
    +    os.makedirs(project_dir)
    
    24
    +    # project.conf
    
    25
    +    project_conf_path = os.path.join(project_dir, 'project.conf')
    
    26
    +    elements_path = 'elements'
    
    27
    +    project_conf = {
    
    28
    +        'name': name,
    
    29
    +        'element-path': elements_path,
    
    30
    +        'ref-storage': ref_storage,
    
    31
    +    }
    
    32
    +    _yaml.dump(project_conf, project_conf_path)
    
    33
    +
    
    34
    +    # elements
    
    35
    +    if with_junction == 'junction':
    
    36
    +        junction_name = 'junction.bst'
    
    37
    +        junction_dir = os.path.join(project_dir, elements_path)
    
    38
    +        junction_path = os.path.join(project_dir, elements_path, junction_name)
    
    39
    +        os.makedirs(junction_dir)
    
    40
    +        generate_junction(tmpdir, subproject_dir, junction_path)
    
    41
    +        element_depends = [{'junction': junction_name, 'filename': 'test.bst'}]
    
    42
    +    else:
    
    43
    +        element_depends = []
    
    44
    +
    
    45
    +    element_name = 'test.bst'
    
    46
    +    create_element_size(element_name, project_dir, elements_path, element_depends, 1)
    
    47
    +
    
    48
    +    return project_dir
    
    49
    +
    
    50
    +
    
    51
    +@contextmanager
    
    52
    +def with_yamlcache(project_dir):
    
    53
    +    context = Context()
    
    54
    +    project = Project(project_dir, context)
    
    55
    +    with YamlCache.open(context) as yamlcache:
    
    56
    +        yield yamlcache, project
    
    57
    +
    
    58
    +
    
    59
    +def yamlcache_key(yamlcache, in_file, copy_tree=False):
    
    60
    +    with open(in_file) as f:
    
    61
    +        key = yamlcache.calculate_key(f.read(), copy_tree)
    
    62
    +    return key
    
    63
    +
    
    64
    +
    
    65
    +def modified_file(input_file):
    
    66
    +    with open(input_file) as f:
    
    67
    +        data = f.read()
    
    68
    +    assert 'variables' not in data
    
    69
    +    data += '\nvariables: {modified: True}\n'
    
    70
    +    _, temppath = tempfile.mkstemp(text=True)
    
    71
    +    with open(temppath, 'w') as f:
    
    72
    +        f.write(data)
    
    73
    +
    
    74
    +    return temppath
    
    75
    +
    
    76
    +
    
    77
    +@pytest.mark.parametrize('ref_storage', ['inline', 'project.refs'])
    
    78
    +@pytest.mark.parametrize('with_junction', ['no-junction', 'junction'])
    
    79
    +@pytest.mark.parametrize('move_project', ['move', 'no-move'])
    
    80
    +def test_yamlcache_used(cli, tmpdir, ref_storage, with_junction, move_project):
    
    81
    +    # Generate the project
    
    82
    +    project = generate_project(str(tmpdir), ref_storage, with_junction)
    
    83
    +    if with_junction == 'junction':
    
    84
    +        result = cli.run(project=project, args=['fetch', '--track', 'junction.bst'])
    
    85
    +        result.assert_success()
    
    86
    +
    
    87
    +    # bst show to put it in the cache
    
    88
    +    result = cli.run(project=project, args=['show', 'test.bst'])
    
    89
    +    result.assert_success()
    
    90
    +
    
    91
    +    element_path = os.path.join(project, 'elements', 'test.bst')
    
    92
    +    with with_yamlcache(project) as (yc, prj):
    
    93
    +        # Check that it's in the cache
    
    94
    +        assert yc.is_cached(prj, element_path)
    
    95
    +
    
    96
    +        # *Absolutely* horrible cache corruption to check it's being used
    
    97
    +        # Modifying the data from the cache is fraught with danger,
    
    98
    +        # so instead I'll load a modified version of the original file
    
    99
    +        temppath = modified_file(element_path)
    
    100
    +        contents = _yaml.load(temppath, copy_tree=False, project=prj)
    
    101
    +        key = yamlcache_key(yc, element_path)
    
    102
    +        yc.put(prj, element_path, key, contents)
    
    103
    +
    
    104
    +    # Show that a variable has been added
    
    105
    +    result = cli.run(project=project, args=['show', '--format', '%{vars}', 'test.bst'])
    
    106
    +    result.assert_success()
    
    107
    +    data = yaml.safe_load(result.output)
    
    108
    +    assert 'modified' in data
    
    109
    +    assert data['modified'] == 'True'
    
    110
    +
    
    111
    +
    
    112
    +@pytest.mark.parametrize('ref_storage', ['inline', 'project.refs'])
    
    113
    +@pytest.mark.parametrize('with_junction', ['junction', 'no-junction'])
    
    114
    +@pytest.mark.parametrize('move_project', ['move', 'no-move'])
    
    115
    +def test_yamlcache_changed_file(cli, ref_storage, with_junction, move_project):
    
    116
    +    # inline and junction can only be changed by opening a workspace
    
    117
    +    pass
    
    118
    +
    
    119
    +
    
    120
    +@pytest.mark.parametrize('ref_storage', ['inline', 'project.refs'])
    
    121
    +@pytest.mark.parametrize('with_junction', ['junction', 'no-junction'])
    
    122
    +@pytest.mark.parametrize('move_project', ['move', 'no-move'])
    
    123
    +def test_yamlcache_track_changed(cli, ref_storage, with_junction, move_project):
    
    124
    +    # Skip inline junction, tracking those is forbidden
    
    125
    +    pass



  • [Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]