BigW Consortium Gitlab

web_hook.rake 1.86 KB
Newer Older
1 2
namespace :gitlab do
  namespace :web_hook do
ashleys committed
3
    desc "GitLab | Adds a webhook to the projects"
4
    task add: :environment do
5 6 7 8 9
      web_hook_url = ENV['URL']
      namespace_path = ENV['NAMESPACE']

      projects = find_projects(namespace_path)

ashleys committed
10
      puts "Adding webhook '#{web_hook_url}' to:"
11 12 13 14
      projects.find_each(batch_size: 1000) do |project|
        print "- #{project.name} ... "
        web_hook = project.hooks.new(url: web_hook_url)
        if web_hook.save
15
          puts "added".color(:green)
16
        else
17
          print "failed".color(:red)
18 19 20 21 22
          puts "  [#{web_hook.errors.full_messages.to_sentence}]"
        end
      end
    end

ashleys committed
23
    desc "GitLab | Remove a webhook from the projects"
24
    task rm: :environment do
25 26 27 28
      web_hook_url = ENV['URL']
      namespace_path = ENV['NAMESPACE']

      projects = find_projects(namespace_path)
29
      project_ids = projects.pluck(:id)
30

ashleys committed
31
      puts "Removing webhooks with the url '#{web_hook_url}' ... "
32
      count = WebHook.where(url: web_hook_url, project_id: project_ids, type: 'ProjectHook').delete_all
ashleys committed
33
      puts "#{count} webhooks were removed."
34 35
    end

ashleys committed
36
    desc "GitLab | List webhooks"
37
    task list: :environment do
38 39 40 41 42 43 44 45
      namespace_path = ENV['NAMESPACE']

      projects = find_projects(namespace_path)
      web_hooks = projects.all.map(&:hooks).flatten
      web_hooks.each do |hook|
        puts "#{hook.project.name.truncate(20).ljust(20)} -> #{hook.url}"
      end

ashleys committed
46
      puts "\n#{web_hooks.size} webhooks found."
47 48 49 50 51 52 53
    end
  end

  def find_projects(namespace_path)
    if namespace_path.blank?
      Project
    elsif namespace_path == '/'
54
      Project.in_namespace(nil)
55 56 57
    else
      namespace = Namespace.where(path: namespace_path).first
      if namespace
58
        Project.in_namespace(namespace.id)
59
      else
60
        puts "Namespace not found: #{namespace_path}".color(:red)
61 62 63 64 65
        exit 2
      end
    end
  end
end