UNPKG

3.26 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const tslib_1 = require("tslib");
4const base_1 = tslib_1.__importStar(require("../base"));
5const CustomErrors_1 = require("../errors/CustomErrors");
6const env_1 = require("../constants/env");
7const get_docker_1 = tslib_1.__importDefault(require("../utils/get-docker"));
8// get ops matching the provided name
9exports.getOps = async (opName, teamId, accessToken, api) => {
10 return api.find('ops', {
11 query: {
12 name: opName,
13 team_id: teamId,
14 },
15 headers: {
16 Authorization: accessToken,
17 },
18 });
19};
20// form docker image name given the name/id and team name
21exports.formImageName = (nameOrId, teamName, registryHost) => {
22 return `${registryHost}/${teamName}/${nameOrId}`;
23};
24// remove the docker images
25exports.removeImage = async (docker, imageName) => {
26 await docker
27 .getImage(imageName)
28 .remove()
29 .catch(err => {
30 this.debug('%O', err);
31 throw new CustomErrors_1.ImageNotFoundError(imageName);
32 });
33};
34class Cleanup extends base_1.default {
35 async run() {
36 const { args: { opName }, } = this.parse(Cleanup);
37 try {
38 this.docker = await get_docker_1.default(this, 'publish');
39 await this.isLoggedIn();
40 if (!this.docker)
41 return;
42 if (opName === 'all' || !opName) {
43 // prune all unused images
44 await this.docker.pruneImages();
45 this.log(`\n Successfully removed unused images`);
46 process.exit();
47 }
48 const ops = await exports.getOps(opName, this.team.id, this.accessToken, this.services.api).catch(err => {
49 this.debug('%O', err);
50 throw new Error('API error');
51 });
52 if (!ops.data) {
53 throw new CustomErrors_1.ImageNotFoundError(opName);
54 }
55 // remove both the images for the matching op name
56 const { id, name } = ops.data[0];
57 const imagebyId = exports.formImageName(id, this.team.name, env_1.OPS_REGISTRY_HOST);
58 const imagebyName = exports.formImageName(name, this.team.name, env_1.OPS_REGISTRY_HOST);
59 await exports.removeImage(this.docker, imagebyId);
60 await exports.removeImage(this.docker, imagebyName);
61 this.services.analytics.track({
62 userId: this.user.email,
63 teamId: this.team.id,
64 event: 'Ops CLI Cleanup',
65 properties: {
66 email: this.user.email,
67 username: this.user.username,
68 },
69 }, this.accessToken);
70 this.log(`\n Successfully removed images for ${opName}`);
71 }
72 catch (err) {
73 this.debug('%O', err);
74 this.config.runHook('error', { err, accessToken: this.accessToken });
75 }
76 }
77}
78Cleanup.description = 'Clean up locally cached docker images.';
79Cleanup.flags = {
80 help: base_1.flags.help({ char: 'h' }),
81};
82Cleanup.args = [
83 {
84 name: 'opName',
85 description: 'Name of the op to be cleaned up',
86 },
87];
88exports.Cleanup = Cleanup;