@automattic/vip 2.6.0 → 2.7.0-dev1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Binary file
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "tracksUserType": "vip:user_id",
3
3
  "tracksAnonUserType": "anon",
4
- "tracksEventPrefix": "vip_cli_",
5
- "environment": "production"
4
+ "tracksEventPrefix": "vip_cli_dev_",
5
+ "environment": "development"
6
6
  }
@@ -0,0 +1,41 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ *
5
+ * @fomat
6
+ */
7
+
8
+ /**
9
+ * External dependencies
10
+ */
11
+ "use strict";
12
+
13
+ var _debug = _interopRequireDefault(require("debug"));
14
+
15
+ var _chalk = _interopRequireDefault(require("chalk"));
16
+
17
+ var _command = _interopRequireDefault(require("../lib/cli/command"));
18
+
19
+ var _devEnvironment = require("../lib/dev-environment");
20
+
21
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
22
+
23
+ /**
24
+ * Internal dependencies
25
+ */
26
+ const debug = (0, _debug.default)('@automattic/vip:bin:dev-environment'); // Command examples
27
+
28
+ const examples = [{
29
+ usage: 'vip dev-environment start',
30
+ description: 'Starts local dev environment\n' + ' * If the environment isn\'t built yet it will build it as well'
31
+ }];
32
+ (0, _command.default)().option('slug', `Custom name of the dev environment (default: "${_devEnvironment.defaults.environmentSlug}")`).option('title', 'Title for the WordPress site (default: "VIP Dev")').option('multisite', 'Enable multisite install').option('php', 'Use a specific PHP version').option('wordpress', 'Use a specific WordPress version or local directory (default: last stable)').option('mu-plugins', 'Use a specific mu-plugins changeset or local directory (default: "auto": last commit in master)').option('jetpack', 'Use a specific Jetpack from a local directory (default: "mu": use the version in mu-plugins)').option('client-code', 'Use the client code from a local directory or VIP skeleton (default: use the VIP skeleton)').examples(examples).argv(process.argv, async (arg, opt) => {
33
+ const slug = opt.slug || _devEnvironment.defaults.environmentSlug;
34
+ debug('Args: ', arg, 'Options: ', opt);
35
+
36
+ try {
37
+ await (0, _devEnvironment.startEnvironment)(slug, opt);
38
+ } catch (e) {
39
+ console.log(_chalk.default.red('Error:'), e.message);
40
+ }
41
+ });
@@ -0,0 +1,23 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ *
5
+ * @fomat
6
+ */
7
+
8
+ /**
9
+ * External dependencies
10
+ */
11
+
12
+ /**
13
+ * Internal dependencies
14
+ */
15
+ "use strict";
16
+
17
+ var _command = _interopRequireDefault(require("../lib/cli/command"));
18
+
19
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20
+
21
+ (0, _command.default)({
22
+ requiredArgs: 1
23
+ }).command('start', 'Start the local dev environment').argv(process.argv);
File without changes
File without changes
File without changes
@@ -0,0 +1,151 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Internal dependencies
5
+ */
6
+ "use strict";
7
+
8
+ Object.defineProperty(exports, "__esModule", {
9
+ value: true
10
+ });
11
+ exports.getLogs = getLogs;
12
+ exports.validateInputs = validateInputs;
13
+ exports.appQuery = void 0;
14
+
15
+ var _command = _interopRequireDefault(require("../lib/cli/command"));
16
+
17
+ var _rollbar = require("../lib/rollbar");
18
+
19
+ var _tracker = require("../lib/tracker");
20
+
21
+ var logsLib = _interopRequireWildcard(require("../lib/logs/logs"));
22
+
23
+ var exit = _interopRequireWildcard(require("../lib/cli/exit"));
24
+
25
+ var _format = require("../lib/cli/format");
26
+
27
+ function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
28
+
29
+ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
30
+
31
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
32
+
33
+ const LIMIT_MAX = 5000;
34
+ const LIMIT_MIN = 1;
35
+ const ALLOWED_TYPES = ['app', 'batch'];
36
+ const ALLOWED_FORMATS = ['csv', 'json', 'text'];
37
+
38
+ async function getLogs(arg, opt) {
39
+ validateInputs(opt.type, opt.limit, opt.format);
40
+ const trackingParams = {
41
+ command: 'vip logs',
42
+ org_id: opt.app.organization.id,
43
+ app_id: opt.app.id,
44
+ env_id: opt.env.id,
45
+ type: opt.type,
46
+ limit: opt.limit,
47
+ format: opt.format
48
+ };
49
+ await (0, _tracker.trackEvent)('logs_command_execute', trackingParams);
50
+ let logs = [];
51
+
52
+ try {
53
+ logs = await logsLib.getRecentLogs(opt.app.id, opt.env.id, opt.type, opt.limit);
54
+ } catch (error) {
55
+ _rollbar.rollbar.error(error);
56
+
57
+ await (0, _tracker.trackEvent)('logs_command_error', { ...trackingParams,
58
+ error: error.message
59
+ });
60
+ return exit.withError(error.message);
61
+ }
62
+
63
+ await (0, _tracker.trackEvent)('logs_command_success', { ...trackingParams,
64
+ logs_output: logs.length
65
+ });
66
+
67
+ if (!logs.length) {
68
+ console.error('No logs found');
69
+ return;
70
+ } // Strip out __typename
71
+
72
+
73
+ logs = logs.map(log => {
74
+ const {
75
+ timestamp,
76
+ message
77
+ } = log;
78
+ return {
79
+ timestamp,
80
+ message
81
+ };
82
+ });
83
+ let output = '';
84
+
85
+ if (opt.format && 'text' === opt.format) {
86
+ const rows = [];
87
+
88
+ for (const {
89
+ timestamp,
90
+ message
91
+ } of logs) {
92
+ rows.push(`${timestamp} ${message}`);
93
+ output = rows.join('\n');
94
+ }
95
+ } else {
96
+ output = (0, _format.formatData)(logs, opt.format);
97
+ }
98
+
99
+ console.log(output);
100
+ }
101
+
102
+ function validateInputs(type, limit, format) {
103
+ if (!ALLOWED_TYPES.includes(type)) {
104
+ exit.withError(`Invalid type: ${type}. The supported types are: ${ALLOWED_TYPES.join(', ')}.`);
105
+ }
106
+
107
+ if (!ALLOWED_FORMATS.includes(format)) {
108
+ exit.withError(`Invalid format: ${format}. The supported formats are: ${ALLOWED_FORMATS.join(', ')}.`);
109
+ }
110
+
111
+ if (!Number.isInteger(limit) || limit < LIMIT_MIN || limit > LIMIT_MAX) {
112
+ exit.withError(`Invalid limit: ${limit}. It should be a number between ${LIMIT_MIN} and ${LIMIT_MAX}.`);
113
+ }
114
+ }
115
+
116
+ const appQuery = `
117
+ id
118
+ name
119
+ environments {
120
+ id
121
+ appId
122
+ name
123
+ type
124
+ }
125
+ organization {
126
+ id
127
+ name
128
+ }
129
+ `;
130
+ exports.appQuery = appQuery;
131
+ (0, _command.default)({
132
+ appContext: true,
133
+ appQuery,
134
+ envContext: true,
135
+ module: 'logs'
136
+ }).option('type', 'The type of logs to be returned: "app" or "batch"', 'app').option('limit', 'The maximum number of log lines', 500).option('format', 'Output the log lines in CSV or JSON format', 'text').examples([{
137
+ usage: 'vip @mysite.production logs',
138
+ description: 'Get the most recent app logs'
139
+ }, {
140
+ usage: 'vip @mysite.production logs --type batch',
141
+ description: 'Get the most recent batch logs'
142
+ }, {
143
+ usage: 'vip @mysite.production logs --limit 100',
144
+ description: 'Get the most recent 100 log entries'
145
+ }, {
146
+ usage: 'vip @mysite.production logs --limit 100 --format csv',
147
+ description: 'Get the most recent 100 log entries formatted as comma-separated values (CSV)'
148
+ }, {
149
+ usage: 'vip @mysite.production logs --limit 100 --format json',
150
+ description: 'Get the most recent 100 log entries formatted as JSON'
151
+ }]).argv(process.argv, getLogs);
package/dist/bin/vip.js CHANGED
@@ -48,7 +48,7 @@ const runCmd = async function () {
48
48
  await _token.default.purge();
49
49
  await (0, _tracker.trackEvent)('logout_command_execute');
50
50
  console.log('You are successfully logged out.');
51
- }).command('app', 'List and modify your VIP applications').command('config', 'Set configuration for your VIP applications').command('dev-env', 'Use local dev-environment').command('import', 'Import media or SQL files into your VIP applications').command('search-replace', 'Perform search and replace tasks on files').command('sync', 'Sync production to a development environment').command('wp', 'Run WP CLI commands against an environment');
51
+ }).command('app', 'List and modify your VIP applications').command('config', 'Set configuration for your VIP applications').command('dev-env', 'Use local dev-environment').command('import', 'Import media or SQL files into your VIP applications').command('logs', 'Get logs from your VIP applications').command('search-replace', 'Perform search and replace tasks on files').command('sync', 'Sync production to a development environment').command('wp', 'Run WP CLI commands against an environment');
52
52
  cmd.argv(process.argv);
