git_adapter.rb 12.3 KB
Newer Older
1
#-- encoding: UTF-8
2 3
#-- copyright
# ChiliProject is a project management system.
4
#
5
# Copyright (C) 2010-2011 the ChiliProject Team
6
#
7 8 9 10
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
11
#
12 13 14
# See doc/COPYRIGHT.rdoc for more details.
#++

15 16 17 18
require 'redmine/scm/adapters/abstract_adapter'

module Redmine
  module Scm
19
    module Adapters
20
      class GitAdapter < AbstractAdapter
21

22
        SCM_GIT_REPORT_LAST_COMMIT = true unless defined?(SCM_GIT_REPORT_LAST_COMMIT)
23

24
        # Git executable name
25
        GIT_BIN = Redmine::Configuration['scm_git_command'] || "git" unless defined?(GIT_BIN)
26

27 28 29
        # raised if scm command exited with error, e.g. unknown revision.
        class ScmCommandAborted < CommandFailed; end

30 31 32 33 34 35 36 37 38
        class << self
          def client_command
            @@bin    ||= GIT_BIN
          end

          def sq_bin
            @@sq_bin ||= shell_quote(GIT_BIN)
          end

39 40 41 42
          def client_version
            @@client_version ||= (scm_command_version || [])
          end

43 44
          def client_available
            !client_version.empty?
45 46 47
          end

          def scm_command_version
48
            scm_version = scm_version_from_command_line.dup
49 50 51
            if scm_version.respond_to?(:force_encoding)
              scm_version.force_encoding('ASCII-8BIT')
            end
52 53 54 55 56 57
            if m = scm_version.match(%r{\A(.*?)((\d+\.)+\d+)})
              m[2].scan(%r{\d+}).collect(&:to_i)
            end
          end

          def scm_version_from_command_line
58
            shellout("#{sq_bin} --version --no-color") { |io| io.read }.to_s
59 60 61
          end
        end

62 63
        def initialize(url, root_url=nil, login=nil, password=nil, path_encoding=nil)
          super
64
          @path_encoding = path_encoding || 'UTF-8'
65 66 67
          @flag_report_last_commit = SCM_GIT_REPORT_LAST_COMMIT
        end

68 69 70 71 72
        def info
          begin
            Info.new(:root_url => url, :lastrev => lastrev('',nil))
          rescue
            nil
73
          end
74
        end
75

76
        def branches
77 78
          return @branches if @branches
          @branches = []
79 80
          cmd_args = %w|branch --no-color|
          scm_cmd(*cmd_args) do |io|
81
            io.each_line do |line|
82
              @branches << line.match('\s*\*?\s*(.*)$')[1]
83
            end
84
          end
85
          @branches.sort!
86 87
        rescue ScmCommandAborted
          nil
88 89
        end

90
        def tags
91
          return @tags if @tags
92 93
          cmd_args = %w|tag|
          scm_cmd(*cmd_args) do |io|
94
            @tags = io.readlines.sort!.map{|t| t.strip}
95
          end
96 97
        rescue ScmCommandAborted
          nil
98 99 100
        end

        def default_branch
101
          bras = self.branches
102
          return nil if bras.nil?
103
          bras.include?('master') ? 'master' : bras.first
104
        end
105

106 107
        def entries(path=nil, identifier=nil)
          path ||= ''
108
          p = scm_iconv(@path_encoding, 'UTF-8', path)
109
          entries = Entries.new
110 111 112 113
          cmd_args = %w|ls-tree -l|
          cmd_args << "HEAD:#{p}"          if identifier.nil?
          cmd_args << "#{identifier}:#{p}" if identifier
          scm_cmd(*cmd_args) do |io|
114 115
            io.each_line do |line|
              e = line.chomp.to_s
116
              if e =~ /^\d+\s+(\w+)\s+([0-9a-f]{40})\s+([0-9-]+)\t(.+)$/
117
                type = $1
118
                sha  = $2
119 120
                size = $3
                name = $4
121 122 123
                if name.respond_to?(:force_encoding)
                  name.force_encoding(@path_encoding)
                end
124
                full_path = p.empty? ? name : "#{p}/#{name}"
125 126 127 128
                n      = scm_iconv('UTF-8', @path_encoding, name)
                full_p = scm_iconv('UTF-8', @path_encoding, full_path)
                entries << Entry.new({:name => n,
                 :path => full_p,
129 130
                 :kind => (type == "tree") ? 'dir' : 'file',
                 :size => (type == "tree") ? nil : size,
131
                 :lastrev => @flag_report_last_commit ? lastrev(full_path, identifier) : Revision.new
132
                }) unless entries.detect{|entry| entry.name == name}
