Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/lib/patchwork.rb
blob: 835d747c4d88cb697a3d837ce32a7c7a27df4eb1 (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
# encoding: utf-8
#--
#   Author: Sascha Silbe
#
#   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/>.
#++

require 'digest/sha1'
require 'xmlrpc/client'

module Patchwork
  def notify_patchwork(repository, branch, events)
    return unless GitoriousConfig["patchwork"].has_key? repository.project.slug
    config = GitoriousConfig["patchwork"][repository.project.slug]
    return unless config["repositories"].include? repository.name

    git = repository.git.git
    server = XMLRPC::Client.new2(config["url"])
    patchwork = XMLRPC::Client::Proxy.new(server, "", [], :call, "")

    if @@cache.has_key? repository.project.slug
      project_id, find_state_ids, set_state_id = @@cache[repository.project.slug]
    else
      project_id = find_project patchwork, config["linkname"]
      find_state_ids = config["find_states"].map { |name| find_state patchwork, name }
      set_state_id = find_state patchwork, config["set_state"]
      @@cache[repository.project.slug] = project_id, find_state_ids, set_state_id
    end

    events.each do |event|
      commit_id = event.commit_details[:id]
      patch_hash = hash_patch(git.show({}, commit_id))

      begin
        patch_id = find_patch patchwork, project_id, patch_hash, find_state_ids
        if patch_id.nil?
          logger.info "No (single) matching patch for commit #{commit_id} found on Patchwork"
          next
        end
        update_patch patchwork, patch_id, commit_id, set_state_id
        logger.info "Updated patchwork patch #{patch_id}"
      rescue Exception => e
        logger.warn("Failed to update Patchwork: #{e}")
      end
    end
  end

  private

  @@cache = {}

  def find_project(patchwork, project_name)
    projects = patchwork.project_list project_name, 0
    entry = projects.find { |entry| entry['linkname'] == project_name }
    entry['id']
  end

  def find_patch(patchwork, project_id, hash, find_state_ids)
    patches = patchwork.patch_list "project_id"=>project_id, "hash"=>hash
    matches = patches.select { |entry| find_state_ids.include?(entry['state_id']) }
    logger.info("Found multiple matches: #{matches}") if matches.size > 1
    return nil if matches.size != 1
    matches[0]['id']
  end

  def find_state(patchwork, name)
    states = patchwork.state_list name, 0
    entry = states.find { |entry| entry['name'] == name }
    entry['id']
  end

  def update_patch(patchwork, patch_id, commit_id, state_id)
    if !patchwork.patch_set patch_id, "state"=>state_id, "commit_ref"=>commit_id
      raise "Failed to update patch \##{patch_id} from commit #{commit_id}"
    end
  end

  _HUNK_PATTERN = /^\@\@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? \@\@/
  _FILENAME_PATTERN = /^(---|\+\+\+) (\S+)/
  def hash_patch(patch)
    # logic taken from Patchwork
    patch = patch.gsub(/\r/, '').strip! + "\n"
    hash = Digest::SHA1.new
    found_first_hunk = false
    hunk_header = ''

    patch.split("\n").each do |line|
      next if line.empty?
      if filename_match = _FILENAME_PATTERN.match(line)
        # normalise -p1 top-directories
        filename = if filename_match[1] == '---'
            'a/'
        else
            'b/'
        end
        filename += filename_match[2].split('/')[1..-1].join('/')
        line = filename_match[1] + ' ' + filename
        hunk_header += line + "\n"

      elsif hunk_match = _HUNK_PATTERN.match(line)
        if !found_first_hunk
          hash = Digest::SHA1.new.update(hunk_header)
          found_first_hunk = true
        end
        # remove line numbers, but leave line counts
        line_nos = hunk_match[1..-1].each { |x| x ? x.to_i : 1 }
        line = '@@ -%d +%d @@' % line_nos

      elsif not found_first_hunk
        hunk_header = ''
        next

      elsif not line =~ /^[ +-]/
        # if we have a +, - or context line, leave as-is
        # other lines are ignored
        next
      end

      hash.update(line + "\n")
    end

    hash.hexdigest
  end

end