This repository has been archived by the owner on Jul 1, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 23
/
switch.ts
645 lines (533 loc) · 20 KB
/
switch.ts
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
/// <reference types="node" />
// The MIT License (MIT)
//
// vs-deploy (https://github.com/mkloubert/vs-deploy)
// Copyright (c) Marcel Joachim Kloubert <marcel.kloubert@gmx.net>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
import * as deploy_contracts from './contracts';
import * as deploy_helpers from './helpers';
import * as deploy_plugins_switch from './plugins/switch';
import * as deploy_values from './values';
import * as Enumerable from 'node-enumerable';
import * as i18 from './i18';
import * as vs_deploy from './deploy';
import * as vscode from 'vscode';
type SavedStates = { [switchName: string]: string };
interface Button {
button: vscode.StatusBarItem;
command: vscode.Disposable;
index: number;
settings: deploy_plugins_switch.DeploySwitchButton;
switch: deploy_plugins_switch.DeployTargetSwitch;
}
/**
* Stores the new option data for a target.
*/
export interface NewSwitchOptionState {
/**
* The new option.
*/
option: deploy_plugins_switch.DeployTargetSwitchOption;
/**
* The underlying target.
*/
target: deploy_plugins_switch.DeployTargetSwitch;
}
/**
* Repository of selected switch options.
*/
export type SelectedSwitchOptions = { [name: string]: deploy_plugins_switch.DeployTargetSwitchOption };
const BUTTONS: Button[] = [];
const KEY_SWITCH_STATES = 'vsdSwitchStates';
let nextButtonId = -1;
let switchStates: SelectedSwitchOptions = {};
/**
* Changes a switch target.
*/
export async function changeSwitch() {
const ME: vs_deploy.Deployer = this;
const TARGETS = <deploy_plugins_switch.DeployTargetSwitch[]>ME.getTargets().filter(t => {
return isSwitch(t);
});
let selectedOption: deploy_plugins_switch.DeployTargetSwitchOption;
let selectedTarget: deploy_plugins_switch.DeployTargetSwitch;
const SELECT_TARGET_OPTION = async (index: number) => {
await selectTargetOption.apply(ME,
[ selectedTarget, index ]);
};
const QUICK_PICKS: deploy_contracts.DeployActionQuickPick[] = TARGETS.map((t, i) => {
const LABEL = getSwitchName(t, i);
const DESCRIPTION = deploy_helpers.toStringSafe(t.description).trim();
return {
action: async () => {
selectedTarget = t;
await SELECT_TARGET_OPTION(i);
},
description: DESCRIPTION,
label: LABEL,
};
});
if (QUICK_PICKS.length < 1) {
vscode.window.showWarningMessage(
'[vs-deploy] ' + i18.t('plugins.switch.noDefined'),
);
return;
}
let targetAction: Function;
if (1 === QUICK_PICKS.length) {
targetAction = QUICK_PICKS[0].action;
}
else {
const SELECTED_ITEM = await vscode.window.showQuickPick(QUICK_PICKS, {
placeHolder: i18.t('plugins.switch.selectSwitch'),
});
if (SELECTED_ITEM) {
targetAction = SELECTED_ITEM.action;
}
}
if (targetAction) {
await Promise.resolve(
targetAction()
);
}
}
/**
* Returns the current option of a target.
*
* @param {deploy_plugins_switch.DeployTargetSwitch} target The target.
* @param {TDefault} [defaultValue] The custom default value.
*
* @return {deploy_plugins_switch.DeployTargetSwitchOption|TDefault} The option (if found).
*/
export function getCurrentOptionOf<TDefault = false>(target: deploy_plugins_switch.DeployTargetSwitch,
defaultValue = <TDefault><any>false): deploy_plugins_switch.DeployTargetSwitchOption | TDefault {
if (!target) {
return <any>target;
}
const TARGET_NAME = deploy_helpers.normalizeString( target.name );
const STATES = getSelectedSwitchOptions();
if (STATES) {
const OPTION = STATES[TARGET_NAME];
if ('object' === typeof OPTION) {
return OPTION; // found
}
else {
// get first (default) one
// instead
return Enumerable.from(
getTargetOptionsOf(target)
).orderBy(o => {
return deploy_helpers.toBooleanSafe(o.isDefault) ? 0 : 1;
}).firstOrDefault(x => true,
defaultValue);
}
}
return defaultValue;
}
/**
* Returns the object that stores the states of all switches.
*
* @return {SelectedSwitchOptions} The object with the states.
*/
export function getSelectedSwitchOptions(): SelectedSwitchOptions {
return switchStates || <any>{};
}
function getSwitches(): deploy_plugins_switch.DeployTargetSwitch[] {
const ME: vs_deploy.Deployer = this;
return <deploy_plugins_switch.DeployTargetSwitch[]>ME.getTargets().filter(t => {
return isSwitch(t);
});
}
function getSwitchName(target: deploy_plugins_switch.DeployTargetSwitch, index: number): string {
if (!target) {
return <any>target;
}
let name = deploy_helpers.toStringSafe(target.name).trim();
if ('' === name) {
name = i18.t('plugins.switch.defaultName',
index + 1);
}
return name;
}
function getSwitchOptionName(target: deploy_plugins_switch.DeployTargetSwitchOption, index: number): string {
if (!target) {
return <any>target;
}
let name = deploy_helpers.toStringSafe(target.name).trim();
if ('' === name) {
name = i18.t('plugins.switch.defaultOptionName',
index + 1);
}
return name;
}
/**
* Returns the options of a switch target.
*
* @param {deploy_plugins_switch.DeployTargetSwitch} target The target.
*
* @return {deploy_plugins_switch.DeployTargetSwitchOption[]} The options.
*/
export function getTargetOptionsOf(target: deploy_plugins_switch.DeployTargetSwitch): deploy_plugins_switch.DeployTargetSwitchOption[] {
if (deploy_helpers.isNullOrUndefined(target)) {
return <any>target;
}
const TARGET_NAME = deploy_helpers.normalizeString(target.name);
const OPTIONS: deploy_plugins_switch.DeployTargetSwitchOption[] = [];
let objIndex = -1;
Enumerable.from( deploy_helpers.asArray(target.options) ).where(v => {
return !deploy_helpers.isNullOrUndefined(v);
}).select(v => {
++objIndex;
v = deploy_helpers.cloneObject(v);
if ('object' !== typeof v) {
v = {
targets: [ deploy_helpers.normalizeString(v) ]
};
}
v.__id = `${target.__id}\n` +
`${deploy_helpers.normalizeString(deploy_helpers.getSortValue(v))}\n` +
`${objIndex}\n` +
`${deploy_helpers.normalizeString(v.name)}`;
v.__index = objIndex;
v.targets = Enumerable.from( deploy_helpers.asArray(v.targets) ).select(t => {
return deploy_helpers.normalizeString(t);
}).where(t => '' !== t &&
TARGET_NAME !== t)
.distinct()
.toArray();
return v;
})
.pushTo(OPTIONS);
return OPTIONS.sort((x, y) => {
return deploy_helpers.compareValuesBy(x, y,
o => deploy_helpers.getSortValue(o));
});
}
function isSwitch(target: deploy_contracts.DeployTarget): target is deploy_plugins_switch.DeployTargetSwitch {
if (target) {
return [
'switch'
].indexOf( deploy_helpers.normalizeString(target.type) ) > -1;
}
return false;
}
export function printSwitchStates() {
const ME: vs_deploy.Deployer = this;
try {
const SWITCHES: deploy_plugins_switch.DeployTargetSwitch[] = getSwitches.apply(ME, []);
if (SWITCHES.length > 0) {
ME.outputChannel.appendLine('');
ME.outputChannel.appendLine(
i18.t('plugins.switch.states')
);
SWITCHES.forEach((s, i) => {
const TARGET_NAME = getSwitchName(s, i);
ME.outputChannel.append(
i18.t('plugins.switch.item',
TARGET_NAME),
);
const OPTION = getCurrentOptionOf(s);
if (false === OPTION) {
ME.outputChannel.appendLine(
`<${i18.t('plugins.switch.noOptionSelected')}>`,
);
}
else {
ME.outputChannel.appendLine(
"'" + getSwitchOptionName(OPTION, OPTION.__index) + "'",
);
}
});
ME.outputChannel.appendLine('');
}
}
catch (e) {
ME.log(`[ERROR :: vs-deploy] switch.printSwitchStates(): ${deploy_helpers.toStringSafe(e)}`);
}
}
/**
* Reloads the switch buttons.
*/
export function reloadButtons() {
const ME = this;
while (BUTTONS.length > 0) {
const BTN = BUTTONS.shift();
deploy_helpers.tryDispose(BTN.button);
deploy_helpers.tryDispose(BTN.command);
}
const SWITCHES: deploy_plugins_switch.DeployTargetSwitch[] = getSwitches.apply(ME, []);
SWITCHES.forEach((s, i) => {
let newBtn: vscode.StatusBarItem;
let newCmd: vscode.Disposable;
try {
if (deploy_helpers.isNullOrUndefined(s.button)) {
return;
}
if ('object' !== typeof s.button) {
if (!deploy_helpers.toBooleanSafe(s.button)) {
return;
}
}
let btn = s.button;
if ('object' !== typeof btn) {
btn = {
};
}
if (!deploy_helpers.toBooleanSafe(btn.enabled, true)) {
return;
}
const ID = nextButtonId++;
let color = deploy_helpers.normalizeString(btn.color);
const IS_RIGHT = deploy_helpers.toBooleanSafe(btn.isRight);
let prio = parseInt(
deploy_helpers.toStringSafe(btn.priority).trim()
);
if (deploy_helpers.isEmptyString(color)) {
color = '#ffffff';
}
if (isNaN(prio)) {
prio = undefined;
}
const ALIGNMENT = IS_RIGHT ? vscode.StatusBarAlignment.Right
: vscode.StatusBarAlignment.Left;
const COMMAND = 'extension.deploy.switches.button' + ID;
newCmd = vscode.commands.registerCommand(COMMAND, async () => {
await selectTargetOption.apply(ME, [ s, i ]);
});
newBtn = vscode.window.createStatusBarItem(ALIGNMENT, prio);
newBtn.color = color;
newBtn.command = COMMAND;
newBtn.show();
BUTTONS.push({
button: newBtn,
command: newCmd,
index: i,
settings: deploy_helpers.cloneObject(btn),
switch: s,
});
}
catch (e) {
deploy_helpers.tryDispose(newBtn);
deploy_helpers.tryDispose(newCmd);
ME.log(`[ERROR :: vs-deploy] switch.reloadButtons(): ${deploy_helpers.toStringSafe(e)}`);
}
});
updateButtons.apply(ME, []);
}
/**
* Reloads the target states for switches.
*/
export function reloadTargetStates() {
const ME: vs_deploy.Deployer = this;
resetTargetStates();
try {
const STATES = ME.context.workspaceState.get<SavedStates>(KEY_SWITCH_STATES);
if (STATES) {
const SWITCHES: deploy_plugins_switch.DeployTargetSwitch[] = getSwitches.apply(ME, []);
for (let p in STATES) {
const OPTION_ID = STATES[p];
if (deploy_helpers.isEmptyString(OPTION_ID)) {
continue;
}
const TARGET_NAME = deploy_helpers.normalizeString(p);
SWITCHES.filter(s => {
return TARGET_NAME === deploy_helpers.normalizeString(s.name);
}).forEach(s => {
Enumerable.from( getTargetOptionsOf(s) ).where(o => {
return o.__id === OPTION_ID;
}).forEach(o => {
setCurrentOptionFor(s, o);
});
});
}
}
// clean update
saveStates.apply(ME, []).then(() => {
}).catch((err) => {
ME.log(`[ERROR :: vs-deploy] switch.reloadTargetStates(2): ${deploy_helpers.toStringSafe(err)}`);
});
}
catch (e) {
ME.log(`[ERROR :: vs-deploy] switch.reloadTargetStates(1): ${deploy_helpers.toStringSafe(e)}`);
}
}
/**
* Resets all target states for switches.
*/
export function resetTargetStates() {
switchStates = {};
}
/**
* Saves the states to the current workspace.
*/
export async function saveStates() {
const ME: vs_deploy.Deployer = this;
try {
let newValue: SavedStates;
const STATES = getSelectedSwitchOptions();
if (STATES) {
newValue = {};
for (let p in STATES) {
newValue[p] = STATES[p].__id;
}
}
await ME.context.workspaceState.update(KEY_SWITCH_STATES,
newValue);
}
catch (e) {
ME.log(`[ERROR :: vs-deploy] switch.saveStates(): ${deploy_helpers.toStringSafe(e)}`);
}
}
async function selectTargetOption(target: deploy_plugins_switch.DeployTargetSwitch,
index: number) {
const ME: vs_deploy.Deployer = this;
if (!target) {
return;
}
let selectedOption: deploy_plugins_switch.DeployTargetSwitchOption;
const SWITCH_NAME = getSwitchName(target, index);
const OPTIONS = Enumerable.from( getTargetOptionsOf(target) )
.toArray()
.sort((x, y) => {
return deploy_helpers.compareValuesBy(x, y,
i => deploy_helpers.getSortValue(i,
() => ME.name));
});
const SELECT_OPTION = async () => {
if (!selectedOption) {
return;
}
setCurrentOptionFor(target, selectedOption);
await saveStates.apply(ME, []);
printSwitchStates.apply(ME, []);
updateButtons.apply(ME, []);
};
const OPTION_QUICK_PICKS: deploy_contracts.DeployActionQuickPick[] = OPTIONS.map((o, i) => {
const LABEL = getSwitchOptionName(o, i);
const DESCRIPTION = deploy_helpers.toStringSafe(o.description).trim();
let details = '';
let isSelected = false;
const SELECTED_OPTION_OF_TARGET = getCurrentOptionOf(target);
if (SELECTED_OPTION_OF_TARGET) {
if (o.__id === SELECTED_OPTION_OF_TARGET.__id) {
isSelected = true;
}
}
return {
action: async () => {
selectedOption = o;
await SELECT_OPTION();
},
description: DESCRIPTION,
detail: isSelected ? `(${i18.t('selected')})` : '',
label: LABEL,
};
});
if (OPTION_QUICK_PICKS.length < 1) {
vscode.window.showWarningMessage(
'[vs-deploy] ' + i18.t('plugins.switch.noOptionsDefined',
SWITCH_NAME),
);
return;
}
let action: Function;
if (1 === OPTION_QUICK_PICKS.length) {
action = OPTION_QUICK_PICKS[0].action;
}
else {
const SELECTED_ITEM = await vscode.window.showQuickPick(OPTION_QUICK_PICKS, {
placeHolder: i18.t('plugins.switch.selectOption',
SWITCH_NAME),
});
if (SELECTED_ITEM) {
action = SELECTED_ITEM.action;
}
}
if (action) {
await Promise.resolve(action());
}
}
/**
* Sets the current option for a switch target.
*
* @param {deploy_plugins_switch.DeployTargetSwitch} target The target.
* @param {deploy_plugins_switch.DeployTargetSwitchOption} option The option to set.
*
* @return {Object} The new data.
*/
export function setCurrentOptionFor(target: deploy_plugins_switch.DeployTargetSwitch, option: deploy_plugins_switch.DeployTargetSwitchOption): NewSwitchOptionState {
if (!target) {
return <any>target;
}
const NAME = deploy_helpers.normalizeString( target.name );
const STATES = getSelectedSwitchOptions();
if (STATES) {
STATES[NAME] = option;
return {
option: STATES[NAME],
target: target,
};
}
}
function updateButtons() {
const ME: vs_deploy.Deployer = this;
BUTTONS.forEach(btn => {
const SWITCH_NAME = getSwitchName(btn.switch, btn.index);
const OPTION = getCurrentOptionOf(btn.switch);
const VALUES: deploy_values.ValueBase[] = [
new deploy_values.StaticValue({
name: 'selectedSwitch',
value: SWITCH_NAME,
}),
new deploy_values.StaticValue({
name: 'selectedSwitchOption',
value: false === OPTION ? undefined
: getSwitchOptionName(OPTION, OPTION.__index),
}),
];
ME.getValues().forEach(v => {
VALUES.push(v);
});
let text = deploy_helpers.toStringSafe(
deploy_values.replaceWithValues(VALUES, btn.settings.text)
).trim();
if ('' === text) {
// default text
text = i18.t('plugins.switch.button.text',
SWITCH_NAME);
}
let tooltip = deploy_helpers.toStringSafe(
deploy_values.replaceWithValues(VALUES, btn.settings.tooltip)
).trim();
if ('' === tooltip) {
// default tooltip
if (false === OPTION) {
tooltip = i18.t('plugins.switch.button.tooltip',
i18.t('plugins.switch.noOptionSelected'));
}
else {
tooltip = i18.t('plugins.switch.button.tooltip',
`'${getSwitchOptionName(OPTION, OPTION.__index)}'`);
}
}
btn.button.text = text;
btn.button.tooltip = tooltip;
});
}