UNPKG

@google-automations/label-utils

Version:
101 lines 3.81 kB
"use strict"; // Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. Object.defineProperty(exports, "__esModule", { value: true }); exports.syncLabels = exports.getLabelColor = void 0; const crypto_1 = require("crypto"); const gcf_utils_1 = require("gcf-utils"); const datastore_lock_1 = require("@google-automations/datastore-lock"); // This way, we'll have always the same color for the same label. function getLabelColor(name) { return (0, crypto_1.createHash)('md5').update(name).digest('hex').slice(0, 6); } exports.getLabelColor = getLabelColor; async function syncLabels(octokit, owner, repo, labels, logger = gcf_utils_1.logger) { try { await (0, datastore_lock_1.withDatastoreLock)({ lockId: 'label-sync', target: `${owner}/${repo}`, }, async () => { return await syncLabelsImpl(octokit, owner, repo, labels, logger); }); } catch (e) { logger.error('Failed to acquire the lock:', e); } } exports.syncLabels = syncLabels; async function syncLabelsImpl(octokit, owner, repo, labels, logger = gcf_utils_1.logger) { const newLabels = []; for (const l of labels) { newLabels.push({ name: l.name.toLowerCase(), description: l.description, color: getLabelColor(l.name.toLowerCase()), }); } const oldLabels = await octokit.paginate(octokit.issues.listLabelsForRepo, { owner, repo, per_page: 100, }); for (const l of newLabels) { const match = oldLabels.find(x => x.name.toLowerCase() === l.name); if (match) { if (match.color !== l.color || match.description !== l.description) { logger.info(`Updating ${match.name} from #${match.color} to #${l.color} and ` + `'${match.description}' to '${l.description}'.`); await octokit.issues .updateLabel({ owner: owner, repo: repo, name: l.name, current_name: l.name, description: l.description, color: l.color, }) .catch(e => { e.message = `Error updating label ${l.name} in ${owner}/${repo}` + `\n\n${e.message}`; logger.error(e); }); } } else { logger.info(`Creating label '${l.name}'.`); await octokit.issues .createLabel({ owner: owner, repo: repo, name: l.name, current_name: l.name, description: l.description, color: l.color, }) .catch(e => { // ignores conflicts if (!Array.isArray(e.errors) || e.errors[0].code !== 'already_exists') { e.message = `Error creating label ${l.name} in ${owner}/${repo}` + `\n\n${e.message}`; logger.error(e); } }); } } return; } //# sourceMappingURL=label-utils.js.map