aboutsummaryrefslogtreecommitdiff
blob: 5782ff5fdda623ccaed7c307adb7344ff3c9bf5c (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
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
# Gentoo centric plugin for rbot
# Copyright (c) 2008 Mark Loeser <mark@halcy0n.com>
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU Affero General Public License as
#  published by the Free Software Foundation, either version 3 of the
#  License, or (at your option) any later version.
#
#  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 Affero General Public License for more details.
#
#  You should have received a copy of the GNU Affero General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.

# This does not always actually get run!
#class Hash
#  def grep(key)
#    keys = self.keys.grep(key)
#    result = {}
#    keys.each do |k| 
#      result[k] = self[k]
#      #warning("#{k} => #{self[k]}")
#    end
#    return result
#  end
#end

#VALID_PACKAGE_SRC = "http://tinderbox.dev.gentoo.org/misc/qsearch.txt"
#GLSA_SRC = "http://www.gentoo.org/security/en/glsa/glsa-@GLSA_ID@.xml?passthru=1"
VALID_PACKAGE_SRC = "/dev/shm/qsearch.txt"
GLSA_SRC = "#{ENV['PORTDIR']}/metadata/glsa/glsa-@GLSA_ID@.xml"
PROJECTS_SRC = 'https://api.gentoo.org/metastructure/projects.xml'
PGO_RESOLVE_URI = 'https://packages.gentoo.org/packages/resolve.json?atom=%s'
PGO_DATA_URI = 'https://packages.gentoo.org/packages/%s.json'

class GentooPlugin < Plugin
  Config.register Config::StringValue.new('gentoo.scriptdir',
    :requires_rescan => true,
    :desc => "Directory for finding external scripts.")
  Config.register Config::StringValue.new('gentoo.python',
    :requires_rescan => true,
    :desc => "Patch to Python binary")

  def scriptdir
    sd = @bot.config['gentoo.scriptdir']
    sd = "@BOTCLASS@/gentoo-scripts" unless sd
    sd.sub!('@BOTCLASS@', @bot.botclass)
    return sd
  end

  def python
    py = @bot.config['gentoo.python']
    py = '/usr/bin/python' unless py
    return py
  end

  def pgo_resolve(atom)
    uri = PGO_RESOLVE_URI % [URI.escape(atom, '\W+')]
    res = @bot.httputil.get(uri)
    return JSON.parse(res)
  end

  def pgo_resolve_one(m, atom)
    pkgs = pgo_resolve(atom)['packages']
    if pkgs.empty?
      m.reply "No matching packages for '#{atom}'"
    elsif pkgs.length > 1
      m.reply "Ambiguous name '#{atom}'. Possible options: #{pkgs.map{ |x| x['atom'] }.sort.join(' ')}"
    else
      return pkgs[0]
    end

    return nil
  end

  def pgo_get(m, atom)
    pkg = pgo_resolve_one(m, atom)
    return if pkg.nil?

    uri = PGO_DATA_URI % [pkg['atom']]
    res = @bot.httputil.get(uri)
    return JSON.parse(res)
  end

  def meta_print(m, pkg)
    # TODO: handle description?
    maints = pkg['maintainers'].map{|x| x['email'].chomp('@gentoo.org')}.join(', ')
    maints = '(none)' if maints.empty?

    m.reply "#{pkg['atom']}; maintainers: #{maints}"
  end

  def meta(m, params)
    atom = params[:pkg]
    pkg = pgo_get(m, atom)
    return if pkg.nil?

    meta_print(m, pkg)
  end

  def validpkg(m, params)
    atom = params[:pkg]
    pkg = pgo_resolve_one(m, atom)
    return if pkg.nil?
    m.reply "#{atom} => #{pkg['atom']} is valid"
  end

  def meta_verbose(m, params)
    atom = params[:pkg]
    pkg = pgo_get(m, atom)
    return if pkg.nil?

    meta_print(m, pkg)
    pkg['maintainers'].each { |maint|
      return if maint['type'] != 'project'
      debug("meta -v calling proj for #{maint['email']}")
      p = params.clone
      p[:project] = maint['email']
      project(m, p)
    }
  end

  def changelog(m, params)
    cp = params[:pkg]
    cp = validate_package(m, cp)
    return if cp.nil?
    f = IO.popen("#{python} #{scriptdir}/changelog.py '#{cp}'")
    m.reply "#{f.readlines}"
    f.close
  end

  def devaway(m, params)
    dev = params[:dev].downcase
    res = @bot.httputil.get("http://dev.gentoo.org/devaway/index-csv.php?who=#{dev}")
    if res.length > 0 then
      m.reply "#{dev}: #{res}"
    else
      m.reply "#{dev} has no devaway!"
    end
  end

  def initialize
    super
    @@cached = {}
    @@cached['projects'] = [0, nil]
    @@cached['pkgindex'] = [0, nil]
    @@cached['alias'] = [0, nil]
  end

  def project(m, params)
    now = Time.now.tv_sec
    unless @@cached['projects'] and @@cached['projects'][0] > now-600
      #m.reply "Fetch #{@@cached['projects'][0]} > #{now-600}"
      res = @bot.httputil.get(PROJECTS_SRC)
      projects = REXML::Document.new(res)
      @@cached['projects'] = [now, projects]
    else
      #m.reply "Cache #{@@cached['projects'][0]} > #{now-600}"
      projects = @@cached['projects'][1]
    end

    req_project = params[:project]
    unless req_project.include?('@')
      req_project += '@gentoo.org'
    end

    # Parse data
    # xpath queries with REXML appear to be extremely slow, which is why we took the approach below
    def expand_project_recursively(projects, proj_email)
      project = nil
      projects.elements[1].each_element { |elem|
        if elem.get_elements('email')[0].text == proj_email
          project = elem
          break
        end }

      if project
        emails = []
        for maintainer in project.get_elements("member")
          emails << maintainer.get_elements('email')[0].text.chomp('@gentoo.org')
        end
        for subproject in project.get_elements("subproject")
          if subproject.attributes["inherit-members"] == "1"
            sub_emails = expand_project_recursively(projects,
                subproject.attributes["ref"])
            if sub_emails.nil?
              emails << "<#{subproject.attributes["ref"]}>"
            else
              emails += sub_emails
            end
          end
        end
        return emails
      else
        return nil
      end
    end
    emails = expand_project_recursively(projects, req_project)

    if emails.nil?
      m.reply "No such project: #{req_project}"
    elsif emails.empty?
      m.reply "(#{req_project}) [no members]"
    else
      m.reply "(#{req_project}) #{emails.sort.uniq.join(', ')}"
    end
  end

  def expand_alias(m, params)
    now = Time.now.tv_sec
    unless @@cached['alias'] and @@cached['alias'][0] > now-600
      #m.reply "Fetch #{@@cached['alias'][0]} > #{now-600}"
      #res = @bot.httputil.get('http://dev.gentoo.org/~solar/.alias')
      res = @bot.httputil.get('http://dev.gentoo.org/.alias.cache')
      alias_hash = {}
      for line in res
        split_line = line.split(' = ')
        alias_hash[split_line[0]] = split_line[1]
      end
      @@cached['alias'] = [now, alias_hash]
    else
      #m.reply "Cache #{@@cached['alias'][0]} > #{now-600}"
      alias_hash = @@cached['alias'][1]
    end

    m.reply "#{params[:alias]} = #{alias_hash[params[:alias]]}"
  end

  def glsa(m, params)
    source = GLSA_SRC.sub('@GLSA_ID@', params[:glsa_id])
    res = fetch_file_or_url(source)
    if res
      glsa_body = REXML::Document.new(res)
      refs = nil
      for ref in glsa_body.get_elements('/glsa/references/uri')
        if refs.nil?
          refs = ''
          refs << ref.text
        else
          refs << ', ' << ref.text
        end
      end
      m.reply "#{glsa_body.get_elements("/glsa/title")[0].text} #{refs}"
    else
      m.reply "Unable to find GLSA #{params[:glsa_id]}"
    end
  end

  def glsa_search(m, params)
    m.reply 'TODO'
  end
  
  def fetch_file_or_url(f)
    if (f =~ /^http/) == 0
      return @bot.httputil.get(f)
    else
      return File.read(f)
    end
  end

  def get_pkgindex(m)
    now = Time.now.tv_sec
    #m.reply "In validate_package"
    @@cached['pkgindex'] = [0, nil] unless
    unless @@cached.key?('pkgindex') and @@cached['pkgindex'][0] > now-600
      #m.reply "Fetch #{@@cached['pkgindex'][0]} > #{now-600}"
      pkgindex_a = fetch_file_or_url(VALID_PACKAGE_SRC).split("\n")
      pkgindex = {}
      pkgindex_a.each do |pkg|
        cp, desc = pkg.split(' ', 2)
        pkgindex[cp] = desc
      end
      @@cached['pkgindex'] = [now, pkgindex]
    else
      #m.reply "Cache #{@@cached['pkgindex'][0]} > #{now-600}"
      pkgindex = @@cached['pkgindex'][1]
    end
    return pkgindex
  end

  def validate_package(m, pn)
    begin
      pkgindex = get_pkgindex(m)

      pn = pn.gsub('+','\\\+')
      rx = (pn =~ /\//) ? /^#{pn}$/ : /\/#{pn}$/

      packages = pkgindex.keys.grep(rx)

      case packages.length
      when 1
        return packages[0]
      when 0
        m.reply "No matching packages for '#{pn}'."
        return nil
      else
        m.reply "Ambiguous name '#{pn}'. Possible options: #{packages.join(' ')}"
        return nil
      end
    rescue ::Exception => e
      m.reply e.message
    end
  end

  def depcommon(m, type, url, params)
    cp = params[:pkg]
    cp = validate_package(m, cp)
    return if cp.nil?

    # Watch out for network problems
    begin
      packages = @bot.httputil.get(url+cp)
    rescue ::Exception => e
      m.reply e.message
      return
    end

    # 404 error => nil response
    packages = '' if packages.nil?

    # Only then can we split it
    packages = packages.split("\n")

    if packages.length == 0
      m.reply "No packages have a reverse #{type} on #{cp}."
    elsif packages.join(' ').length > 400
      m.reply "Too many packages have reverse #{type} on #{cp}, go to #{url+cp} instead."
    else
      m.reply "Reverse #{type} for #{cp}: #{packages.join(' ')}"
    end
  end

  def ddep(m, params)
    depcommon(m, 'DEPEND', 'http://qa-reports.gentoo.org/output/genrdeps/dindex/', params)
  end

  def pdep(m, params)
    depcommon(m, 'PDEPEND', 'http://qa-reports.gentoo.org/output/genrdeps/pindex/', params)
  end

  def rdep(m, params)
    depcommon(m, 'RDEPEND', 'http://qa-reports.gentoo.org/output/genrdeps/rindex/', params)
  end

  def earch(m, params)
    cp = params[:pkg]
    cp = validate_package(m, cp)
    return if cp.nil?
    f = IO.popen("#{python} #{scriptdir}/earch --nocolor --quiet -c '#{cp}'")
    output = f.readlines
    f.close
    if output[0] =~ /^!!!/
      m.reply "Unable to find package #{cp}"
      return
    end
    output[0].gsub!(/^.*#{cp}/,cp)
    output.map!{ |l| l.gsub(/^#{cp}-/,'').chomp }
    m.reply "#{cp} #{output.join(' ')}"
  end

  @@help_gentoo = {
    "gentoo" => "Available commands: #{Bold}meta#{Bold}, #{Bold}changelog#{Bold}, #{Bold}devaway#{Bold}, #{Bold}proj#{Bold}, #{Bold}expn#{Bold}, #{Bold}glsa#{Bold}, #{Bold}earch#{Bold}, #{Bold}rdep#{Bold}, #{Bold}ddep#{Bold}, #{Bold}pdep#{Bold}",
    "meta" => [
            "meta #{Bold}[cat/]package#{Bold} : Print metadata for the given package",
            "meta -v #{Bold}[cat/]package#{Bold} : Print metadata for the given package and the members of the maintaining projects.",
            ].join("\n"),
    "changelog" => "changelog #{Bold}[cat/]package#{Bold} : Produce changelog statistics for a given package",
    "devaway" => "devaway #{Bold}devname|list#{Bold} : Print the .away for a developer (if any). Using 'list' shows the developers who are away.",
    "proj" => "proj #{Bold}project-email#{Bold} : Print the members of a project.",
    "expn" => "expn #{Bold}alias#{Bold} : Print the addresses on a Gentoo mail alias.",
    "glsa" => [
            "glsa #{Bold}GLSA-ID#{Bold} : Prints the title and reference IDs for a given GLSA.",
            "glsa -s #{Bold}[cat/]package#{Bold} : Prints all GLSA IDs for a given package.",
            ].join("\n"),
    "earch" => "earch #{Bold}[cat/]package#{Bold} : Prints the versions and effective keywords for a given package.",
    "rdep" => "rdep #{Bold}[cat/]package#{Bold} : Prints the reverse RDEPENDs for a given package.",
    "ddep" => "ddep #{Bold}[cat/]package#{Bold} : Prints the reverse DEPENDS for a given package.",
    "pdep" => "pdep #{Bold}[cat/]package#{Bold} : Prints the reverse PDEPENDs for a given package.",
  }


  def help(plugin, topic = "")
    cmd = plugin
    cmd += " "+topic if topic.length > 0
    if @@help_gentoo.has_key?(cmd)
      return @@help_gentoo[cmd]
    else
      return @@help_gentoo['gentoo']
    end
  end
end

plugin = GentooPlugin.new

plugin.default_auth( 'modify', false )
plugin.default_auth( 'view', true )

REGEX_CP = /^(?:[-[:alnum:]]+\/)?[-+_[:alnum:]]+$/
REGEX_DEV = /^[-_[:alnum:]]+$/
REGEX_PROJECT = /^[-_@.[:alnum:]]+$/
REGEX_GLSA = /^[-1234567890]+$/

plugin.map 'meta -v :pkg',
  :requirements => {
    :pkg => REGEX_CP,
  },
  :action => 'meta_verbose',
  :thread => 'yes',
  :auth_path => 'view'

plugin.map 'meta :pkg',
  :requirements => {
    :pkg => REGEX_CP,
  },
  :action => 'meta',
  :thread => 'yes',
  :auth_path => 'view'

plugin.map 'validpkg :pkg',
  :requirements => {
    :pkg => REGEX_CP,
  },
  :action => 'validpkg',
  :auth_path => 'view'

plugin.map 'changelog :pkg',
  :requirements => {
    :pkg => REGEX_CP,
  },
  :action => 'changelog',
  :thread => 'yes',
  :auth_path => 'view'

plugin.map 'devaway :dev',
  :requirements => {
    :dev => REGEX_DEV,
  },
  :action => 'devaway',
  :thread => 'yes',
  :auth_path => 'view'

plugin.map 'away :dev',
  :requirements => {
    :dev => REGEX_DEV,
  },
  :action => 'devaway',
  :thread => 'yes',
  :auth_path => 'view'

plugin.map 'proj :project',
  :requirements => {
    :project => REGEX_PROJECT,
  },
  :action => 'project',
  :thread => 'yes',
  :auth_path => 'view'

plugin.map 'expn :alias',
  :requirements => {
    :alias => REGEX_DEV,
  },
  :action => 'expand_alias',
  :thread => 'yes',
  :auth_path => 'view'

plugin.map 'glsa :glsa_id',
  :requirements => {
    :alias => REGEX_GLSA,
  },
  :action => 'glsa',
  :thread => 'yes',
  :auth_path => 'view'

plugin.map 'glsa -s :text',
  :requirements => {
    :text => /^[^ ]+$/,
  },
  :action => 'glsa_search',
  :thread => 'yes',
  :auth_path => 'view'

plugin.map 'ddep :pkg',
  :requirements => {
    :pkg => REGEX_CP,
  },
  :action => 'ddep',
  :thread => 'yes',
  :auth_path => 'view'

plugin.map 'pdep :pkg',
  :requirements => {
    :pkg => REGEX_CP,
  },
  :action => 'pdep',
  :thread => 'yes',
  :auth_path => 'view'

plugin.map 'rdep :pkg',
  :requirements => {
    :pkg => REGEX_CP,
  },
  :action => 'rdep',
  :thread => 'yes',
  :auth_path => 'view'

plugin.map 'earch :pkg',
  :requirements => {
    :pkg => REGEX_CP,
  },
  :action => 'earch',
  :thread => 'yes',
  :auth_path => 'view'

# vim: ft=ruby ts=2 sts=2 et: