To check out this repository please hg clone the following URL, or open the URL using EasyMercurial or your preferred Mercurial client.

Statistics Download as Zip
| Branch: | Tag: | Revision:

root / lib / redmine / scm / adapters / git_adapter.rb @ 912:5e80956cc792

History | View | Annotate | Download (13.7 KB)

1 441:cbce1fd3b1b7 Chris
# Redmine - project management software
2
# Copyright (C) 2006-2011  Jean-Philippe Lang
3 0:513646585e45 Chris
#
4
# This program is free software; you can redistribute it and/or
5
# modify it under the terms of the GNU General Public License
6
# as published by the Free Software Foundation; either version 2
7
# of the License, or (at your option) any later version.
8 441:cbce1fd3b1b7 Chris
#
9 0:513646585e45 Chris
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
13 441:cbce1fd3b1b7 Chris
#
14 0:513646585e45 Chris
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17
18
require 'redmine/scm/adapters/abstract_adapter'
19
20
module Redmine
21
  module Scm
22 245:051f544170fe Chris
    module Adapters
23 0:513646585e45 Chris
      class GitAdapter < AbstractAdapter
24 245:051f544170fe Chris
25 0:513646585e45 Chris
        # Git executable name
26 210:0579821a129a Chris
        GIT_BIN = Redmine::Configuration['scm_git_command'] || "git"
27 0:513646585e45 Chris
28 245:051f544170fe Chris
        class << self
29
          def client_command
30
            @@bin    ||= GIT_BIN
31
          end
32
33
          def sq_bin
34 909:cbb26bc654de Chris
            @@sq_bin ||= shell_quote_command
35 245:051f544170fe Chris
          end
36
37
          def client_version
38
            @@client_version ||= (scm_command_version || [])
39
          end
40
41
          def client_available
42
            !client_version.empty?
43
          end
44
45
          def scm_command_version
46
            scm_version = scm_version_from_command_line.dup
47
            if scm_version.respond_to?(:force_encoding)
48
              scm_version.force_encoding('ASCII-8BIT')
49
            end
50
            if m = scm_version.match(%r{\A(.*?)((\d+\.)+\d+)})
51
              m[2].scan(%r{\d+}).collect(&:to_i)
52
            end
53
          end
54
55
          def scm_version_from_command_line
56
            shellout("#{sq_bin} --version --no-color") { |io| io.read }.to_s
57
          end
58
        end
59
60
        def initialize(url, root_url=nil, login=nil, password=nil, path_encoding=nil)
61
          super
62 441:cbce1fd3b1b7 Chris
          @path_encoding = path_encoding.blank? ? 'UTF-8' : path_encoding
63
        end
64
65
        def path_encoding
66
          @path_encoding
67 245:051f544170fe Chris
        end
68
69 0:513646585e45 Chris
        def info
70
          begin
71
            Info.new(:root_url => url, :lastrev => lastrev('',nil))
72
          rescue
73
            nil
74
          end
75
        end
76
77
        def branches
78
          return @branches if @branches
79
          @branches = []
80 909:cbb26bc654de Chris
          cmd_args = %w|branch --no-color --verbose --no-abbrev|
81 441:cbce1fd3b1b7 Chris
          scm_cmd(*cmd_args) do |io|
82 0:513646585e45 Chris
            io.each_line do |line|
83 909:cbb26bc654de Chris
              branch_rev = line.match('\s*\*?\s*(.*?)\s*([0-9a-f]{40}).*$')
84
              bran = Branch.new(branch_rev[1])
85
              bran.revision =  branch_rev[2]
86
              bran.scmid    =  branch_rev[2]
87
              @branches << bran
88 0:513646585e45 Chris
            end
89
          end
90
          @branches.sort!
91 441:cbce1fd3b1b7 Chris
        rescue ScmCommandAborted
92
          nil
93 0:513646585e45 Chris
        end
94
95
        def tags
96
          return @tags if @tags
97 441:cbce1fd3b1b7 Chris
          cmd_args = %w|tag|
98
          scm_cmd(*cmd_args) do |io|
99 0:513646585e45 Chris
            @tags = io.readlines.sort!.map{|t| t.strip}
100
          end
101 441:cbce1fd3b1b7 Chris
        rescue ScmCommandAborted
102
          nil
103
        end
104
105
        def default_branch
106
          bras = self.branches
107
          return nil if bras.nil?
108
          bras.include?('master') ? 'master' : bras.first
109
        end
110
111
        def entry(path=nil, identifier=nil)
112
          parts = path.to_s.split(%r{[\/\\]}).select {|n| !n.blank?}
113
          search_path = parts[0..-2].join('/')
114
          search_name = parts[-1]
115
          if search_path.blank? && search_name.blank?
116
            # Root entry
117
            Entry.new(:path => '', :kind => 'dir')
118
          else
