summaryrefslogtreecommitdiff
path: root/lib/tasks/gitlab/web_hook.rake
blob: f467cc0ee29f53419b40f8ebe334fb4abbcc045d (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
namespace :gitlab do
  namespace :web_hook do
    desc "GitLab | Adds a webhook to the projects"
    task :add => :environment do
      web_hook_url = ENV['URL']
      namespace_path = ENV['NAMESPACE']

      projects = find_projects(namespace_path)

      puts "Adding webhook '#{web_hook_url}' to:"
      projects.find_each(batch_size: 1000) do |project|
        print "- #{project.name} ... "
        web_hook = project.hooks.new(url: web_hook_url)
        if web_hook.save
          puts "added".color(:green)
        else
          print "failed".color(:red)
          puts "  [#{web_hook.errors.full_messages.to_sentence}]"
        end
      end
    end

    desc "GitLab | Remove a webhook from the projects"
    task :rm => :environment do
      web_hook_url = ENV['URL']
      namespace_path = ENV['NAMESPACE']

      projects = find_projects(namespace_path)
      projects_ids = projects.pluck(:id)

      puts "Removing webhooks with the url '#{web_hook_url}' ... "
      count = WebHook.where(url: web_hook_url, project_id: projects_ids, type: 'ProjectHook').delete_all
      puts "#{count} webhooks were removed."
    end

    desc "GitLab | List webhooks"
    task :list => :environment do
      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

      puts "\n#{web_hooks.size} webhooks found."
    end
  end

  def find_projects(namespace_path)
    if namespace_path.blank?
      Project
    elsif namespace_path == '/'
      Project.in_namespace(nil)
    else
      namespace = Namespace.where(path: namespace_path).first
      if namespace
        Project.in_namespace(namespace.id)
      else
        puts "Namespace not found: #{namespace_path}".color(:red)
        exit 2
      end
    end
  end
end