Kiln » Dependencies » Dulwich Read More
Clone URL:  
Pushed to one repository · View In Graph Contained in master

Add a GitFile class that uses the same locking protocol for writes as git.

Change-Id: Id9c6f8b5880a73e0e714cbc61e954d0ecae6103a

Changeset c8e9d212ce59

Parent 032036b37eeb

committed by Dave Borowitz

authored by Dave Borowitz

Changes to 7 files · Browse files at c8e9d212ce59 Showing diff from parent 032036b37eeb Diff from another changeset...

Change 1 of 1 Show Entire File dulwich/​file.py Stacked
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
@@ -1,0 +1,106 @@
+# file.py -- Safe access to git files +# Copyright (C) 2010 Google, Inc. +# +# 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; version 2 +# of the License or (at your option) a later version of the License. +# +# 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., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. + + +"""Safe access to git files.""" + + +import errno +import os + + +def GitFile(filename, mode='r', bufsize=-1): + if 'a' in mode: + raise IOError('append mode not supported for Git files') + if 'w' in mode: + return _GitFile(filename, mode, bufsize) + else: + return file(filename, mode, bufsize) + + +class _GitFile(object): + """File that follows the git locking protocol for writes. + + All writes to a file foo will be written into foo.lock in the same + directory, and the lockfile will be renamed to overwrite the original file + on close. The lockfile is automatically removed upon filesystem error. + + :note: You *must* call close() or abort() on a _GitFile for the lock to be + released. Typically this will happen in a finally block. + """ + + PROXY_PROPERTIES = set(['closed', 'encoding', 'errors', 'mode', 'name', + 'newlines', 'softspace']) + PROXY_METHODS = ('__iter__', 'flush', 'fileno', 'isatty', 'next', 'read', + 'readline', 'readlines', 'xreadlines', 'seek', 'tell', + 'truncate', 'write', 'writelines') + def __init__(self, filename, mode, bufsize): + self._filename = filename + self._lockfilename = '%s.lock' % self._filename + fd = os.open(self._lockfilename, os.O_RDWR | os.O_CREAT | os.O_EXCL) + self._file = os.fdopen(fd, mode, bufsize) + + for method in self.PROXY_METHODS: + setattr(self, method, + self._safe_method(getattr(self._file, method))) + + def _safe_method(self, file_method): + # note that built-in file methods have no kwargs + def do_safe_method(*args): + try: + return file_method(*args) + except (OSError, IOError): + self.abort() + raise + return do_safe_method + + def abort(self): + """Close and discard the lockfile without overwriting the target. + + If the file is already closed, this is a no-op. + """ + self._file.close() + try: + os.remove(self._lockfilename) + except OSError, e: + # The file may have been removed already, which is ok. + if e.errno != errno.ENOENT: + raise + + def close(self): + """Close this file, saving the lockfile over the original. + + :note: If this method fails, it will attempt to delete the lockfile. + However, it is not guaranteed to do so (e.g. if a filesystem becomes + suddenly read-only), which will prevent future writes to this file + until the lockfile is removed manually. + :raises OSError: if the original file could not be overwritten. The lock + file is still closed, so further attempts to write to the same file + object will raise ValueError. + """ + self._file.close() + try: + os.rename(self._lockfilename, self._filename) + finally: + self.abort() + + def __getattr__(self, name): + """Proxy property calls to the underlying file.""" + if name in self.PROXY_PROPERTIES: + return getattr(self._file, name) + raise AttributeError(name)
Change 1 of 3 Show Entire File dulwich/​index.py Stacked
 
22
23
24
 
25
26
27
 
173
174
175
176
 
177
178
179
 
182
183
184
185
 
186
187
188
 
22
23
24
25
26
27
28
 
174
175
176
 
177
178
179
180
 
183
184
185
 