119
            # Search for the entry in the parent directory
120
            es = entries(search_path, identifier,
121
                         options = {:report_last_commit => false})
122
            es ? es.detect {|e| e.name == search_name} : nil
123
          end
124 0:513646585e45 Chris
        end
125
126 441:cbce1fd3b1b7 Chris
        def entries(path=nil, identifier=nil, options={})
127 0:513646585e45 Chris
          path ||= ''
128 441:cbce1fd3b1b7 Chris
          p = scm_iconv(@path_encoding, 'UTF-8', path)
129 0:513646585e45 Chris
          entries = Entries.new
130 441:cbce1fd3b1b7 Chris
          cmd_args = %w|ls-tree -l|
131
          cmd_args << "HEAD:#{p}"          if identifier.nil?
132
          cmd_args << "#{identifier}:#{p}" if identifier
133
          scm_cmd(*cmd_args) do |io|
134 0:513646585e45 Chris
            io.each_line do |line|
135
              e = line.chomp.to_s
136 37:94944d00e43c chris
              if e =~ /^\d+\s+(\w+)\s+([0-9a-f]{40})\s+([0-9-]+)\t(.+)$/
137 0:513646585e45 Chris
                type = $1
138 441:cbce1fd3b1b7 Chris
                sha  = $2
139 0:513646585e45 Chris
                size = $3
140
                name = $4
141 441:cbce1fd3b1b7 Chris
                if name.respond_to?(:force_encoding)
142
                  name.force_encoding(@path_encoding)
143
                end
144
                full_path = p.empty? ? name : "#{p}/#{name}"
145
                n      = scm_iconv('UTF-8', @path_encoding, name)
146
                full_p = scm_iconv('UTF-8', @path_encoding, full_path)
147
                entries << Entry.new({:name => n,
148
                 :path => full_p,
149 0:513646585e45 Chris
                 :kind => (type == "tree") ? 'dir' : 'file',
150
                 :size => (type == "tree") ? nil : size,
151 441:cbce1fd3b1b7 Chris
                 :lastrev => options[:report_last_commit] ?
152
                                 lastrev(full_path, identifier) : Revision.new
153 0:513646585e45 Chris
                }) unless entries.detect{|entry| entry.name == name}
154
              end
155
            end
156
          end
157
          entries.sort_by_name
158 441:cbce1fd3b1b7 Chris
        rescue ScmCommandAborted
159
          nil
160 0:513646585e45 Chris
        end
161
162 245:051f544170fe Chris
        def lastrev(path, rev)
163 0:513646585e45 Chris
          return nil if path.nil?
164 245:051f544170fe Chris
          cmd_args = %w|log --no-color --encoding=UTF-8 --date=iso --pretty=fuller --no-merges -n 1|
165 441:cbce1fd3b1b7 Chris
          cmd_args << rev if rev
166 245:051f544170fe Chris
          cmd_args << "--" << path unless path.empty?
167 119:8661b858af72 Chris
          lines = []
168 245:051f544170fe Chris
          scm_cmd(*cmd_args) { |io| lines = io.readlines }
169 119:8661b858af72 Chris
          begin
170
              id = lines[0].split[1]
171
              author = lines[1].match('Author:\s+(.*)$')[1]
172 245:051f544170fe Chris
              time = Time.parse(lines[4].match('CommitDate:\s+(.*)$')[1])
173 0:513646585e45 Chris
174
              Revision.new({
175
                :identifier => id,
176 441:cbce1fd3b1b7 Chris
                :scmid      => id,
177
                :author     => author,
178
                :time       => time,
179
                :message    => nil,
180
                :paths      => nil
181 245:051f544170fe Chris
                })
182 119:8661b858af72 Chris
          rescue NoMethodError => e
183 0:513646585e45 Chris
              logger.error("The revision '#{path}' has a wrong format")
184
              return nil
185
          end
186 245:051f544170fe Chris
        rescue ScmCommandAborted
187
          nil
188 0:513646585e45 Chris
        end
189
190
        def revisions(path, identifier_from, identifier_to, options={})
191 441:cbce1fd3b1b7 Chris
          revs = Revisions.new
192 909:cbb26bc654de Chris
          cmd_args = %w|log --no-color --encoding=UTF-8 --raw --date=iso --pretty=fuller --parents|
193 245:051f544170fe Chris
          cmd_args << "--reverse" if options[:reverse]
194
          cmd_args << "--all" if options[:all]
195
          cmd_args << "-n" << "#{options[:limit].to_i}" if options[:limit]
196
          from_to = ""
197
          from_to << "#{identifier_from}.." if identifier_from
198
          from_to << "#{identifier_to}" if identifier_to
199
          cmd_args << from_to if !from_to.empty?
200
          cmd_args << "--since=#{options[:since].strftime("%Y-%m-%d %H:%M:%S")}" if options[:since]
