summaryrefslogtreecommitdiff
path: root/lib/git/tree.py
blob: 1ed3396dc2d2e12b96b872f1c268f967b06409ca (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
# tree.py
# Copyright (C) 2008 Michael Trier (mtrier@gmail.com) and contributors
#
# This module is part of GitPython and is released under
# the BSD License: http://www.opensource.org/licenses/bsd-license.php

import os
from lazy import LazyMixin
import blob

class Tree(LazyMixin):
    def __init__(self, repo, **kwargs):
        LazyMixin.__init__(self)
        self.repo = repo
        self.id = None
        self.mode = None
        self.name = None
        self.contents = None

        for k, v in kwargs.items():
            setattr(self, k, v)

    def __bake__(self):
        # Ensure the treeish references directly a tree
        treeish = self.id
        if not treeish.endswith(':'):
            treeish = treeish + ':'

        # Read the tree contents.
        self.contents = {}
        for line in self.repo.git.ls_tree(self.id).splitlines():
            obj = self.content_from_string(self.repo, line)
            if obj:
                self.contents[obj.name] = obj

    def content_from_string(self, repo, text):
        """
        Parse a content item and create the appropriate object

        ``repo``
            is the Repo

         ``text``
            is the single line containing the items data in `git ls-tree` format

        Returns
            ``GitPython.Blob`` or ``GitPython.Tree``
        """
        try:
            mode, typ, id, name = text.expandtabs(1).split(" ", 4)
        except:
            return None

        if typ == "tree":
            return Tree(repo, id=id, mode=mode, name=name)
        elif typ == "blob":
            return blob.Blob(repo, id=id, mode=mode, name=name)
        elif typ == "commit":
            return None
        else:
          raise(TypeError, "Invalid type: %s" % typ)

    def __div__(self, file):
        """
        Find the named object in this tree's contents

        Examples::

            >>> Repo('/path/to/python-git').tree/'lib'
            <GitPython.Tree "6cc23ee138be09ff8c28b07162720018b244e95e">
            >>> Repo('/path/to/python-git').tree/'README.txt'
            <GitPython.Blob "8b1e02c0fb554eed2ce2ef737a68bb369d7527df">

        Returns
            ``GitPython.Blob`` or ``GitPython.Tree`` or ``None`` if not found
        """
        return self.contents.get(file)

    @property
    def basename(self):
        os.path.basename(self.name)

    def __repr__(self):
        return '<GitPython.Tree "%s">' % self.id