utils.py 7.44 KB
Newer Older
Philip ABBET's avatar
Philip ABBET committed
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
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :

###############################################################################
#                                                                             #
# Copyright (c) 2016 Idiap Research Institute, http://www.idiap.ch/           #
# Contact: beat.support@idiap.ch                                              #
#                                                                             #
# This file is part of the beat.core module of the BEAT platform.             #
#                                                                             #
# Commercial License Usage                                                    #
# Licensees holding valid commercial BEAT licenses may use this file in       #
# accordance with the terms contained in a written agreement between you      #
# and Idiap. For further information contact tto@idiap.ch                     #
#                                                                             #
# Alternatively, this file may be used under the terms of the GNU Affero      #
# Public License version 3 as published by the Free Software and appearing    #
# in the file LICENSE.AGPL included in the packaging of this file.            #
# The BEAT platform 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.                                        #
#                                                                             #
# You should have received a copy of the GNU Affero Public License along      #
# with the BEAT platform. If not, see http://www.gnu.org/licenses/.           #
#                                                                             #
###############################################################################


import os
import shutil
import collections

import simplejson

import six

from . import hash


def safe_rmfile(f):
  """Safely removes a file from the disk"""

  if os.path.exists(f): os.unlink(f)



def safe_rmdir(f):
  """Safely removes the directory containg a given file from the disk"""

  d = os.path.dirname(f)
  if not os.path.exists(d): return
  if not os.listdir(d): os.rmdir(d)



def extension_for_language(language):
  """Returns the preferred extension for a given programming language

  The set of languages supported must match those declared in our
  ``common.json`` schema.

  Parameters:

    language (str) The language for which you'd like to get the extension for.


  Returns:

    str: The extension for the given language, including a leading ``.`` (dot)


  Raises:

    KeyError: If the language is not defined in our internal dictionary.

  """

  return dict(
          unknown = '',
          cxx = '.so',
          matlab = '.m',
          python = '.py',
          r = '.r',
          )[language]



class File(object):
  """User helper to read and write file objects"""


  def __init__(self, path, binary=False):

    self.path = path
    self.binary = binary


  def exists(self):

    return os.path.exists(self.path)


  def load(self):

    mode = 'rb' if self.binary else 'rt'
    with open(self.path, mode) as f: return f.read()


  def try_load(self):

    if os.path.exists(self.path):
      return self.load()
    return None


  def backup(self):

    if not os.path.exists(self.path): return #no point in backing-up
    backup = self.path + '~'
    if os.path.exists(backup): os.remove(backup)
    shutil.copy(self.path, backup)


  def save(self, contents):

    d = os.path.dirname(self.path)
    if not os.path.exists(d): os.makedirs(d)

    if os.path.exists(self.path): self.backup()

    mode = 'wb' if self.binary else 'wt'
    with open(self.path, mode) as f: f.write(contents)


  def remove(self):

    safe_rmfile(self.path)
    safe_rmfile(self.path + '~') #backup
    safe_rmdir(self.path) #remove containing directory



class Storage(object):
  """Resolves paths for objects that provide only a description

  Parameters:

    prefix (str): Establishes the prefix of your installation.

    name (str): The name of the database object in the format
      ``<name>/<version>``.

  """

  def __init__(self, path):

    self.path = path
    self.json = File(self.path + '.json')
    self.doc = File(self.path + '.rst')

  def hash(self, description='description'):
    """The 64-character hash of the database declaration JSON"""
    return hash.hashJSONFile(self.json.path, description)

  def exists(self):
    """If the database declaration file exists"""
    return self.json.exists()

  def load(self):
    """Loads the JSON declaration as a file"""
    tp = collections.namedtuple('Storage', ['declaration', 'description'])
    return tp(self.json.load(), self.doc.try_load())

  def save(self, declaration, description=None):
    """Saves the JSON declaration as files"""
    if description: self.doc.save(description.encode('utf8'))
    if not isinstance(declaration, six.string_types):
      declaration = simplejson.dumps(declaration, indent=4)
    self.json.save(declaration)

  def remove(self):
    """Removes the object from the disk"""
    self.json.remove()
    self.doc.remove()



class CodeStorage(object):
  """Resolves paths for objects that provide a description and code

  Parameters:

    prefix (str): Establishes the prefix of your installation.

    name (str): The name of the database object in the format
      ``<name>/<version>``.

    language (str): One of the valdid programming languages

  """

  def __init__(self, path, language=None):

    self.path = path
    self.json = File(self.path + '.json')
    self.doc = File(self.path + '.rst')

    self._language = language or self.__auto_discover_language()
    self.code = File(self.path + \
            extension_for_language(self._language), binary=True)

  def __auto_discover_language(self, json=None):
    """Discovers and sets the language from its own JSON descriptor"""
    try:
      text = json or self.json.load()
      json = simplejson.loads(text)
      return json['language']
    except IOError:
      return 'unknown'

  @property
  def language(self):
    return self._language

  @language.setter
  def language(self, value):
    self._language = value
    self.code = File(self.path + extension_for_language(self._language),
            binary=True)

  def hash(self):
    """The 64-character hash of the database declaration JSON"""

    if self.code.exists():
      return hash.hash(dict(
          json=hash.hashJSONFile(self.json.path, 'description'),
          code=hash.hashFileContents(self.code.path),
          ))
    else:
      return hash.hash(dict(
          json=hash.hashJSONFile(self.json.path, 'description'),
          ))

  def exists(self):
    """If the database declaration file exists"""
    return self.json.exists() and self.code.exists()

  def load(self):
    """Loads the JSON declaration as a file"""
    tp = collections.namedtuple('CodeStorage',
            ['declaration', 'code', 'description'])
    return tp(self.json.load(), self.code.try_load(), self.doc.try_load())

  def save(self, declaration, code=None, description=None):
    """Saves the JSON declaration and the code as files"""
    super(CodeStorage, self).save(declaration, description)
    if code:
      if self._language == 'unknown':
        self.language = self.__auto_discover_language(declaration)
      self.code.save(code)

  def remove(self):
    """Removes the object from the disk"""
    super(CodeStorage, self).remove()
    self.code.remove()