133 134 135 136
              end
            end
          end
          entries.sort_by_name
137 138
        rescue ScmCommandAborted
          nil
139
        end
140

141
        def lastrev(path, rev)
142
          return nil if path.nil?
143
          cmd_args = %w|log --no-color --encoding=UTF-8 --date=iso --pretty=fuller --no-merges -n 1|
144
          cmd_args << rev if rev
145
          cmd_args << "--" << path unless path.empty?
146
          lines = []
147
          scm_cmd(*cmd_args) { |io| lines = io.readlines }
148 149 150
          begin
              id = lines[0].split[1]
              author = lines[1].match('Author:\s+(.*)$')[1]
151
              time = Time.parse(lines[4].match('CommitDate:\s+(.*)$')[1])
152 153 154 155

              Revision.new({
                :identifier => id,
                :scmid => id,
156
                :author => author,
157
                :time => time,
158 159
                :message => nil,
                :paths => nil
160
                })
161
          rescue NoMethodError => e
162 163 164
              logger.error("The revision '#{path}' has a wrong format")
              return nil
          end
165 166
        rescue ScmCommandAborted
          nil
167 168
        end

169 170
        def revisions(path, identifier_from, identifier_to, options={})
          revisions = Revisions.new
171
          cmd_args = %w|log --no-color --encoding=UTF-8 --raw --date=iso --pretty=fuller|
172 173 174 175 176 177 178
          cmd_args << "--reverse" if options[:reverse]
          cmd_args << "--all" if options[:all]
          cmd_args << "-n" << "#{options[:limit].to_i}" if options[:limit]
          from_to = ""
          from_to << "#{identifier_from}.." if identifier_from
          from_to << "#{identifier_to}" if identifier_to
          cmd_args << from_to if !from_to.empty?
179
          cmd_args << "--since='#{options[:since].strftime("%Y-%m-%d %H:%M:%S")}'" if options[:since]
180
          cmd_args << "--" << scm_iconv(@path_encoding, 'UTF-8', path) if path && !path.empty?
181

182
          scm_cmd *cmd_args do |io|
183 184 185 186 187 188 189 190 191 192
            files=[]
            changeset = {}
            parsing_descr = 0  #0: not parsing desc or files, 1: parsing desc, 2: parsing files

            io.each_line do |line|
              if line =~ /^commit ([0-9a-f]{40})$/
                key = "commit"
                value = $1
                if (parsing_descr == 1 || parsing_descr == 2)
                  parsing_descr = 0
193 194 195 196 197 198 199 200
                  revision = Revision.new({
                    :identifier => changeset[:commit],
                    :scmid => changeset[:commit],
                    :author => changeset[:author],
                    :time => Time.parse(changeset[:date]),
                    :message => changeset[:description],
                    :paths => files
                  })
201 202 203 204 205
                  if block_given?
                    yield revision
                  else
                    revisions << revision
                  end
206 207 208 209 210 211 212 213 214
                  changeset = {}
                  files = []
                end
                changeset[:commit] = $1
              elsif (parsing_descr == 0) && line =~ /^(\w+):\s*(.*)$/
                key = $1
                value = $2
                if key == "Author"
                  changeset[:author] = value
215
                elsif key == "CommitDate"
216 217 218 219 220
                  changeset[:date] = value
                end
              elsif (parsing_descr == 0) && line.chomp.to_s == ""
                parsing_descr = 1
                changeset[:description] = ""
221
              elsif (parsing_descr == 1 || parsing_descr == 2) \
222
                  && line =~ /^:\d+\s+\d+\s+[0-9a-f.]+\s+[0-9a-f.]+\s+(\w)\t(.+)$/
223
                parsing_descr = 2
224 225
                fileaction    = $1
                filepath      = $2
226 227
                p = scm_iconv('UTF-8', @path_encoding, filepath)
                files << {:action => fileaction, :path => p}
228
              elsif (parsing_descr == 1 || parsing_descr == 2) \
229
                  && line =~ /^:\d+\s+\d+\s+[0-9a-f.]+\s+[0-9a-f.]+\s+(\w)\d+\s+(\S+)\t(.+)$/
230
                parsing_descr = 2
231 232
                fileaction    = $1
                filepath      = $3