201 441:cbce1fd3b1b7 Chris
          cmd_args << "--" << scm_iconv(@path_encoding, 'UTF-8', path) if path && !path.empty?
202 0:513646585e45 Chris
203 245:051f544170fe Chris
          scm_cmd *cmd_args do |io|
204 0:513646585e45 Chris
            files=[]
205
            changeset = {}
206
            parsing_descr = 0  #0: not parsing desc or files, 1: parsing desc, 2: parsing files
207
208
            io.each_line do |line|
209 909:cbb26bc654de Chris
              if line =~ /^commit ([0-9a-f]{40})(( [0-9a-f]{40})*)$/
210 0:513646585e45 Chris
                key = "commit"
211
                value = $1
212 909:cbb26bc654de Chris
                parents_str = $2
213 0:513646585e45 Chris
                if (parsing_descr == 1 || parsing_descr == 2)
214
                  parsing_descr = 0
215
                  revision = Revision.new({
216
                    :identifier => changeset[:commit],
217 441:cbce1fd3b1b7 Chris
                    :scmid      => changeset[:commit],
218
                    :author     => changeset[:author],
219
                    :time       => Time.parse(changeset[:date]),
220
                    :message    => changeset[:description],
221 909:cbb26bc654de Chris
                    :paths      => files,
222
                    :parents    => changeset[:parents]
223 0:513646585e45 Chris
                  })
224
                  if block_given?
225
                    yield revision
226
                  else
227 441:cbce1fd3b1b7 Chris
                    revs << revision
228 0:513646585e45 Chris
                  end
229
                  changeset = {}
230
                  files = []
231
                end
232
                changeset[:commit] = $1
233 909:cbb26bc654de Chris
                unless parents_str.nil? or parents_str == ""
234
                  changeset[:parents] = parents_str.strip.split(' ')
235
                end
236 0:513646585e45 Chris
              elsif (parsing_descr == 0) && line =~ /^(\w+):\s*(.*)$/
237
                key = $1
238
                value = $2
239
                if key == "Author"
240
                  changeset[:author] = value
241
                elsif key == "CommitDate"
242
                  changeset[:date] = value
243
                end
244
              elsif (parsing_descr == 0) && line.chomp.to_s == ""
245
                parsing_descr = 1
246
                changeset[:description] = ""
247
              elsif (parsing_descr == 1 || parsing_descr == 2) \
248 441:cbce1fd3b1b7 Chris
                  && line =~ /^:\d+\s+\d+\s+[0-9a-f.]+\s+[0-9a-f.]+\s+(\w)\t(.+)$/
249 0:513646585e45 Chris
                parsing_descr = 2
250 441:cbce1fd3b1b7 Chris
                fileaction    = $1
251
                filepath      = $2
252
                p = scm_iconv('UTF-8', @path_encoding, filepath)
253
                files << {:action => fileaction, :path => p}
254 0:513646585e45 Chris
              elsif (parsing_descr == 1 || parsing_descr == 2) \
255 441:cbce1fd3b1b7 Chris
                  && line =~ /^:\d+\s+\d+\s+[0-9a-f.]+\s+[0-9a-f.]+\s+(\w)\d+\s+(\S+)\t(.+)$/
256 0:513646585e45 Chris
                parsing_descr = 2
257 441:cbce1fd3b1b7 Chris
                fileaction    = $1
258
                filepath      = $3
259
                p = scm_iconv('UTF-8', @path_encoding, filepath)
260
                files << {:action => fileaction, :path => p}
261 0:513646585e45 Chris
              elsif (parsing_descr == 1) && line.chomp.to_s == ""
262
                parsing_descr = 2
263
              elsif (parsing_descr == 1)
264
                changeset[:description] << line[4..-1]
265
              end
266 441:cbce1fd3b1b7 Chris
            end
267 0:513646585e45 Chris
268
            if changeset[:commit]
269
              revision = Revision.new({
270
                :identifier => changeset[:commit],
271 441:cbce1fd3b1b7 Chris
                :scmid      => changeset[:commit],
272
                :author     => changeset[:author],
273
                :time       => Time.parse(changeset[:date]),
274
                :message    => changeset[:description],
275 909:cbb26bc654de Chris
                :paths      => files,
276
                :parents    => changeset[:parents]
277 441:cbce1fd3b1b7 Chris
                 })
278 0:513646585e45 Chris
              if block_given?
279
                yield revision
280
              else
281 441:cbce1fd3b1b7 Chris
                revs << revision
282 0:513646585e45 Chris
              end
283
            end
284
          end
285 441:cbce1fd3b1b7 Chris
          revs
286
        rescue ScmCommandAborted => e
287
          logger.error("git log #{from_to.to_s} error: #{e.message}")
288
          revs
289 0:513646585e45 Chris
        end
