PageRenderTime 42ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/app/controllers/bitbucket_hook_controller.rb

https://bitbucket.org/petersanchez/redmine-bitbucket
Ruby | 56 lines | 38 code | 14 blank | 4 comment | 6 complexity | 8641fc29f254f6d4ad100446480f8878 MD5 | raw file
  1. require 'json'
  2. class BitbucketHookController < ApplicationController
  3. skip_before_filter :verify_authenticity_token, :check_if_login_required
  4. def index
  5. payload = JSON.parse(params[:payload])
  6. logger.debug { "Received from Bitbucket: #{payload.inspect}" }
  7. # For now, we assume that the repository name is the same as the project identifier
  8. identifier = payload['repository']['name']
  9. project = Project.find_by_identifier(identifier)
  10. raise ActiveRecord::RecordNotFound, "No project found with identifier '#{identifier}'" if project.nil?
  11. repository = project.repository
  12. raise TypeError, "Project '#{identifier}' has no repository" if repository.nil?
  13. raise TypeError, "Repository for project '#{identifier}' is not a BitBucket repository" unless repository.is_a?(Repository::Mercurial) || repository.is_a?(Repository::Git)
  14. # Get updates from the bitbucket repository
  15. if repository.is_a?(Repository::Git)
  16. update_git_repository(repository)
  17. else
  18. command = "hg --repository \"#{repository.url}\" pull"
  19. exec(command)
  20. end
  21. # Fetch the new changesets into Redmine
  22. repository.fetch_changesets
  23. render(:text => 'OK')
  24. end
  25. private
  26. def exec(command)
  27. logger.info { "BitbucketHook: Executing command: '#{command}'" }
  28. output = Kernel.system("#{command}")
  29. logger.info { "BitbucketHook: Shell returned '#{output}'" }
  30. end
  31. # Taken from: https://github.com/koppen/redmine_github_hook
  32. def git_command(command, repository)
  33. "git --git-dir='#{repository.url}' #{command}"
  34. end
  35. def update_git_repository(repository)
  36. command = git_command('fetch origin', repository)
  37. if exec(command)
  38. command = git_command("fetch origin '+refs/heads/*:refs/heads/*'", repository)
  39. exec(command)
  40. end
  41. end
  42. end