summaryrefslogtreecommitdiff
path: root/patchtracker/Patch.py
blob: 307821442202ce87046afa2e38544a567e1395b0 (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
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
import errno
import os
import stat
import sys
import tempfile
from glob import glob
import pygments
import pygments.lexers
import pygments.formatters
import tarfile

class Diffstat:
  def __init__(self, patch):
    self.patch = patch
    i,o = os.popen2("diffstat -p1")
    i.write(str(patch))
    i.close()
    self.output = o.readlines()

  def stats(self):
    i,o = os.popen2("diffstat -p1 -t")
    i.write(str(self.patch))
    i.close()
    o.readline()
    return [map(lambda x: x.strip(), l.split(",")) for l in o.readlines()]

  def summary(self):
    return self.output[-1]

  def __str__(self):
    return "".join(self.output)

class Patch:
  def __init__(self, fh, level=1):
    self.p = fh.readlines()
    self.lvl = level

  def __str__(self):
    return "".join(self.p)

  def lines(self):
    return len(self.p)

  def diffstat(self):
    return Diffstat(self)

  def highlight(self):
    for enc in ['utf-8', 'latin-1']:
      try:
        return pygments.highlight(str(self).decode(enc), pygments.lexers.DiffLexer(), 
                                  pygments.formatters.HtmlFormatter(style='colorful', noclasses=True, encoding=enc, nobackground=True))
      except UnicodeDecodeError:
        pass

class GenericPatchSeries (list):
  def blank(self):
    self.names = []
    self.style = "unknown"
    self.patches = {}
    self.patchargs = {}

  # WTF am i doing this for, again?
  def iterpatches(self):
    for p in self.names:
      yield (p, self.patches[p])

  def __iter__(self):
    return self.iterpatches()

  def __getitem__(self, y):
    return self.patches[self.names[y]]

  def __len__(self):
    return len(self.names)

  def fetch(self, name):
    return self.patches[name]

  def __str__(self):
    return "\n".join(self.names)

# XXX this entire __init__ stuff is way to ugly
class PatchSeries (GenericPatchSeries):
  def __init__(self, dir):
    fd = None
    self.blank()
    self.style = "simple"
    try:
      fd = file(os.sep.join([dir, "00list"]))
      self.style = "dpatch"
    except IOError, e:
      if e.errno != errno.ENOENT:
        #print "ERROR: unable to open dpatch list..."
        self.blank()
        return
    try:
      fd = file(os.sep.join([dir, "series"]))
      self.style = "quilt"
    except IOError, e:
      if e.errno != errno.ENOENT:
        #print "ERROR: series file is a directory..."
        self.blank()
        return

    if fd:
      # remove blank lines
      for line in filter(None, [n.strip() for n in fd.readlines()]):
        stuff = line.split(' ')
        # skip comments
        if stuff[0][0] == "#":
          continue
        # here's the name
        name = stuff[0]
        #print "\t\t\t%s: %s"%(self.style,name)
        self.names.append(name)
        # anything else are either patch args or comments
        self.patchargs[name] = []
        for rest in filter(None, stuff[1:]):
          if rest[0][0] == "#":
            break
          else:
            self.patchargs[name].append(rest)

    else:
      self.names = os.listdir(dir)
      self.names.sort()
      for n in self.names:
        self.patchargs[n] = []

    # XXX this code is too ugly
    removelater=[]
    for p in self.names:
      try:
        self.patches[p] = Patch(file(os.sep.join([dir, p])))
      except IOError, e:
        if e.errno == errno.ENOENT and self.style == "dpatch":
          try:
            self.patches[p] = Patch(file(os.sep.join([dir, p+".dpatch"])))
          except:
            #print "ERROR: could not find patch",p
            self.blank()
            return
        elif e.errno == errno.EISDIR:
          #print "WARNING: directory %s in patch dir, patch list incomplete"%(p)
          removelater.append(p)
        else:
          #print "ERROR: could not find patch",p
          self.blank()
          return
    for p in removelater:
      self.names.remove(p)

class Quilt30PatchSeries (GenericPatchSeries):
  def __init__(self, tarBall):
    self.blank()
    self.style = "quilt (3.0)"
    self.tarfh = tarfile.open(tarBall, 'r:*')
    try:
      try:
        series_fh = self.tarfh.extractfile("debian/patches/debian.series")
      except KeyError:
        series_fh = self.tarfh.extractfile("debian/patches/series")
    except KeyError:
      series_fh = None

    if series_fh:
      for line in filter(None, [fn.strip() for fn in series_fh.readlines()]):
        stuff = line.split(' ')
        # skip comments
        if stuff[0][0] == "#":
          continue
        # here's the name
        name = stuff[0]
        self.names.append(name)

    # XXX to lazy eval this might be better
    for name in self.names:
      self.patches[name] = Patch(self.tarfh.extractfile("debian/patches/"+name))

class DebTarHandler:
  diff = None
  def __init__(self,fname):
    self.tarfile = fname
    self.size = os.stat(fname)[stat.ST_SIZE]

  def series(self):
    return Quilt30PatchSeries(self.tarfile)

class DiffGzException(Exception):
  pass

class DiffGzHandler:
  diff = None
  def __init__(self,fname):
    self.diff = fname
    self.size = os.stat(fname)[stat.ST_SIZE]

  def filterdiff(self, include=None, exclude=None):
    cmd = ["filterdiff","-z","-p","1"]
    if include:
      cmd += [ "-i", include]
    elif exclude:
      cmd += [ "-x", exclude]
    else:
      raise Exception("DiffGzHandler.filterdiff called w/o include/exclude")
    i,o,e=os.popen3(cmd+[self.diff])
    i.close()
    p = Patch(o)
    err = e.read()
    if len(err):
      raise DiffGzException("filterdiff gave errors: "+err)
    return p

  def debiandir(self):
    return self.filterdiff(include='debian/*')

  def nondebiandir(self):
    return self.filterdiff(exclude='debian/*')

  def series(self):
    patches = None
    embedded = self.filterdiff(include='debian/patches*')

    # XXX *cough* cache *cough*
    if embedded.lines():
      td = tempfile.mkdtemp()
      i,o,e=os.popen3("patch -d %s -p3"%(td))
      o.close()
      i.write(str(embedded))
      i.close()
      err = e.read()
      if len(err):
        raise Exception("unable to extract series patches:\n"+err)
      patches = PatchSeries(td)
      os.system("rm -rf %s"%(td))

    return patches
  
if __name__ == "__main__":
  print "Patch.py testing"
  try:
    p = Patch(file(sys.argv[1]))
    print "patch contents:"
    print p
  except IndexError:
    print "usage: %s <patch>"