233 234
                p = scm_iconv('UTF-8', @path_encoding, filepath)
                files << {:action => fileaction, :path => p}
235 236 237 238 239
              elsif (parsing_descr == 1) && line.chomp.to_s == ""
                parsing_descr = 2
              elsif (parsing_descr == 1)
                changeset[:description] << line[4..-1]
              end
240
            end
241

242
            if changeset[:commit]
243 244 245 246 247 248 249 250 251
              revision = Revision.new({
                :identifier => changeset[:commit],
                :scmid => changeset[:commit],
                :author => changeset[:author],
                :time => Time.parse(changeset[:date]),
                :message => changeset[:description],
                :paths => files
              })

252 253 254 255 256 257
              if block_given?
                yield revision
              else
                revisions << revision
              end
            end
258
          end
259 260
          revisions
        rescue ScmCommandAborted
261 262
          revisions
        end
263

264
        def diff(path, identifier_from, identifier_to=nil)
265
          path ||= ''
266
          cmd_args = []
267
          if identifier_to
268
            cmd_args << "diff" << "--no-color" <<  identifier_to << identifier_from
269
          else
270
            cmd_args << "show" << "--no-color" << identifier_from
271
          end
272
          cmd_args << "--" <<  scm_iconv(@path_encoding, 'UTF-8', path) unless path.empty?
273
          diff = []
274
          scm_cmd *cmd_args do |io|
275 276 277 278
            io.each_line do |line|
              diff << line
            end
          end
279
          diff
280 281
        rescue ScmCommandAborted
          nil
282
        end
283

284 285
        def annotate(path, identifier=nil)
          identifier = 'HEAD' if identifier.blank?
286 287
          cmd_args = %w|blame|
          cmd_args << "-p" << identifier << "--" <<  scm_iconv(@path_encoding, 'UTF-8', path)
288
          blame = Annotate.new
289
          content = nil
290
          scm_cmd(*cmd_args) { |io| io.binmode; content = io.read }
291
          # git annotates binary files
292 293 294 295 296 297
          if content.respond_to?("is_binary_data?") && content.is_binary_data? # Ruby 1.8.x and <1.9.2
            return nil
          elsif content.respond_to?(:force_encoding) && (content.dup.force_encoding("UTF-8") != content.dup.force_encoding("BINARY")) # Ruby 1.9.2
            # TODO: need to handle edge cases of non-binary content that isn't UTF-8
            return nil
          end
298
          identifier = ''
299 300
          # git shows commit author on the first occurrence only
          authors_by_commit = {}
301
          content.split("\n").each do |line|
302 303 304
            if line =~ /^([0-9a-f]{39,40})\s.*/
              identifier = $1
            elsif line =~ /^author (.+)/
305
              authors_by_commit[identifier] = $1.strip
306
            elsif line =~ /^\t(.*)/
307 308 309
              blame.add_line($1, Revision.new(
                                    :identifier => identifier,
                                    :author => authors_by_commit[identifier]))
310 311 312
              identifier = ''
              author = ''
            end
313
          end
314
          blame
315 316
        rescue ScmCommandAborted
          nil
317
        end
318

319 320 321 322
        def cat(path, identifier=nil)
          if identifier.nil?
            identifier = 'HEAD'
          end
323 324
          cmd_args = %w|show --no-color|
          cmd_args << "#{identifier}:#{scm_iconv(@path_encoding, 'UTF-8', path)}"
325
          cat = nil
326
          scm_cmd(*cmd_args) do |io|
327 328 329 330
            io.binmode
            cat = io.read
          end
          cat
331 332
        rescue ScmCommandAborted
          nil
333
        end
334 335 336 337 338 339 340

        class Revision < Redmine::Scm::Adapters::Revision
          # Returns the readable identifier
          def format_identifier
            identifier[0,8]
          end
        end
341 342 343

        def scm_cmd(*args, &block)
          repo_path = root_url || url
344 345 346 347
          full_args = [GIT_BIN, '--git-dir', repo_path]
          if self.class.client_version_above?([1, 7, 2])
            full_args << '-c' << 'core.quotepath=false'
          end
348 349 350 351 352 353 354 355
          full_args += args
          ret = shellout(full_args.map { |e| shell_quote e.to_s }.join(' '), &block)
          if $? && $?.exitstatus != 0
            raise ScmCommandAborted, "git exited with non-zero status: #{$?.exitstatus}"
          end
          ret
        end
        private :scm_cmd
356 357 358 359
      end
    end
  end
end