/* * Copyright © 2020 Atomist, Inc. * * 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 * * http://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. */ /** Input to [[labelName]]. */ export interface Labels { /** Project environment, e.g., "staging" or "production". */ environment: string; /** Project purpose, e.g., "general" or "skill". */ purpose: string; /** Project user, e.g., "internal" or "customer". */ user: string; /** Maximum length of string to return. */ length?: number; /** Resource prefix to prepend to string. */ resource?: string; } /** * Create valid Atomist GCP resource labels from `labels`. */ export function resourceLabels( labels: Pick, ): Record<"atm-env" | "atm-purpose" | "atm-user", string> { return { "atm-env": labels.environment, "atm-purpose": labels.purpose, "atm-user": labels.user, }; } /** Only include purpose if it provides information. */ function includePurpose(labels: Labels): boolean { return ( labels.purpose !== "general" && labels.purpose !== labels.environment ); } /** * Generate name from environment, purpose, and user. The returned * name will be lower cased and not exceed `labels.length`, if * provided. If the name is truncated to `labels.length`, it is * truncated to an alphanumeric character. * * @param labels components of name, see [[Labels]]. * @return name generated from labels */ export function labelName(labels: Labels): string { const parts: string[] = []; if (labels.resource) { parts.push(labels.resource); } parts.push(labels.user); if (includePurpose(labels)) { parts.push(labels.purpose); } parts.push(labels.environment); let name = parts.join("-").toLowerCase(); if (labels.length && labels.length > 0) { if (name.length > labels.length) { name = name.substring(0, labels.length).replace(/[^a-z0-9]*$/, ""); } } return name; } /** * Create array of tags from labels. Ensure tags are lower cased. */ export function labelTags( labels: Pick, ): string[] { const tags: string[] = [labels.user]; if (includePurpose(labels)) { tags.push(labels.purpose); } tags.push(labels.environment); return tags.map(t => t.toLowerCase()); }