summaryrefslogtreecommitdiff
path: root/db/migrate/20150601043222_migrate_jobs_to_yaml.rb
blob: 19533b3eaa288bbec996ce7d5b4a091071735e26 (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
66
67
68
# Migration tested on MySQL and PostgreSQL.
# Can be performed online without errors.
# This migration will loop through all projects and jobs, so it can take some time.

class MigrateJobsToYaml < ActiveRecord::Migration
  def up
    select_all("SELECT * FROM projects").each do |project|
      config = {jobs: [], deploy_jobs: []}

      concatenate_expression = if ActiveRecord::Base.connection.adapter_name == 'PostgreSQL' 
                                 "string_agg(tags.name, ',')"
                               else
                                 "GROUP_CONCAT(tags.name SEPARATOR ',')"
                               end

      sql = "SELECT j.*, #{concatenate_expression} tags
        FROM jobs j
          LEFT JOIN taggings tgs ON j.id = tgs.taggable_id AND tgs.taggable_type = 'Job'
          LEFT JOIN tags ON tgs.tag_id = tags.id
        WHERE project_id = #{project['id']}
          AND active = true
          AND job_type = 'parallel'
        GROUP BY j.id"

      # Create Jobs
      select_all(sql).each do |job|
        config[:jobs] << {
          script: job["commands"].split("\n").map(&:strip),
          name: job["name"],
          branches: parse_boolean_value(job["build_branches"]),
          tags: parse_boolean_value(job["build_tags"]),
          runner: job["tags"]
        }
      end

      # Create Deploy Jobs
      select_all(sql.sub("parallel", 'deploy')).each do |job|
        config[:deploy_jobs] << {
          script: job["commands"].split("\n").map(&:strip),
          name: job["name"],
          refs: job["refs"],
          runner: job["tags"]
        }
      end

      config[:skip_refs] = project["skip_refs"]

      yaml_config = YAML.dump(config.deep_stringify_keys)

      yaml_config.sub!("---", "# This file is generated by GitLab CI")

      # Convert array of scripts to multiline string
      yaml_config.gsub!("  -", "   ").gsub!("script:", "script: |")

      execute("UPDATE projects SET generated_yaml_config = '#{quote_string(yaml_config)}' WHERE projects.id = #{project["id"]}")
    end
  end

  def down

  end

  private

  def parse_boolean_value(value)
    [ true, 1, '1', 't', 'T', 'true', 'TRUE', 'on', 'ON' ].include?(value)
  end
end