public
Description: Python interface for talking to the github API
Clone URL: git://github.com/dustin/py-github.git
dustin (author)
Sat May 24 12:48:21 -0700 2008
commit  30659ad20a090751efa902a5a9db405c96fc8291
tree    f9af0f96726d97516d3494689b96cc841ef32437
parent  0942fc3164237e73dcdceddb66eef452849e2b7a
py-github / github.py
100755 221 lines (181 sloc) 7.618 kb
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
#!/usr/bin/env python
"""
Interface to github's API.
 
Basic usage:
 
g = GitHub()
 
for r in g.search('memcache'):
print r.name
 
See the GitHub docs or README.markdown for more usage.
 
Copyright (c) 2007 Dustin Sallings <dustin@spy.net>
"""
 
# Copyright (c) 2005 Dustin Sallings <dustin@spy.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# <http://www.opensource.org/licenses/mit-license.php>
 
# GAE friendly URL detection (theoretically)
try:
    import urllib2
    default_fetcher=urllib2.urlopen
except LoadError:
    pass
 
import xml
import xml.dom.minidom
 
class Repository(object):
    """A github repository."""
 
    def __init__(self, el):
        ch=el.firstChild
        while ch:
            if ch.nodeType != xml.dom.Node.TEXT_NODE and ch.firstChild:
                type = 'string'
                if ch.attributes.has_key('type'):
                    type = ch.attributes['type'].value
                if type == 'integer':
                    self.__dict__[ch.localName] = int(ch.firstChild.data)
                else:
                    self.__dict__[ch.localName] = ch.firstChild.data
            ch=ch.nextSibling
 
    def __repr__(self):
        return "<<Repository %s>>" % self.name
 
class Person(object):
    """A person."""
 
    def __init__(self, el):
        ch=el.firstChild
        while ch:
            if ch.nodeType != xml.dom.Node.TEXT_NODE:
                if ch.localName != 'repositories':
                    self.__dict__[ch.localName] = ch.firstChild.data
            ch=ch.nextSibling
        repos=[Repository(el) for el in el.getElementsByTagName('repository')]
        self.repos=dict([(r.name, r) for r in repos])
 
    def __repr__(self):
        return "<<Person %s <%s>>>" % (self.name, self.email)
 
class SearchResults(object):
    """Search results."""
 
    def __init__(self, el):
        ch=el.firstChild
        self.repos=[Repository(el)
            for el in el.getElementsByTagName('repository')]
 
    def __iter__(self):
        return iter(self.repos)
 
    def __getitem__(self, which):
        return self.repos[which]
 
    def __getslice__(self, i, j):
        return self.repos[i:j]
 
    def __len__(self):
        return len(self.repos)
 
    def __repr__(self):
        return "<<SearchResults with %d repos>>" % len(self.repos)
 
class User(Person):
    """A github user."""
 
    def __init__(self, doc):
        Person.__init__(self, doc.firstChild)
 
    def __repr__(self):
        return "<<User %s with %d repos>>" % (self.login, len(self.repos))
 
class FileModification(object):
    """Object representing a specific file modification."""
 
    def __init__(self, el):
        self.diff = el.getElementsByTagName('diff')[0].firstChild.data
        self.filename = el.getElementsByTagName('filename')[0].firstChild.data
 
    def __repr__(self):
        return "<<FileModification: %s>>" % self.filename
 
class Commit(object):
    """A single commit."""
 
    def __init__(self, el):
        ch=el.firstChild
        self.removed=[]
        self.added=[]
        self.modified=[]
        while ch:
            if ch.nodeType != xml.dom.Node.TEXT_NODE:
                if ch.localName == 'parents':
                    self.parents = self.__parseSimpleList(ch, 'id')
                elif ch.localName == 'author':
                    self.author = Person(ch)
                elif ch.localName == 'committer':
                    self.committer = Person(ch)
                elif ch.localName == 'committed-date':
                    self.committedDate = self.__parseDate(ch)
                elif ch.localName == 'authored-date':
                    self.authoredDate = self.__parseDate(ch)
                elif ch.localName == 'added':
                    self.added = self.__parseSimpleList(ch, 'filename')
                elif ch.localName == 'removed':
                    self.removed = self.__parseSimpleList(ch, 'removed')
                elif ch.localName == 'modified':
                    self.modified = [FileModification(el)
                        for el in ch.getElementsByTagName('modified')]
                else:
                    self.__dict__[ch.localName] = ch.firstChild.data
            ch=ch.nextSibling
 
    def __parseSimpleList(self, el, name):
        return [str(s.firstChild.data) for s in el.getElementsByTagName(name)]
 
    def __parseDate(self, el):
        dateStr=el.firstChild.data
        # XXX: Parse here.
        return dateStr
 
    def __repr__(self):
        return "<<Commit %s>>" % self.id
 
class GitHub(object):
    """Interface to github."""
 
    def __init__(self, fetcher=default_fetcher):
        self.fetcher=fetcher
 
    def user(self, username):
        """Get the info for a user."""
        x=self.fetcher("http://github.com/api/v1/xml/%s" % username).read()
        doc=xml.dom.minidom.parseString(x)
        return User(doc)
 
    def search(self, search_string):
        """Search for repositories."""
        x=self.fetcher("http://github.com/api/v1/xml/search/%s"
            % search_string.replace(' ', '+')).read()
        doc=xml.dom.minidom.parseString(x)
        return SearchResults(doc)
 
    def commits(self, username, repo, branch='master'):
        """Get the recent commits for the given repo."""
        x=self.fetcher("http://github.com/api/v1/xml/%s/%s/commits/%s"
            % (username, repo, branch)).read()
        doc=xml.dom.minidom.parseString(x)
        return [Commit(el) for el in doc.getElementsByTagName('commit')]
 
    def commit(self, username, repo, commit):
        """Get a specific commit from the given repo."""
        x=self.fetcher("http://github.com/api/v1/xml/%s/%s/commit/%s"
            % (username, repo, commit)).read()
        doc=xml.dom.minidom.parseString(x)
        return Commit(doc.getElementsByTagName('commit')[0])
 
if __name__ == '__main__':
    import sys
    gh=GitHub()
    if len(sys.argv) == 2:
        u = gh.user(sys.argv[1])
        print "User: %s (%s)" % (u.login, u.name)
        for repo in [u.repos[k] for k in sorted(u.repos.keys())]:
            print "- %s" % repo.name
            print " %s" % repo.url
            print " %s" % "git://github.com/%s/%s.git" % (u.login, repo.name)
    elif len(sys.argv) == 4:
        for commit in gh.commits(*sys.argv[1:]):
            print "%s %s - %s" % (commit.id[0:7],
                commit.author.email, commit.message)
    else:
        print "Usages:"
        print " %s user" % sys.argv[0]
        print " -- show info about a given user"
        print " %s user repo branch" % sys.argv[0]
        print " -- show recent commits on a specific branch"