53
53
  };
54
54
 
@@ -0,0 +1,194 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.startEnvironment = startEnvironment;
7
+ exports.generateInstanceData = generateInstanceData;
8
+ exports.getEnvironmentPath = getEnvironmentPath;
9
+ exports.defaults = void 0;
10
+
11
+ var _debug = _interopRequireDefault(require("debug"));
12
+
13
+ var _xdgBasedir = _interopRequireDefault(require("xdg-basedir"));
14
+
15
+ var _os = _interopRequireDefault(require("os"));
16
+
17
+ var _fs = _interopRequireDefault(require("fs"));
18
+
19
+ var _ejs = _interopRequireDefault(require("ejs"));
20
+
21
+ var _path = _interopRequireDefault(require("path"));
22
+
23
+ var _lando = _interopRequireDefault(require("lando/lib/lando"));
24
+
25
+ var _utils = _interopRequireDefault(require("lando/plugins/lando-core/lib/utils"));
26
+
27
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
28
+
29
+ /**
30
+ *
31
+ * @format
32
+ */
33
+
34
+ /**
35
+ * External dependencies
36
+ */
37
+
38
+ /**
39
+ * Internal dependencies
40
+ */
41
+ const debug = (0, _debug.default)('@automattic/vip:bin:dev-environment');
42
+ const containerImages = {
43
+ wordpress: {
44
+ image: 'wpvipdev/wordpress',
45
+ tag: '5.6'
46
+ },
47
+ jetpack: {
48
+ image: 'wpvipdev/jetpack'
49
+ },
50
+ muPlugins: {
51
+ image: 'wpvipdev/mu-plugins',
52
+ tag: 'auto'
53
+ },
54
+ clientCode: {
55
+ image: 'wpvipdev/skeleton',
56
+ tag: '181a17d9aedf7da73730d65ccef3d8dbf172a5c5'
57
+ }
58
+ };
59
+ const defaults = {
60
+ environmentSlug: 'vip-local',
61
+ title: 'VIP Dev',
62
+ multisite: false,
63
+ phpVersion: '7.3',
64
+ jetpack: {
65
+ mode: 'inherit'
66
+ },
67
+ wordpress: {},
68
+ muPlugins: {},
69
+ clientCode: {}
70
+ };
71
+ exports.defaults = defaults;
72
+ ['wordpress', 'muPlugins', 'clientCode'].forEach(type => {
73
+ defaults[type] = {
74
+ mode: 'image',
75
+ image: containerImages[type].image,
76
+ tag: containerImages[type].tag
77
+ };
78
+ });
79
+ const landoFileTemplatePath = 'assets/dev-environment.lando.template.yml.ejs';
80
+ const landoFileName = '.lando.yml';
81
+
82
+ async function startEnvironment(slug, options) {
83
+ debug('Will start an environment', slug, 'with options: ', options);
84
+ const instancePath = getEnvironmentPath(slug);
85
+
86
+ const alreadyExists = _fs.default.existsSync(instancePath);
87
+
88
+ if (alreadyExists) {
89
+ const parameters = Object.keys(options || {}).filter(key => key !== 'slug');
90
+
91
+ if (parameters && parameters.length) {
92
+ throw new Error(`The environment ${slug} already exists and we can not change its configuration` + ` ( configuration parameters - ${parameters.join(', ')} found ).` + ' Destroy the environment first if you would like to recreate it.');
93
+ }
94
+ } else {
95
+ const instanceData = generateInstanceData(slug, options);
96
+ debug('Instance data to create a new environment:', instanceData);
97
+ await prepareLandoEnv(instanceData, instancePath);
98
+ }
99
+
100
+ await landoStart(instancePath);
101
+ }
102
+
103
+ function getLandoConfig() {
104
+ const landoPath = _path.default.join(__dirname, '..', '..', 'node_modules', 'lando');
105
+
106
+ debug(`Getting lando config, using path '${landoPath}' for plugins`);
107
+ return {
108
+ logLevelConsole: 'warn',
109
+ landoFile: '.lando.yml',
110
+ preLandoFiles: ['.lando.base.yml', '.lando.dist.yml', '.lando.upstream.yml'],
111
+ postLandoFiles: ['.lando.local.yml'],
112
+ pluginDirs: [landoPath, {
113
+ path: _path.default.join(landoPath, 'integrations'),
114
+ subdir: '.'
115
+ }]
116
+ };
117
+ }
118
+
119
+ async function landoStart(instancePath) {
120
+ debug('Will start lando app on path:', instancePath);
121
+ const lando = new _lando.default(getLandoConfig());
122
+ await lando.bootstrap();
123
+ const app = lando.getApp(instancePath);
124
+ await app.init();
125
+ await app.start();
126
+ console.log(lando.cli.formatData(_utils.default.startTable(app), {
127
+ format: 'table'
128
+ }, {
129
+ border: false
130
+ }));
131
+ }
132
+
133
+ async function prepareLandoEnv(instanceData, instancePath) {
134
+ const landoFile = await _ejs.default.renderFile(landoFileTemplatePath, instanceData);
135
+
136
+ const landoFileTargetPath = _path.default.join(instancePath, landoFileName);
137
+
138
+ _fs.default.mkdirSync(instancePath, {
139
+ recursive: true
140
+ });
141
+
142
+ _fs.default.writeFileSync(landoFileTargetPath, landoFile);
143
+
144
+ debug(`Lando file created in ${landoFileTargetPath}`);
145
+ }
146
+
147
+ function generateInstanceData(slug, options) {
148
+ const instanceData = {
149
+ siteSlug: slug,
150
+ wpTitle: options.title || defaults.title,
151
+ multisite: options.multisite || defaults.multisite,
152
+ phpVersion: options.phpVersion || defaults.phpVersion,
153
+ wordpress: getParamInstanceData(options.wordpress, 'wordpress'),
154
+ muPlugins: getParamInstanceData(options.muPlugins, 'muPlugins'),
155
+ jetpack: getParamInstanceData(options.jetpack, 'jetpack'),
156
+ clientCode: getParamInstanceData(options.clientCode, 'clientCode')
157
+ };
158
+ return instanceData;
159
+ }
160
+
161
+ function getParamInstanceData(param, type) {
162
+ if (param) {
163
+ if (param.includes('/')) {
164
+ return {
165
+ mode: 'local',
166
+ dir: param
167
+ };
168
+ }
169
+
170
+ if (type === 'jetpack' && param === 'mu') {
171
+ return {
172
+ mode: 'inherit'
173
+ };
174
+ }
175
+
176
+ return {
177
+ mode: 'image',
178
+ image: containerImages[type].image,
179
+ tag: param
180
+ };
181
+ }
182
+
183
+ return defaults[type];
184
+ }
185
+
186
+ function getEnvironmentPath(name) {
187
+ if (!name) {
188
+ throw new Error('Name was not provided');
189
+ }
190
+
191
+ const mainEnvironmentPath = _xdgBasedir.default.data || _os.default.tmpdir();
192
+
193
+ return _path.default.join(mainEnvironmentPath, 'vip', 'dev-environment', name);
194
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@automattic/vip",
3
- "version": "2.6.0",
3
+ "version": "2.7.0-dev1",
4
4
  "description": "The VIP Javascript library & CLI",
5
5
  "main": "index.js",
6
6
  "bin": {
@@ -33,6 +33,7 @@
33
33
  "vip-import-sql-status": "dist/bin/vip-import-sql-status.js",
34
34
  "vip-import-validate-files": "dist/bin/vip-import-validate-files.js",
35
35
  "vip-import-validate-sql": "dist/bin/vip-import-validate-sql.js",
36
+ "vip-logs": "dist/bin/vip-logs.js",
36
37
  "vip-search-replace": "dist/bin/vip-search-replace.js",
37
38
  "vip-sync": "dist/bin/vip-sync.js",
38
39
  "vip-wp": "dist/bin/vip-wp.js"