summaryrefslogtreecommitdiff
path: root/scripts/gerrit/cherry-pick_automation/gerritRESTTools.js
blob: 0793e9f2080cb8dc63dc35a512dce4c417c0a8b1 (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
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
/* eslint-disable no-unused-vars */
// Copyright (C) 2020 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

exports.id = "gerritRESTTools";

const axios = require("axios");
const axiosRetry = require('axios-retry');
const safeJsonStringify = require("safe-json-stringify");

const toolbox = require("./toolbox");
const config = require("./config.json");
const Logger = require("./logger");
const logger = new Logger();


axiosRetry(axios, {
  retries: 3,
  // Random delay in ms between 1 and 6 sec. Helps reduce load on gerrit.
  retryDelay: function() {Math.floor(Math.random() * 5 * 1000) + 1},
  shouldResetTimeout: true,
  retryCondition: (error) => {
    let status = error.response.status;
    let text = error.response.data;

    if (
      axiosRetry.isNetworkOrIdempotentRequestError(error)  // The default retry behavior
      || (status == 409 && text.includes("com.google.gerrit.git.LockFailureException"))
      || status == 408  // "Server Deadline Exceeded" Hit the anti-DDoS timeout threshold.
    )
      return true;
  },
});


// Set default values with the config file, but prefer environment variable.
function envOrConfig(ID) {
  return process.env[ID] || config[ID];
}

let gerritURL = envOrConfig("GERRIT_URL");
let gerritPort = envOrConfig("GERRIT_PORT");
let gerritAuth = {
  username: envOrConfig("GERRIT_USER"),
  password: envOrConfig("GERRIT_PASS")
};

// Assemble the gerrit URL, and tack on http/https if it's not already
// in the URL. Add the port if it's non-standard, and assume https
// if the port is anything other than port 80.
let gerritResolvedURL = /^https?:\/\//g.test(gerritURL)
  ? gerritURL
  : `${gerritPort == 80 ? "http" : "https"}://${gerritURL}`;
gerritResolvedURL += gerritPort != 80 && gerritPort != 443 ? ":" + gerritPort : "";

// Return an assembled url to use as a base for requests to gerrit.
function gerritBaseURL(api) {
  return `${gerritResolvedURL}/a/${api}`;
}

// Trim )]}' off of a gerrit response. This magic prefix in the response
// from gerrit helpts to prevent against XSSI attacks and will
// always be included in a genuine response from gerrit.
// See https://gerrit-review.googlesource.com/Documentation/rest-api.html
exports.trimResponse = trimResponse;
function trimResponse(response) {
  if (response.startsWith(")]}'"))
    return response.slice(4);
  else
    return response;
}

// Make a REST API call to gerrit to cherry pick the change to a requested branch.
// Splice out the "Pick-to: keyword from the old commit message, but keep the rest."
exports.generateCherryPick = generateCherryPick;
function generateCherryPick(changeJSON, parent, destinationBranch, customAuth, callback) {

  function doPick() {
    logger.log(
      `New commit message for ${changeJSON.change.branch}:\n${newCommitMessage}`,
      "verbose", changeJSON.uuid
    );
    logger.log(
      `POST request to: ${url}\nRequest Body: ${safeJsonStringify(data)}`,
      "debug", changeJSON.uuid
    );
    axios({ method: "post", url: url, data: data, auth: customAuth || gerritAuth })
      .then(function (response) {
        // Send an update with only the branch before trying to parse the raw response.
        // If the parse is bad, then at least we stored a status with the branch.
        toolbox.addToCherryPickStateUpdateQueue(
          changeJSON.uuid, { branch: destinationBranch, statusDetail: "pickCreated" },
          "validBranchReadyForPick"
        );
        let parsedResponse = JSON.parse(trimResponse(response.data));
        toolbox.addToCherryPickStateUpdateQueue(
          changeJSON.uuid,
          { branch: destinationBranch, cherrypickID: parsedResponse.id,
            statusDetail: "pickCreated" },
          "validBranchReadyForPick"
        );
        callback(true, parsedResponse);
      })
      .catch(function (error) {
        if (error.response) {
          // The server responded with a code outside of 2xx. Something's
          // actually wrong with the cherrypick request.
          logger.log(
            `An error occurred in POST to "${url}". Error ${error.response.status}: ${
              error.response.data}`,
            "error", changeJSON.uuid
          );
          callback(false, { statusDetail: error.response.data, statusCode: error.response.status });
        } else if (error.request) {
          // The server failed to respond. Try the pick later.
          callback(false, "retry");
        } else {
          // Something unexpected happened in generating the HTTP request itself.
          logger.log(
            `UNKNOWN ERROR posting cherry-pick for ${destinationBranch}: ${error}`,
            "error", changeJSON.uuid
          );
          callback(false, error.message);
        }
      }
    );
  }

  const newCommitMessage = changeJSON.change.commitMessage
    .replace(/^Pick-to:.+\s?/gm, "")
    .concat(`(cherry picked from commit ${changeJSON.patchSet.revision})`);
  let url;
  if (/^(tqtc(?:%2F|\/)lts-)/.test(changeJSON.change.branch)) {
    url = `${gerritBaseURL("projects")}/${encodeURIComponent(changeJSON.change.project)}/commits/${
      changeJSON.patchSet.revision}/cherrypick`;
  } else {
    url = `${gerritBaseURL("changes")}/${changeJSON.fullChangeID}/revisions/${
      changeJSON.patchSet.revision}/cherrypick`;
  }
  let data = {
    message: newCommitMessage, destination: destinationBranch,
    notify: "NONE", base: parent, keep_reviewers: false,
    allow_conflicts: true // Add conflict markers to files in the resulting cherry-pick.
  };

  queryChangeTopic(changeJSON.uuid, changeJSON.fullChangeID, customAuth,
    function (success, topic) {
      if (success) {
        if (topic)
          data["topic"] = topic;  // Only populate topic field if the original change had one.
        doPick();
      } else if (!success && topic == "retry") {
        callback(false, "retry");
      } else {
        // Something unexpected happened when trying to get the Topic.
        logger.log(
          `UNKNOWN ERROR querying topic for change ${changeJSON.fullChangeID}: ${error}`,
          "error", changeJSON.uuid
        );
        callback(false, error);
      }
    });
}

// Post a review to the change on the latest revision.
exports.setApproval = setApproval;
function setApproval(
  parentUuid, cherryPickJSON, approvalScore,
  message, notifyScope, customAuth, callback
) {
  let url = `${gerritBaseURL("changes")}/${cherryPickJSON.id}/revisions/current/review`;
  let data = {
    message: message || "", notify: notifyScope || "OWNER",
    labels: { "Code-Review": approvalScore, "Sanity-Review": 1 },
    omit_duplicate_comments: true, ready: true
  };
  logger.log(
    `POST request to: ${url}\nRequest Body: ${safeJsonStringify(data)}`,
    "debug", parentUuid
  );

  axios({ method: "post", url: url, data: data, auth: customAuth || gerritAuth })
    .then(function (response) {
      logger.log(
        `Successfully set approval to "${approvalScore}" on change ${cherryPickJSON.id}`,
        "verbose", parentUuid
      );
      callback(true, undefined);
    })
    .catch(function (error) {
      if (error.response) {
        // The request was made and the server responded with a status code
        // that falls out of the range of 2xx
        logger.log(
          `An error occurred in POST to "${url}". Error ${error.response.status}: ${
            error.response.data}`,
          "error", parentUuid
        );
        callback(false, error.response.status);
      } else if (error.request) {
        // The request was made but no response was received
        callback(false, "retry");
      } else {
        // Something unexpected happened in generating the HTTP request itself.
        logger.log(
          `UNKNOWN ERROR while setting approval for ${
            cherryPickJSON.id}: ${safeJsonStringify(error)}`,
          "error", parentUuid
        );
        callback(false, error.message);
      }
    });
}

// Stage a conflict-free change to Qt's CI system.
// NOTE: This requires gerrit to be extended with "gerrit-plugin-qt-workflow"
// https://codereview.qt-project.org/admin/repos/qtqa/gerrit-plugin-qt-workflow
exports.stageCherryPick = stageCherryPick;
function stageCherryPick(parentUuid, cherryPickJSON, customAuth, callback) {
  let url =`${
    gerritBaseURL("changes")}/${cherryPickJSON.id}/revisions/current/gerrit-plugin-qt-workflow~stage`;

  logger.log(`POST request to: ${url}`, "debug", parentUuid);

  setTimeout(function () {
    axios({ method: "post", url: url, data: {}, auth: customAuth || gerritAuth })
      .then(function (response) {
        logger.log(`Successfully staged "${cherryPickJSON.id}"`, "info", parentUuid);
        callback(true, undefined);
      })
      .catch(function (error) {
        if (error.response) {
        // The request was made and the server responded with a status code
        // that falls out of the range of 2xx

          // Call this a permanent failure for staging. Ask the owner to handle it.
          logger.log(
            `An error occurred in POST to "${url}". Error ${error.response.status}: ${
              error.response.data}`,
            "error", parentUuid
          );
          callback(false, { status: error.response.status, data: error.response.data });
        } else if (error.request) {
        // The request was made but no response was received. Retry it later.
          callback(false, "retry");
        } else {
        // Something happened in setting up the request that triggered an Error
          logger.log(
            `Error in HTTP request while trying to stage. Error: ${safeJsonStringify(error)}`,
            "error", parentUuid
          );
          callback(false, error.message);
        }
      });
  }, 5000);
}

// Post a comment to the change on the latest revision.
exports.postGerritComment = postGerritComment;
function postGerritComment(
  parentUuid, fullChangeID, revision, message,
  notifyScope, customAuth, callback
) {
  let url = `${gerritBaseURL("changes")}/${fullChangeID}/revisions/${
    revision || "current"}/review`;
  let data = { message: message, notify: notifyScope || "OWNER_REVIEWERS" };

  logger.log(
    `POST request to: ${url}\nRequest Body: ${safeJsonStringify(data)}`,
    "debug", parentUuid
  );

  axios({ method: "post", url: url, data: data, auth: customAuth || gerritAuth })
    .then(function (response) {
      logger.log(`Posted comment "${message}" to change "${fullChangeID}"`, "info", parentUuid);
      callback(true, undefined);
    })
    .catch(function (error) {
      if (error.response) {
        // The request was made and the server responded with a status code
        // that falls out of the range of 2xx
        logger.log(
          `An error occurred in POST (gerrit comment) to "${url}". Error ${
            error.response.status}: ${error.response.data}`,
          "error", parentUuid
        );
        callback(false, error.response);
      } else if (error.request) {
        // The request was made but no response was received
        callback(false, "retry");
      } else {
        // Something happened in setting up the request that triggered an Error
        logger.log(
          `Error in HTTP request while posting comment. Error: ${safeJsonStringify(error)}`,
          "error", parentUuid
        );
        callback(false, error.message);
      }
    });
}

// Query gerrit project to make sure a target cherry-pick branch exists.
exports.validateBranch = validateBranch;
function validateBranch (parentUuid, project, branch, customAuth, callback) {
  let url = `${gerritBaseURL("projects")}/${encodeURIComponent(project)}/branches/${
    encodeURIComponent(branch)}`;
  logger.log(`GET request to: ${url}`, "debug", parentUuid);
  axios.get(url, { auth: customAuth || gerritAuth })
    .then(function (response) {
      // Execute callback with the target branch head SHA1 of that branch.
      callback(true, JSON.parse(trimResponse(response.data)).revision);
    })
    .catch(function (error) {
      if (error.response) {
        if (error.response.status == 404) {
          // Not a valid branch according to gerrit.
          callback(
            false,
            { "status": error.response.status, "statusText": error.response.statusText }
          );
        } else {
          logger.log(
            `An error occurred in GET "${url}". Error ${error.response.status}: ${
              error.response.data}`,
            "error", parentUuid
          );
        }
      } else if (error.request) {
        // Gerrit failed to respond, try again later and resume the process.
        callback(false, "retry");
      } else {
        // Something happened in setting up the request that triggered an Error
        logger.log(
          `Error in HTTP request while requesting branch validation for ${
            branch}. Error: ${safeJsonStringify(error)}`,
          "warn", parentUuid
        );
        callback(false, error.message);
      }
    });
};

// Query gerrit commit for it's relation chain. Returns a list of changes.
exports.queryRelated = function (parentUuid, fullChangeID, customAuth, callback) {
  let url = `${gerritBaseURL("changes")}/${fullChangeID}/revisions/current/related`;
  logger.log(`GET request to: ${url}`, "debug", parentUuid);
  axios.get(url, { auth: customAuth || gerritAuth })
    .then(function (response) {
      // Execute callback and return the list of changes
      logger.log(`Raw Response:\n${response.data}`, "debug", parentUuid);
      callback(true, JSON.parse(trimResponse(response.data)).changes);
    })
    .catch(function (error) {
      if (error.response) {
        // An error here would be unexpected. Changes without related changes
        // should still return valid JSON with an empty "changes" field
        callback(false, error.response);
        logger.log(
          `An error occurred in GET "${url}". Error ${error.response.status}: ${
            error.response.data}`,
          "error", parentUuid
        );
      } else if (error.request) {
        // Gerrit failed to respond, try again later and resume the process.
        callback(false, "retry");
      } else {
        // Something happened in setting up the request that triggered an Error
        logger.log(
          `Error in HTTP request while trying to query for related changes on ${
            fullChangeID}. Error: ${safeJsonStringify(error)}`,
          "error", parentUuid
        );
        callback(false, error.message);
      }
    });
};

// Query gerrit for a change and return it along with the current revision if it exists.
exports.queryChange = function (parentUuid, fullChangeID, fields, customAuth, callback) {
  let url = `${gerritBaseURL("changes")}/${fullChangeID}/?o=CURRENT_COMMIT&o=CURRENT_REVISION`;
  // Tack on any additional fields requested
  if (fields)
    fields.forEach((field) => url = `${url}&o=${field}`);
  logger.log(`Querying gerrit for ${url}`, "debug", parentUuid);
  axios.get(url, { auth: customAuth || gerritAuth })
    .then(function (response) {
      // Execute callback and return the list of changes
      logger.log(`Raw response: ${response.data}`, "debug", parentUuid);
      callback(true, JSON.parse(trimResponse(response.data)));
    })
    .catch(function (error) {
      if (error.response) {
        if (error.response.status == 404) {
          // Change does not exist. Depending on usage, this may not
          // be considered an error, so only write an error trace if
          // a status other than 404 is returned.
          callback(false, { statusCode: 404 });
        } else {
          // Some other error was returned
          logger.log(
            `An error occurred in GET "${url}". Error ${error.response.status}: ${
              error.response.data}`,
            "error", parentUuid
          );
          callback(false, { statusCode: error.response.status, statusDetail: error.response.data });
        }
      } else if (error.request) {
        // Gerrit failed to respond, try again later and resume the process.
        callback(false, "retry");
      } else {
        // Something happened in setting up the request that triggered an Error
        logger.log(
          `Error in HTTP request while trying to query ${fullChangeID}. ${error}`,
          "error", parentUuid
        );
        callback(false, error.message);
      }
    });
};

// Query gerrit for a change's topic
exports.queryChangeTopic = queryChangeTopic
function queryChangeTopic(parentUuid, fullChangeID, customAuth, callback) {
  let url = `${gerritBaseURL("changes")}/${fullChangeID}/topic`;
  logger.log(`Querying gerrit for ${url}`, "debug", parentUuid);
  axios.get(url, { auth: customAuth || gerritAuth })
    .then(function (response) {
      logger.log(`Raw response: ${response.data}`, "debug", parentUuid);
       // Topic responses are always double-quoted, and a double-quote is
       // otherwise not permitted in topics, so a blind replacement is safe.
      let topic = trimResponse(response.data).replace(/"/g, '');
      callback(true, topic);
    })
    .catch(function (error) {
      if (error.response) {
        // Some other error was returned
        logger.log(
          `An error occurred in GET "${url}". Error ${error.response.status}: ${
            error.response.data}`,
          "error", parentUuid
        );
        callback(false, { statusCode: error.response.status, statusDetail: error.response.data });
      } else if (error.request) {
        // Gerrit failed to respond, try again later and resume the process.
        callback(false, "retry");
      } else {
        // Something happened in setting up the request that triggered an Error
        logger.log(
          `Error in HTTP request while trying to query ${fullChangeID}. ${error}`,
          "error", parentUuid
        );
        callback(false, error.message);
      }
    });
};

// Query gerrit for a change and return it along with the current revision if it exists.
exports.queryProjectCommit = function (parentUuid, project, commit, customAuth, callback) {
  let url = `${gerritBaseURL("projects")}/${encodeURIComponent(project)}/commits/${commit}`;
  logger.log(`Querying gerrit for ${url}`, "debug", parentUuid);
  axios.get(url, { auth: customAuth || gerritAuth })
    .then(function (response) {
      // Execute callback and return the list of changes
      logger.log(`Raw response: ${response.data}`, "debug", parentUuid);
      callback(true, JSON.parse(trimResponse(response.data)));
    })
    .catch(function (error) {
      if (error.response) {
        // Depending on usage, a 404 may not
        // be considered an error, so only write an error trace if
        // a status other than 404 is returned.
        if (error.response.status != 404) {
          // Some other error was returned
          logger.log(
            `An error occurred in GET "${url}". Error ${error.response.status}: ${
              error.response.data}`,
            "error", parentUuid
          );
        }
        callback(false, { statusCode: error.response.status, statusDetail: error.response.data });
      } else if (error.request) {
        // Gerrit failed to respond, try again later and resume the process.
        callback(false, "retry");
      } else {
        // Something happened in setting up the request that triggered an Error
        logger.log(
          `Error in HTTP request while trying to query ${project}:${commit}. ${error}`,
          "error", parentUuid
        );
        callback(false, error.message);
      }
    });
};

// Add a user to the attention set of a change
exports.addToAttentionSet = addToAttentionSet;
function addToAttentionSet(parentUuid, changeJSON, user, customAuth, callback) {
  checkAccessRights(
    parentUuid, changeJSON.project, changeJSON.branch || changeJSON.change.branch,
    user, "push", customAuth || gerritAuth,
    function (success, data) {
      if (!success) {
        let msg = `User "${user}" cannot push to ${changeJSON.project}:${changeJSON.branch}.`
        logger.log(msg, "warn", parentUuid);
        callback(false, msg);
        let botAssignee = envOrConfig("GERRIT_USER");
        if (botAssignee && newAssignee != botAssignee) {
          logger.log(`Falling back to GERRIT_USER (${botAssignee}) as assignee...`);
          addToAttentionSet(
            parentUuid, changeJSON, botAssignee, customAuth,
            function () {}
          );
        }
      } else {
        let url = `${gerritBaseURL("changes", changeJSON.fullChangeID || changeJSON.id)}/attention`;
        let data = { user: user, "reason": "Original author of change" };
        logger.log(
          `POST request to: ${url}\nRequest Body: ${safeJsonStringify(data)}`,
          "debug", parentUuid
        );
        axios({ method: "POST", url: url, data: data, auth: customAuth || gerritAuth })
          .then(function (response) {
            logger.log(
              `Added Attention Set user: "${user}" on "${changeJSON.fullChangeID || changeJSON.id}"`,
              "info", parentUuid
            );
            callback(true, undefined);
          })
          .catch(function (error) {
            if (error.response) {
              // The request was made and the server responded with a status code
              // that falls out of the range of 2xx
              logger.log(
                `An error occurred in POST to "${url}". Error: ${error.response.status}: ${
                  error.response.data}`,
                "error", parentUuid
              );
              callback(false, { status: error.response.status, data: error.response.data });
            } else if (error.request) {
              // The request was made but no response was received. Retry it later.
              callback(false, "retry");
            } else {
              // Something happened in setting up the request that triggered an Error
              logger.log(
                `Error in HTTP request while trying to add to attention set. Error: ${error}`,
                "error", parentUuid
              );
              callback(false, error.message);
            }
          });
      }
    }
  )
}

// Query gerrit for the existing reviewers on a change.
exports.getChangeReviewers = getChangeReviewers;
function getChangeReviewers(parentUuid, fullChangeID, customAuth, callback) {
  let url = `${gerritBaseURL("changes")}/${fullChangeID}/reviewers/`;
  logger.log(`GET request for ${url}`, "debug", parentUuid);
  axios
    .get(url, { auth: customAuth || gerritAuth })
    .then(function (response) {
      logger.log(`Raw Response: ${response.data}`, "debug", parentUuid);
      // Execute callback with the target branch head SHA1 of that branch
      let reviewerlist = [];
      JSON.parse(trimResponse(response.data)).forEach(function (item) {
        // Email as user ID is preferred. If unavailable, use the bare username.
        if (item.email)
          reviewerlist.push(item.email);
        else if (item.username)
          reviewerlist.push(item.username);
      });
      callback(true, reviewerlist);
    })
    .catch(function (error) {
      if (error.response) {
        // The request was made and the server responded with a status code
        // that falls out of the range of 2xx
        logger.log(
          `An error occurred in GET to "${url}". Error ${error.response.status}: ${
            error.response.data}`,
          "error", parentUuid
        );
      } else {
        logger.log(
          `Failed to get change reviewers on ${fullChangeID}: ${safeJsonStringify(error)}`,
          "error", parentUuid
        );
      }
      // Some kind of error occurred. Have the caller take some action to
      // alert the owner that they need to add reviewers manually.
      callback(false, "manual");
    });
}

// Add new reviewers to a change.
exports.setChangeReviewers = setChangeReviewers;
function setChangeReviewers(parentUuid, fullChangeID, reviewers, customAuth, callback) {
  let failedItems = [];
  let project = /^(\w+(?:%2F|\/)\w+-?\w+)~/.exec(fullChangeID).pop();
  let branch = /~(.+)~/.exec(fullChangeID).pop();
  function postReviewer(reviewer) {
    checkAccessRights(
      parentUuid, project, branch, reviewer, "read", customAuth,
      function (success, data) {
        if (!success) {
          logger.log(`Dropping reviewer ${reviewer} from cherry-pick to ${
            branch} because they can't view it.`, "info", parentUuid);
          logger.log(`Reason: ${data}`, "debug", parentUuid);
          failedItems.push(reviewer);
        } else {
          let url = `${gerritBaseURL("changes")}/${fullChangeID}/reviewers`;
          let data = { reviewer: reviewer };
          logger.log(
            `POST request to ${url}\nRequest Body: ${safeJsonStringify(data)}`,
            "debug", parentUuid
          );
          axios({ method: "post", url: url, data: data, auth: customAuth || gerritAuth })
            .then(function (response) {
              logger.log(
                `Success adding ${reviewer} to ${fullChangeID}\n${response.data}`,
                "info", parentUuid
              );
            })
            .catch(function (error) {
              if (error.response) {
                // The request was made and the server responded with a status code
                // that falls out of the range of 2xx
                logger.log(
                  `Error in POST to ${url} to add reviewer ${reviewer}: ${
                    error.response.status}: ${error.response.data}`,
                  "error", parentUuid
                );
              } else {
                logger.log(
                  `Error adding a reviewer (${reviewer}) to ${fullChangeID}: ${safeJsonStringify(error)}`,
                  "warn", parentUuid
                );
              }
              failedItems.push(reviewer);
            });
        }
      }
    );
  }

  // Not possible to batch reviewer adding into a single request. Iterate through
  // the list instead.
  reviewers.forEach(postReviewer);
  callback(failedItems);
}

// Copy reviewers from one change ID to another
exports.copyChangeReviewers = copyChangeReviewers;
function copyChangeReviewers(parentUuid, fromChangeID, toChangeID, customAuth, callback) {
  logger.log(`Copy change reviewers from ${fromChangeID} to ${toChangeID}`, "info", parentUuid);
  getChangeReviewers(parentUuid, fromChangeID, customAuth, function (success, reviewerlist) {
    if (success) {
      setChangeReviewers(parentUuid, toChangeID, reviewerlist, customAuth, function (failedItems) {
        if (callback)
          callback(true, failedItems);
      });
    } else {
      if (callback)
        callback(false, []);
    }
  });
}

// Check permissions for a branch. Returns Bool.
exports.checkAccessRights = checkAccessRights;
function checkAccessRights(uuid, repo, branch, user, permission, customAuth, callback) {
  // Decode and re-encode to be sure we don't double-encode something that was already
  // passed to us in URI encoded format.
  repo = encodeURIComponent(decodeURIComponent(repo));
  branch = encodeURIComponent(decodeURIComponent(branch));
  let url = `${gerritBaseURL("projects")}/${repo}/check.access?account=${
    user}&ref=${encodeURIComponent('refs/for/refs/heads/')}${branch}&perm=${permission}`;
  logger.log(`GET request for ${url}`, "debug", uuid);
  axios
    .get(url, { auth: customAuth || gerritAuth })
    .then(function (response) {
      // A successful response's JSON object has a status field (independent
      // of the HTTP response's status), that tells us whether this user
      // does (200) or doesn't (403) have the requested permissions.
      logger.log(`Raw Response: ${response.data}`, "debug", uuid);
      callback(JSON.parse(trimResponse(response.data)).status == 200, undefined)
    })
    .catch(function (error) {
      let data = ""
      if (error.response) {
        if (error.response.status != 403) {
          // The request was made and the server responded with a status code
          // that falls out of the range of 2xx and response code is unexpected.
          // However, a 403 response code means that the bot does not have permissions
          // to check permissions of other users, a much bigger problem.
          data = "retry";
        }
        logger.log(
          `An error occurred in GET to "${url}". Error ${error.response.status}: ${
            error.response.data}`,
          "error", uuid
        );
      } else {
        data = `${error.status}:${error.message}`;
        logger.log(
          `Failed to get ${permission} access rights on ${repo}:${branch}\n${
            safeJsonStringify(error)}`,
          "error", uuid
        );
      }
      callback(false, data);
    });
}

// Validate branch and check access in one action.
// Callback called with params (branchExists: bool,  PermissionAllowed: bool, data: str|undefined)
exports.checkBranchAndAccess = checkBranchAndAccess;
function checkBranchAndAccess(uuid, repo, branch, user, permission, customAuth, callback) {
 validateBranch(uuid, repo, branch, customAuth, function(success, data) {
    if (success && data != "retry") {
      logger.log(`${repo}:${branch} exists. Checking permissions...`, "info", uuid);
      checkAccessRights(uuid, repo, branch, user, permission, customAuth, function(hasRights, err) {
          callback(true, hasRights, hasRights ? data : err); // data from validateBranch contains a SHA.
      });
    } else {
      callback(false, false, data);
    }
  });
}