Module: Cyclid::API::Plugins::ApiExtension::GithubMethods::PullRequest

Included in:
Cyclid::API::Plugins::ApiExtension::GithubMethods
Defined in:
app/cyclid/plugins/api/github/pull_request.rb

Overview

Handle a Pull Request event

Instance Method Summary collapse

Instance Method Details

#event_pull_request(config) ⇒ Object

Handle a Github Pull Request event



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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'app/cyclid/plugins/api/github/pull_request.rb', line 31

def event_pull_request(config)
  # Safely load the JSON event data
  @payload = parse_request_body
  Cyclid.logger.debug "hook payload=#{@payload.inspect}"

  # Do we know what to do with this action?
  action = @payload['action'] || nil

  Cyclid.logger.debug "action=#{action}"
  return true unless action == 'opened' \
                  or action == 'reopened' \
                  or action == 'synchronize'

  # Get the list of files in the root of the repository in the
  # Pull Request branch
  clone_url = URI(pr_head_url)

  # Get the authentication key
  auth_token = find_oauth_token(config, clone_url)

  return_failure(400, "can not find a valid OAuth token for #{clone_url}") \
    if auth_token.nil?

  # Create an Octokit client
  @client = Octokit::Client.new(access_token: auth_token)

  # Set the PR to 'pending'
  @client.create_status(pr_repository, pr_sha, 'pending',
                        context: 'Cyclid', description: 'Preparing build')

  # Get the Pull Request
  tree = @client.tree(pr_repository, pr_sha, recursive: false)
  Cyclid.logger.debug "tree=#{tree.to_hash}"

  # Find the Cyclid job file (if it exists)
  job_sha, job_type = find_job_file(tree)
  Cyclid.logger.debug "job_sha=#{job_sha}"

  if job_sha.nil?
    @client.create_status(pr_repository, pr_sha, 'error',
                          context: 'Cyclid', description: 'No Cyclid job file found')

    return_failure(400, 'not a Cyclid repository')
  end

  # Get the job file
  begin
    job_definition = load_job_file(pr_repository, job_sha, job_type)

    # Insert this repository & branch into the sources
    clone_source = normalize(clone_url.to_s)
    clone_source['type'] = 'git'
    clone_source['branch'] = pr_ref
    clone_source['token'] = auth_token

    # We need to avoid causing a collision between the PR source
    # (which may be from a forked repo) and any source definitions
    # which may exist in the job file (which may be the "base"
    # repository.
    #
    # Compare everything and try to match any duplicates, and
    # flatten the sources.
    job_sources = insert_or_update_source(job_definition['sources'] || [], clone_source)
    job_definition['sources'] = job_sources

    Cyclid.logger.debug "sources=#{job_definition['sources']}"
  rescue StandardError => ex
    Cyclid.logger.error "failed to retrieve Github Pull Request job: #{ex}"

    @client.create_status(pr_repository, pr_sha, 'error',
                          context: 'Cyclid',
                          description: "Couldn't retrieve Cyclid job file")
    return_failure(400, 'not a Cyclid repository')
  end

  Cyclid.logger.debug "job_definition=#{job_definition}"

  begin
    # Retrieve the plugin configuration
    plugins_config = Cyclid.config.plugins
    github_config = load_github_config(plugins_config)

    ui_url = github_config[:ui_url]
    linkback_url = "#{ui_url}/#{organization_name}"

    # Inject some useful context data
    ctx = { github_event: 'pull_request',
            github_user: pull_request['user']['login'],
            github_ref: pr_ref,
            github_comment: pull_request['title'],
            github_owner: pr_repository.owner,
            github_repository: pr_repository.name,
            github_number: pr_number }

    callback = GithubCallback.new(auth_token, pr_repository, pr_sha, linkback_url)
    job_from_definition(job_definition, callback, ctx)
  rescue NotFoundError
    @client.create_status(pr_repository, pr_sha, 'error',
                          context: 'Cyclid',
                          description: 'The Organization does not exist')

    return_failure(404, 'organization does not exist')
  rescue InvalidObjectError
    @client.create_status(pr_repository, pr_sha, 'error',
                          context: 'Cyclid',
                          description: 'The Job definition contains errors')

    return_failure(400, 'job definition contains errors')
  rescue InternalError
    @client.create_status(pr_repository, pr_sha, 'error',
                          context: 'Cyclid', description: 'An Internal Error occurred')

    return_failure(4500, "internal error: #{ex}")
  rescue StandardError
    @client.create_status(pr_repository, pr_sha, 'error',
                          context: 'Cyclid', description: 'An unknown error occurred')

    return_failure(500, 'job failed')
  end

  return true
end

#insert_or_update_source(sources, new_source) ⇒ Object

Either insert (append) the Pull Request head repository, or replace an existing definition; for example if the job contains a source definition for “github.com/foo/bar” and the PR head is “github.com/baz/bar”, replace “foo/bar” with “baz/bar”



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'app/cyclid/plugins/api/github/pull_request.rb', line 159

def insert_or_update_source(sources, new_source)
  updated = false
  new_uri = URI.parse(new_source['url'])

  normalized = sources.map do |source|
    uri = URI.parse(source['url'])
    next unless uri.scheme =~ /\Ahttps?\z/

    # If the "humanish" components match, use the new definition.
    if humanish(uri) == humanish(new_uri)
      updated = true
      new_source
    else
      source
    end
  end

  # If we didn't update an existing source definition, insert the new one
  normalized << new_source unless updated

  normalized.compact
end