浏览代码

Add __iter__.

Jelmer Vernooij 16 年之前
父节点
当前提交
f09bda5466
共有 2 个文件被更改,包括 16 次插入3 次删除
  1. 9 3
      dulwich/pack.py
  2. 7 0
      dulwich/tests/test_pack.py

+ 9 - 3
dulwich/pack.py

@@ -182,6 +182,10 @@ class PackIndex(object):
         return struct.unpack_from(">L", self._contents, 
                                   self._crc32_table_offset + i * 4)[0]
 
+  def __iter__(self):
+    for i in range(len(self)):
+        yield sha_to_hex(self._unpack_name(i))
+
   def iterentries(self):
     """Iterate over the entries in this pack index.
    
@@ -222,11 +226,10 @@ class PackIndex(object):
     size = os.path.getsize(self._filename)
     assert size == self._size, "Pack index %s has changed size, I don't " \
          "like that" % self._filename
-    return self._object_index(sha)
+    return self._object_index(hex_to_sha(sha))
 
-  def _object_index(self, hexsha):
+  def _object_index(self, sha):
       """See object_index"""
-      sha = hex_to_sha(hexsha)
       start = self._fan_out_table[ord(sha[0])-1]
       end = self._fan_out_table[ord(sha[0])]
       while start < end:
@@ -464,6 +467,9 @@ class Pack(object):
     def __repr__(self):
         return "Pack(%r)" % self._basename
 
+    def __iter__(self):
+        return iter(self._idx)
+
     def check(self):
         return self._idx.check() and self._pack.check()
 

+ 7 - 0
dulwich/tests/test_pack.py

@@ -86,6 +86,9 @@ class PackIndexTests(PackTests):
     p = self.get_pack_index(pack1_sha)
     self.assertEquals([('og\x0c\x0f\xb5?\x94cv\x0br\x95\xfb\xb8\x14\xe9e\xfb \xc8', 178, None), ('\xb2\xa2vj(y\xc2\t\xab\x11v\xe7\xe7x\xb8\x1a\xe4"\xee\xaa', 138, None), ('\xf1\x8f\xaa\x16S\x1a\xc5p\xa3\xfd\xc8\xc7\xca\x16h%H\xda\xfd\x12', 12, None)], list(p.iterentries()))
 
+  def test_iter(self):
+    p = self.get_pack_index(pack1_sha)
+    self.assertEquals(set([tree_sha, commit_sha, a_sha]), set(p))
 
 
 class TestPackData(PackTests):
@@ -131,6 +134,10 @@ class TestPack(PackTests):
         p = self.get_pack(pack1_sha)
         self.assertEquals(type(p[tree_sha]), Tree)
 
+    def test_iter(self):
+        p = self.get_pack(pack1_sha)
+        self.assertEquals(set([tree_sha, commit_sha, a_sha]), set(p))
+
 
 class TestHexToSha(unittest.TestCase):