186
187
188
189
@@ -22,6 +22,7 @@
 import stat  import struct   +from dulwich.file import GitFile  from dulwich.objects import (   S_IFGITLINK,   S_ISGITLINK, @@ -173,7 +174,7 @@
    def write(self):   """Write current contents of index to disk.""" - f = open(self._filename, 'wb') + f = GitFile(self._filename, 'wb')   try:   f = SHA1Writer(f)   write_index_dict(f, self._byname) @@ -182,7 +183,7 @@
    def read(self):   """Read current contents of index from disk.""" - f = open(self._filename, 'rb') + f = GitFile(self._filename, 'rb')   try:   f = SHA1Reader(f)   for x in read_index(f):
 
29
30
31
 
32
33
34
 
294
295
296
297
 
298
299
300
 
29
30
31
32
33
34
35
 
295
296
297
 
298
299
300
301
@@ -29,6 +29,7 @@
 from dulwich.errors import (   NotTreeError,   ) +from dulwich.file import GitFile  from dulwich.objects import (   Commit,   ShaFile, @@ -294,7 +295,7 @@
  path = os.path.join(dir, sha[2:])   if os.path.exists(path):   return # Already there, no need to write again - f = open(path, 'w+') + f = GitFile(path, 'wb')   try:   f.write(o.as_legacy_object())   finally:
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
 
 # objects.py -- Access to base git objects  # Copyright (C) 2007 James Westby <jw+debian@jameswestby.net>  # Copyright (C) 2008-2009 Jelmer Vernooij <jelmer@samba.org>  #  # 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; version 2  # of the License or (at your option) a later version of the License.  #  # 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., 51 Franklin Street, Fifth Floor, Boston,  # MA 02110-1301, USA.      """Access to base git objects."""      import binascii  from cStringIO import (   StringIO,   )  import mmap  import os  import stat  import time  import zlib    from dulwich.errors import (   NotBlobError,   NotCommitError,   NotTreeError,   ) +from dulwich.file import GitFile  from dulwich.misc import (   make_sha,   )    BLOB_ID = "blob"  TAG_ID = "tag"  TREE_ID = "tree"  COMMIT_ID = "commit"  PARENT_ID = "parent"  AUTHOR_ID = "author"  COMMITTER_ID = "committer"  OBJECT_ID = "object"  TYPE_ID = "type"  TAGGER_ID = "tagger"  ENCODING_ID = "encoding"    S_IFGITLINK = 0160000  def S_ISGITLINK(m):   return (stat.S_IFMT(m) == S_IFGITLINK)    def _decompress(string):   dcomp = zlib.decompressobj()   dcomped = dcomp.decompress(string)   dcomped += dcomp.flush()   return dcomped      def sha_to_hex(sha):   """Takes a string and returns the hex of the sha within"""   hexsha = binascii.hexlify(sha)   assert len(hexsha) == 40, "Incorrect length of sha1 string: %d" % hexsha   return hexsha      def hex_to_sha(hex):   """Takes a hex sha and returns a binary sha"""   assert len(hex) == 40, "Incorrent length of hexsha: %s" % hex   return binascii.unhexlify(hex)      def serializable_property(name, docstring=None):   def set(obj, value):   obj._ensure_parsed()   setattr(obj, "_"+name, value)   obj._needs_serialization = True   def get(obj):   obj._ensure_parsed()   return getattr(obj, "_"+name)   return property(get, set, doc=docstring)      class ShaFile(object):   """A git SHA file."""     @classmethod   def _parse_legacy_object(cls, map):   """Parse a legacy object, creating it and setting object._text"""   text = _decompress(map)   object = None   for posstype in type_map.keys():   if text.startswith(posstype):   object = type_map[posstype]()   text = text[len(posstype):]   break   assert object is not None, "%s is not a known object type" % text[:9]   assert text[0] == ' ', "%s is not a space" % text[0]   text = text[1:]   size = 0   i = 0   while text[0] >= '0' and text[0] <= '9':   if i > 0 and size == 0:   raise AssertionError("Size is not in canonical format")   size = (size * 10) + int(text[0])   text = text[1:]   i += 1   object._size = size   assert text[0] == "\0", "Size not followed by null"   text = text[1:]   object.set_raw_string(text)   return object     def as_legacy_object(self):   text = self.as_raw_string()   return zlib.compress("%s %d\0%s" % (self._type, len(text), text))     def as_raw_string(self):   if self._needs_serialization:   self.serialize()   return self._text     def __str__(self):   return self.as_raw_string()     def __hash__(self):   return hash(self.id)     def as_pretty_string(self):   return self.as_raw_string()     def _ensure_parsed(self):   if self._needs_parsing:   self._parse_text()     def set_raw_string(self, text):   if type(text) != str:   raise TypeError(text)   self._text = text   self._sha = None   self._needs_parsing = True   self._needs_serialization = False     @classmethod   def _parse_object(cls, map):   """Parse a new style object , creating it and setting object._text"""   used = 0   byte = ord(map[used])   used += 1   num_type = (byte >> 4) & 7   try:   object = num_type_map[num_type]()   except KeyError:   raise AssertionError("Not a known type: %d" % num_type)   while (byte & 0x80) != 0:   byte = ord(map[used])   used += 1   raw = map[used:]   object.set_raw_string(_decompress(raw))   return object     @classmethod   def _parse_file(cls, map):   word = (ord(map[0]) << 8) + ord(map[1])   if ord(map[0]) == 0x78 and (word % 31) == 0:   return cls._parse_legacy_object(map)   else:   return cls._parse_object(map)     def __init__(self):   """Don't call this directly"""   self._sha = None     def _parse_text(self):   """For subclasses to do initialisation time parsing"""     @classmethod   def from_file(cls, filename):   """Get the contents of a SHA file on disk"""   size = os.path.getsize(filename) - f = open(filename, 'rb') + f = GitFile(filename, 'rb')   try:   map = mmap.mmap(f.fileno(), size, access=mmap.ACCESS_READ)   shafile = cls._parse_file(map)   return shafile   finally:   f.close()     @classmethod   def from_raw_string(cls, type, string):   """Creates an object of the indicated type from the raw string given.     Type is the numeric type of an object. String is the raw uncompressed   contents.   """   real_class = num_type_map[type]   obj = real_class()   obj.type = type   obj.set_raw_string(string)   return obj     @classmethod   def from_string(cls, string):   """Create a blob from a string."""   shafile = cls()   shafile.set_raw_string(string)   return shafile     def _header(self):   return "%s %lu\0" % (self._type, len(self.as_raw_string()))     def sha(self):   """The SHA1 object that is the name of this object."""   if self._needs_serialization or self._sha is None:   self._sha = make_sha()   self._sha.update(self._header())   self._sha.update(self.as_raw_string())   return self._sha     @property   def id(self):   return self.sha().hexdigest()     def get_type(self):   return self._num_type     def set_type(self, type):   self._num_type = type     type = property(get_type, set_type)     def __repr__(self):   return "<%s %s>" % (self.__class__.__name__, self.id)     def __ne__(self, other):   return self.id != other.id     def __eq__(self, other):   """Return true id the sha of the two objects match.     The __le__ etc methods aren't overriden as they make no sense,   certainly at this level.   """   return self.id == other.id      class Blob(ShaFile):   """A Git Blob object."""     _type = BLOB_ID   _num_type = 3   _needs_serialization = False   _needs_parsing = False     def get_data(self):   return self._text     def set_data(self, data):   self._text = data     data = property(get_data, set_data,   "The text contained within the blob object.")     @classmethod   def from_file(cls, filename):   blob = ShaFile.from_file(filename)   if blob._type != cls._type:   raise NotBlobError(filename)   return blob      class Tag(ShaFile):   """A Git Tag object."""     _type = TAG_ID   _num_type = 4     def __init__(self):   super(Tag, self).__init__()   self._needs_parsing = False   self._needs_serialization = True     @classmethod   def from_file(cls, filename):   blob = ShaFile.from_file(filename)   if blob._type != cls._type:   raise NotBlobError(filename)   return blob     @classmethod   def from_string(cls, string):   """Create a blob from a string."""   shafile = cls()   shafile.set_raw_string(string)   return shafile     def serialize(self):   f = StringIO()   f.write("%s %s\n" % (OBJECT_ID, self._object_sha))   f.write("%s %s\n" % (TYPE_ID, num_type_map[self._object_type]._type))   f.write("%s %s\n" % (TAG_ID, self._name))   if self._tagger:   if self._tag_time is None:   f.write("%s %s\n" % (TAGGER_ID, self._tagger))   else:   f.write("%s %s %d %s\n" % (TAGGER_ID, self._tagger, self._tag_time, format_timezone(self._tag_timezone)))   f.write("\n") # To close headers   f.write(self._message)   self._text = f.getvalue()   self._needs_serialization = False     def _parse_text(self):   """Grab the metadata attached to the tag"""   self._tagger = None   f = StringIO(self._text)   for l in f:   l = l.rstrip("\n")   if l == "":   break # empty line indicates end of headers   (field, value) = l.split(" ", 1)   if field == OBJECT_ID:   self._object_sha = value   elif field == TYPE_ID:   self._object_type = type_map[value]   elif field == TAG_ID:   self._name = value   elif field == TAGGER_ID:   try:   sep = value.index("> ")   except ValueError:   self._tagger = value   self._tag_time = None   self._tag_timezone = None   else:   self._tagger = value[0:sep+1]   (timetext, timezonetext) = value[sep+2:].rsplit(" ", 1)   try:   self._tag_time = int(timetext)   except ValueError: #Not a unix timestamp   self._tag_time = time.strptime(timetext)   self._tag_timezone = parse_timezone(timezonetext)   else:   raise AssertionError("Unknown field %s" % field)   self._message = f.read()   self._needs_parsing = False     def get_object(self):   """Returns the object pointed by this tag, represented as a tuple(type, sha)"""   self._ensure_parsed()   return (self._object_type, self._object_sha)     def set_object(self, value):   self._ensure_parsed()   (self._object_type, self._object_sha) = value   self._needs_serialization = True     object = property(get_object, set_object)     name = serializable_property("name", "The name of this tag")   tagger = serializable_property("tagger",   "Returns the name of the person who created this tag")   tag_time = serializable_property("tag_time",   "The creation timestamp of the tag. As the number of seconds since the epoch")   tag_timezone = serializable_property("tag_timezone",   "The timezone that tag_time is in.")   message = serializable_property("message", "The message attached to this tag")      def parse_tree(text):   ret = {}   count = 0   l = len(text)   while count < l:   mode_end = text.index(' ', count)   mode = int(text[count:mode_end], 8)     name_end = text.index('\0', mode_end)   name = text[mode_end+1:name_end]     count = name_end+21     sha = text[name_end+1:count]     ret[name] = (mode, sha_to_hex(sha))     return ret      class Tree(ShaFile):   """A Git tree object"""     _type = TREE_ID   _num_type = 2     def __init__(self):   super(Tree, self).__init__()   self._entries = {}   self._needs_parsing = False   self._needs_serialization = True     @classmethod   def from_file(cls, filename):   tree = ShaFile.from_file(filename)   if tree._type != cls._type:   raise NotTreeError(filename)   return tree     def __contains__(self, name):   self._ensure_parsed()   return name in self._entries     def __getitem__(self, name):   self._ensure_parsed()   return self._entries[name]     def __setitem__(self, name, value):   assert isinstance(value, tuple)   assert len(value) == 2   self._ensure_parsed()   self._entries[name] = value   self._needs_serialization = True     def __delitem__(self, name):   self._ensure_parsed()   del self._entries[name]   self._needs_serialization = True     def __len__(self):   self._ensure_parsed()   return len(self._entries)     def add(self, mode, name, hexsha):   assert type(mode) == int   assert type(name) == str   assert type(hexsha) == str   self._ensure_parsed()   self._entries[name] = mode, hexsha   self._needs_serialization = True     def entries(self):   """Return a list of tuples describing the tree entries"""   self._ensure_parsed()   # The order of this is different from iteritems() for historical reasons   return [(mode, name, hexsha) for (name, mode, hexsha) in self.iteritems()]     def iteritems(self):   def cmp_entry((name1, value1), (name2, value2)):   if stat.S_ISDIR(value1[0]):   name1 += "/"   if stat.S_ISDIR(value2[0]):   name2 += "/"   return cmp(name1, name2)   self._ensure_parsed()   for name, entry in sorted(self._entries.iteritems(), cmp=cmp_entry):   yield name, entry[0], entry[1]     def _parse_text(self):   """Grab the entries in the tree"""   self._entries = parse_tree(self._text)   self._needs_parsing = False     def serialize(self):   f = StringIO()   for name, mode, hexsha in self.iteritems():   f.write("%04o %s\0%s" % (mode, name, hex_to_sha(hexsha)))   self._text = f.getvalue()   self._needs_serialization = False     def as_pretty_string(self):   text = ""   for name, mode, hexsha in self.iteritems():   if mode & stat.S_IFDIR:   kind = "tree"   else:   kind = "blob"   text += "%04o %s %s\t%s\n" % (mode, kind, hexsha, name)   return text      def parse_timezone(text):   offset = int(text)   signum = (offset < 0) and -1 or 1   offset = abs(offset)   hours = int(offset / 100)   minutes = (offset % 100)   return signum * (hours * 3600 + minutes * 60)      def format_timezone(offset):   if offset % 60 != 0:   raise ValueError("Unable to handle non-minute offset.")   sign = (offset < 0) and '-' or '+'   offset = abs(offset)   return '%c%02d%02d' % (sign, offset / 3600, (offset / 60) % 60)      class Commit(ShaFile):   """A git commit object"""     _type = COMMIT_ID   _num_type = 1     def __init__(self):   super(Commit, self).__init__()   self._parents = []   self._encoding = None   self._needs_parsing = False   self._needs_serialization = True   self._extra = {}     @classmethod   def from_file(cls, filename):   commit = ShaFile.from_file(filename)   if commit._type != cls._type:   raise NotCommitError(filename)   return commit     def _parse_text(self):   self._parents = []   self._extra = []   self._author = None   f = StringIO(self._text)   for l in f:   l = l.rstrip("\n")   if l == "":   # Empty line indicates end of headers   break   (field, value) = l.split(" ", 1)   if field == TREE_ID:   self._tree = value   elif field == PARENT_ID:   self._parents.append(value)   elif field == AUTHOR_ID:   self._author, timetext, timezonetext = value.rsplit(" ", 2)   self._author_time = int(timetext)   self._author_timezone = parse_timezone(timezonetext)   elif field == COMMITTER_ID:   self._committer, timetext, timezonetext = value.rsplit(" ", 2)   self._commit_time = int(timetext)   self._commit_timezone = parse_timezone(timezonetext)   elif field == ENCODING_ID:   self._encoding = value   else:   self._extra.append((field, value))   self._message = f.read()   self._needs_parsing = False     def serialize(self):   f = StringIO()   f.write("%s %s\n" % (TREE_ID, self._tree))   for p in self._parents:   f.write("%s %s\n" % (PARENT_ID, p))   f.write("%s %s %s %s\n" % (AUTHOR_ID, self._author, str(self._author_time), format_timezone(self._author_timezone)))   f.write("%s %s %s %s\n" % (COMMITTER_ID, self._committer, str(self._commit_time), format_timezone(self._commit_timezone)))   if self.encoding:   f.write("%s %s\n" % (ENCODING_ID, self.encoding))   for k, v in self.extra:   if "\n" in k or "\n" in v:   raise AssertionError("newline in extra data: %r -> %r" % (k, v))   f.write("%s %s\n" % (k, v))   f.write("\n") # There must be a new line after the headers   f.write(self._message)   self._text = f.getvalue()   self._needs_serialization = False     tree = serializable_property("tree", "Tree that is the state of this commit")     def get_parents(self):   """Return a list of parents of this commit."""   self._ensure_parsed()   return self._parents     def set_parents(self, value):   """Return a list of parents of this commit."""   self._ensure_parsed()   self._needs_serialization = True   self._parents = value     parents = property(get_parents, set_parents)     def get_extra(self):   """Return extra settings of this commit."""   self._ensure_parsed()   return self._extra     extra = property(get_extra)     author = serializable_property("author",   "The name of the author of the commit")     committer = serializable_property("committer",   "The name of the committer of the commit")     message = serializable_property("message",   "The commit message")     commit_time = serializable_property("commit_time",   "The timestamp of the commit. As the number of seconds since the epoch.")     commit_timezone = serializable_property("commit_timezone",   "The zone the commit time is in")     author_time = serializable_property("author_time",   "The timestamp the commit was written. as the number of seconds since the epoch.")     author_timezone = serializable_property("author_timezone",   "Returns the zone the author time is in.")     encoding = serializable_property("encoding",   "Encoding of the commit message.")      type_map = {   BLOB_ID : Blob,   TREE_ID : Tree,   COMMIT_ID : Commit,   TAG_ID: Tag,  }    num_type_map = {   0: None,   1: Commit,   2: Tree,   3: Blob,   4: Tag,   # 5 Is reserved for further expansion  }    try:   # Try to import C versions   from dulwich._objects import parse_tree  except ImportError:   pass -
Change 1 of 7 Show Entire File dulwich/​pack.py Stacked
 
55
56
57
 
58
59
60
 
150
151
152
153
 
154
155
156
 
211
212
213
214
 
215
216
217
 
497
498
499
500
 
501
502
503
 
809
810
811
812
 
813
814
815
 
873
874
875
876
 
877
878
879
 
1021
1022
1023
1024
 
1025
1026
1027
 
55
56
57
58
59
60
61
 
151
152
153
 
154
155
156
157
 
212
213
214
 
215
216
217
218
 
498
499
500
 
501
502
503
504
 
810
811
812
 
813
814
815
816
 
874
875
876
 
877
878
879
880
 
1022
1023
1024
 
1025
1026
1027
1028
@@ -55,6 +55,7 @@
  ApplyDeltaError,   ChecksumMismatch,   ) +from dulwich.file import GitFile  from dulwich.lru_cache import (   LRUSizeCache,   ) @@ -150,7 +151,7 @@
    :param filename: Path to the index file   """ - f = open(filename, 'rb') + f = GitFile(filename, 'rb')   if f.read(4) == '\377tOc':   version = struct.unpack(">L", f.read(4))[0]   if version == 2: @@ -211,7 +212,7 @@
  # ensure that it hasn't changed.   self._size = os.path.getsize(filename)   if file is None: - self._file = open(filename, 'rb') + self._file = GitFile(filename, 'rb')   else:   self._file = file   self._contents, map_offset = simple_mmap(self._file, 0, self._size) @@ -497,7 +498,7 @@
  self._size = os.path.getsize(filename)   self._header_size = 12   assert self._size >= self._header_size, "%s is too small for a packfile (%d < %d)" % (filename, self._size, self._header_size) - self._file = open(self._filename, 'rb') + self._file = GitFile(self._filename, 'rb')   self._read_header()   self._offset_cache = LRUSizeCache(1024*1024*20,   compute_size=_compute_object_size) @@ -809,7 +810,7 @@
  :param objects: Iterable over (object, path) tuples to write   :param num_objects: Number of objects to write   """ - f = open(filename + ".pack", 'wb') + f = GitFile(filename + ".pack", 'wb')   try:   entries, data_sum = write_pack_data(f, objects, num_objects)   finally: @@ -873,7 +874,7 @@
  crc32_checksum.   :param pack_checksum: Checksum of the pack file.   """ - f = open(filename, 'wb') + f = GitFile(filename, 'wb')   f = SHA1Writer(f)   fan_out_table = defaultdict(lambda: 0)   for (name, offset, entry_checksum) in entries: @@ -1021,7 +1022,7 @@
  crc32_checksum.   :param pack_checksum: Checksum of the pack file.   """ - f = open(filename, 'wb') + f = GitFile(filename, 'wb')   f = SHA1Writer(f)   f.write('\377tOc') # Magic!   f.write(struct.pack(">L", 2))
Change 1 of 5 Show Entire File dulwich/​repo.py Stacked
 
32
33
34
 
35
36
37
 
161
162
163
164
 
165
166
167
 
172
173
174
175
 
176
177
178
 
310
311
312
313
 
314
315
316
 
482
483
484
485
486
487
 
 
 
 
 
 
 
 
 
488
489
490
491
492
 
 
 
 
 
493
494
495
496
 
32
33
34
35
36
37
38
 
162
163
164
 
165
166
167
168
 
173
174
175
 
176
177
178
179
 
311
312
313
 
314
315
316
317
 
483
484
485
 
 
 
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
 
@@ -32,6 +32,7 @@
  NotGitRepository,   NotTreeError,   ) +from dulwich.file import GitFile  from dulwich.object_store import (   DiskObjectStore,   ) @@ -161,7 +162,7 @@
  file = self.refpath(name)   if not os.path.exists(file):   raise KeyError(name) - f = open(file, 'rb') + f = GitFile(file, 'rb')   try:   return f.read().strip("\n")   finally: @@ -172,7 +173,7 @@
  dirpath = os.path.dirname(file)   if not os.path.exists(dirpath):   os.makedirs(dirpath) - f = open(file, 'wb') + f = GitFile(file, 'wb')   try:   f.write(ref+"\n")   finally: @@ -310,7 +311,7 @@
  if not os.path.exists(path):   return {}   ret = {} - f = open(path, 'rb') + f = GitFile(path, 'rb')   try:   for entry in read_packed_refs(f):   ret[entry[1]] = entry[0] @@ -482,15 +483,25 @@
  os.mkdir(os.path.join(path, *d))   ret = cls(path)   ret.refs.set_ref("HEAD", "refs/heads/master") - open(os.path.join(path, 'description'), 'wb').write("Unnamed repository") - open(os.path.join(path, 'info', 'excludes'), 'wb').write("") - open(os.path.join(path, 'config'), 'wb').write("""[core] + f = GitFile(os.path.join(path, 'description'), 'wb') + try: + f.write("Unnamed repository") + finally: + f.close() + + f = GitFile(os.path.join(path, 'config'), 'wb') + try: + f.write("""[core]   repositoryformatversion = 0   filemode = true   bare = false   logallrefupdates = true  """) + finally: + f.close() + + f = GitFile(os.path.join(path, 'info', 'excludes'), 'wb') + f.close()   return ret     create = init_bare -
Change 1 of 1 Show Entire File dulwich/​tests/​test_file.py Stacked
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
@@ -1,0 +1,133 @@
+# test_file.py -- Test for git files +# Copyright (C) 2010 Google, Inc. +# +# 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; version 2 +# of the License or (at your option) a later version of the License. +# +# 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., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. + + +import errno +import os +import shutil +import tempfile +import unittest + +from dulwich.file import GitFile + +class GitFileTests(unittest.TestCase): + def setUp(self): + self._tempdir = tempfile.mkdtemp() + f = open(self.path('foo'), 'wb') + f.write('foo contents') + f.close() + + def tearDown(self): + shutil.rmtree(self._tempdir) + + def path(self, filename): + return os.path.join(self._tempdir, filename) + + def test_readonly(self): + f = GitFile(self.path('foo'), 'rb') + self.assertTrue(isinstance(f, file)) + self.assertEquals('foo contents', f.read()) + self.assertEquals('', f.read()) + f.seek(4) + self.assertEquals('contents', f.read()) + f.close() + + def test_write(self): + foo = self.path('foo') + foo_lock = '%s.lock' % foo + + orig_f = open(foo, 'rb') + self.assertEquals(orig_f.read(), 'foo contents') + orig_f.close() + + self.assertFalse(os.path.exists(foo_lock)) + f = GitFile(foo, 'wb') + self.assertFalse(f.closed) + self.assertRaises(AttributeError, getattr, f, 'not_a_file_property') + + self.assertTrue(os.path.exists(foo_lock)) + f.write('new stuff') + f.seek(4) + f.write('contents') + f.close() + self.assertFalse(os.path.exists(foo_lock)) + + new_f = open(foo, 'rb') + self.assertEquals('new contents', new_f.read()) + new_f.close() + + def test_open_twice(self): + foo = self.path('foo') + f1 = GitFile(foo, 'wb') + f1.write('new') + try: + f2 = GitFile(foo, 'wb') + fail() + except OSError, e: + self.assertEquals(errno.EEXIST, e.errno) + f1.write(' contents') + f1.close() + + # Ensure trying to open twice doesn't affect original. + f = open(foo, 'rb') + self.assertEquals('new contents', f.read()) + f.close() + + def test_abort(self): + foo = self.path('foo') + foo_lock = '%s.lock' % foo + + orig_f = open(foo, 'rb') + self.assertEquals(orig_f.read(), 'foo contents') + orig_f.close() + + f = GitFile(foo, 'wb') + f.write('new contents') + f.abort() + self.assertTrue(f.closed) + self.assertFalse(os.path.exists(foo_lock)) + + new_orig_f = open(foo, 'rb') + self.assertEquals(new_orig_f.read(), 'foo contents') + new_orig_f.close() + + def test_safe_method(self): + foo = self.path('foo') + foo_lock = '%s.lock' % foo + + f = GitFile(foo, 'wb') + f.write('new contents') + + def error_method(x): + f._test = x + raise IOError('fake IO error') + + try: + f._safe_method(error_method)('test value') + fail() + except IOError, e: + # error is re-raised + self.assertEquals('fake IO error', e.message) + + # method got correct args + self.assertEquals('test value', f._test) + self.assertFalse(os.path.exists(foo_lock)) + + new_orig_f = open(foo, 'rb') + self.assertEquals(new_orig_f.read(), 'foo contents') + new_orig_f.close()