290
291
        def diff(path, identifier_from, identifier_to=nil)
292
          path ||= ''
293 441:cbce1fd3b1b7 Chris
          cmd_args = []
294 0:513646585e45 Chris
          if identifier_to
295 441:cbce1fd3b1b7 Chris
            cmd_args << "diff" << "--no-color" <<  identifier_to << identifier_from
296 0:513646585e45 Chris
          else
297 441:cbce1fd3b1b7 Chris
            cmd_args << "show" << "--no-color" << identifier_from
298 0:513646585e45 Chris
          end
299 441:cbce1fd3b1b7 Chris
          cmd_args << "--" <<  scm_iconv(@path_encoding, 'UTF-8', path) unless path.empty?
300 0:513646585e45 Chris
          diff = []
301 441:cbce1fd3b1b7 Chris
          scm_cmd *cmd_args do |io|
302 0:513646585e45 Chris
            io.each_line do |line|
303
              diff << line
304
            end
305
          end
306
          diff
307 441:cbce1fd3b1b7 Chris
        rescue ScmCommandAborted
308
          nil
309 0:513646585e45 Chris
        end
310 441:cbce1fd3b1b7 Chris
311 0:513646585e45 Chris
        def annotate(path, identifier=nil)
312
          identifier = 'HEAD' if identifier.blank?
313 441:cbce1fd3b1b7 Chris
          cmd_args = %w|blame|
314
          cmd_args << "-p" << identifier << "--" <<  scm_iconv(@path_encoding, 'UTF-8', path)
315 0:513646585e45 Chris
          blame = Annotate.new
316
          content = nil
317 441:cbce1fd3b1b7 Chris
          scm_cmd(*cmd_args) { |io| io.binmode; content = io.read }
318 0:513646585e45 Chris
          # git annotates binary files
319
          return nil if content.is_binary_data?
320
          identifier = ''
321
          # git shows commit author on the first occurrence only
322
          authors_by_commit = {}
323
          content.split("\n").each do |line|
324
            if line =~ /^([0-9a-f]{39,40})\s.*/
325
              identifier = $1
326
            elsif line =~ /^author (.+)/
327
              authors_by_commit[identifier] = $1.strip
328
            elsif line =~ /^\t(.*)/
329 441:cbce1fd3b1b7 Chris
              blame.add_line($1, Revision.new(
330
                                    :identifier => identifier,
331
                                    :revision   => identifier,
332
                                    :scmid      => identifier,
333
                                    :author     => authors_by_commit[identifier]
334
                                    ))
335 0:513646585e45 Chris
              identifier = ''
336
              author = ''
337
            end
338
          end
339
          blame
340 441:cbce1fd3b1b7 Chris
        rescue ScmCommandAborted
341
          nil
342 0:513646585e45 Chris
        end
343 245:051f544170fe Chris
344 0:513646585e45 Chris
        def cat(path, identifier=nil)
345
          if identifier.nil?
346
            identifier = 'HEAD'
347
          end
348 441:cbce1fd3b1b7 Chris
          cmd_args = %w|show --no-color|
349
          cmd_args << "#{identifier}:#{scm_iconv(@path_encoding, 'UTF-8', path)}"
350 0:513646585e45 Chris
          cat = nil
351 441:cbce1fd3b1b7 Chris
          scm_cmd(*cmd_args) do |io|
352 0:513646585e45 Chris
            io.binmode
353
            cat = io.read
354
          end
355
          cat
356 441:cbce1fd3b1b7 Chris
        rescue ScmCommandAborted
357
          nil
358 0:513646585e45 Chris
        end
359 119:8661b858af72 Chris
360
        class Revision < Redmine::Scm::Adapters::Revision
361
          # Returns the readable identifier
362
          def format_identifier
363
            identifier[0,8]
364
          end
365
        end
366 245:051f544170fe Chris
367
        def scm_cmd(*args, &block)
368
          repo_path = root_url || url
369 909:cbb26bc654de Chris
          full_args = ['--git-dir', repo_path]
370 441:cbce1fd3b1b7 Chris
          if self.class.client_version_above?([1, 7, 2])
371
            full_args << '-c' << 'core.quotepath=false'
372
            full_args << '-c' << 'log.decorate=no'
373
          end
374 245:051f544170fe Chris
          full_args += args
375 909:cbb26bc654de Chris
          ret = shellout(
376
                   self.class.sq_bin + ' ' + full_args.map { |e| shell_quote e.to_s }.join(' '),
377
                   &block
378
                   )
379 245:051f544170fe Chris
          if $? && $?.exitstatus != 0
380
            raise ScmCommandAborted, "git exited with non-zero status: #{$?.exitstatus}"
381
          end
382
          ret
383
        end
384
        private :scm_cmd
385 0:513646585e45 Chris
      end
386
    end
387
  end
388
end