-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextension.js
334 lines (299 loc) · 9.97 KB
/
extension.js
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
'use strict';
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode');
const fetch = require('node-fetch');
const fs = require('fs');
const path = require('path');
const punycode = require('punycode');
const exec = require('child_process').exec;
const sitesCache = {
time: 0,
sites: []
};
exports.activate = context => {
const commands = {
'site-ssh': commandSiteSSH,
'ssh-tunnel': commandSSHTunnel,
winscp: commandSiteWinSCP,
'site-putty': commandSitePuTTY,
'site-clone': commandGitClone,
'site-configs': commandSiteConfigs
};
const subscriptions = Object.entries(commands).map(tuple => {
return vscode.commands.registerCommand(
'ansible-server-sites.' + tuple[0],
proxySiteCommand(tuple[1])
);
});
for (let i = 0; i < subscriptions.length; i++) {
context.subscriptions.push(subscriptions[i]);
}
};
exports.deactivate = () => {};
// proxy site command, select site, then call command
const proxySiteCommand = (command, site = null) => {
return async function() {
// from .ansible-site file
if (!site) {
const cacheJsonPath = vscode.workspace.rootPath + '/.ansible-site';
if (fs.existsSync(cacheJsonPath)) {
const jsonRaw = fs.readFileSync(cacheJsonPath).toString();
site = JSON.parse(jsonRaw);
}
}
// from select
if (!site) site = await getSites().then(selectSite);
// site not defined
if (!site) return false;
return command(site);
};
};
const commandSiteSSH = async site => {
const terminal = vscode.window.createTerminal(site.domain);
terminal.sendText(site.ssh_command);
terminal.show();
};
const commandSSHTunnel = async site => {
const terminal = vscode.window.createTerminal(site.domain + 'SSH tunnel');
terminal.sendText(site.ssh_command + ' -R 9000:localhost:9000');
terminal.show();
};
const commandSiteWinSCP = async site => {
const config = vscode.workspace.getConfiguration('ansible-server-sites');
const winscpPath = config.get('winscp_path');
const userHost = site.user + '@' + site.host;
exec(`"${winscpPath}" "${userHost}`);
};
const commandSitePuTTY = async site => {
const config = vscode.workspace.getConfiguration('ansible-server-sites');
const puttyPath = config.get('putty_path');
const userHost = site.user + '@' + site.domain;
exec(`START ${puttyPath} ${userHost}`);
};
const commandGitClone = async site => {
const url = await vscode.window.showInputBox({
value: site.git_clone_url,
prompt: 'Repository URL',
ignoreFocusOut: true
});
const config = vscode.workspace.getConfiguration('git');
const value = config.get('defaultCloneDirectory') || process.HOMEPATH;
const parentPath = await vscode.window.showInputBox({
prompt: 'Parent Directory',
value,
ignoreFocusOut: true
});
const name = path.basename(site.site_root);
let clonePath = parentPath + path.sep + name;
clonePath = clonePath.split('\\').join('/');
// Open project in new window
if (fs.existsSync(clonePath)) {
vscode.window.showInformationMessage(
name + ' exists at ' + parentPath + ', opening in new window'
);
const uri = vscode.Uri.parse('file:///' + clonePath);
vscode.commands.executeCommand('vscode.openFolder', uri, true);
return false;
}
// clone terminal command
const terminal = vscode.window.createTerminal();
const sshCommand = 'git clone ' + url + ' ' + clonePath;
const openCommand = 'code ' + clonePath;
terminal.sendText(sshCommand + ' && ' + openCommand);
terminal.show();
// wait for project directory appears
let interval = setInterval(async function() {
if (fs.existsSync(clonePath)) {
await commandSiteConfigs(site, clonePath, true);
clearInterval(interval);
vscode.window.showInformationMessage('Configs created for ' + clonePath);
}
}, 1000);
// this.git.clone(url, parentPath);
// try {
// vscode.window.withProgress({ location: ProgressLocation.SourceControl, title: "Cloning git repository..." }, () => clonePromise);
// vscode.window.withProgress({ location: ProgressLocation.Window, title: "Cloning git repository..." }, () => clonePromise);
// const repositoryPath = clonePromise;
// const open = "Open Repository";
// const result = vscode.window.showInformationMessage("Would you like to open the cloned repository?", open);
// const openFolder = result === open;
// if (openFolder) {
// commands.executeCommand('vscode.openFolder', Uri.file(repositoryPath));
// }
// } catch (err) {
// throw err;
// }
};
const commandSiteConfigs = async (site, projectRoot = null, yesToAll = false) => {
const settingsPath = projectRoot + '/.vscode';
if (!fs.existsSync(settingsPath)) fs.mkdirSync(settingsPath);
const debugData = {
name: 'Listen for XDebug',
type: 'php',
request: 'launch',
port: 9000,
serverSourceRoot: site.site_root,
localSourceRoot: '${workspaceRoot}'
};
const sessionName = site.user + '@' + site.host;
let winscpConfig = '';
winscpConfig += `[Sessions\\${sessionName}]\n`;
winscpConfig += `HostName=${site.host}\n`;
winscpConfig += `UserName=${site.user}\n`;
winscpConfig += `LocalDirectory=C:\n`;
winscpConfig += `RemoteDirectory=${site.site_root}`;
const deployConfig = {
packages: [
{
name: site.domain,
deployOnSave: true,
fastCheckOnSave: true,
targets: ['sftp'],
files: ['**/*']
}
],
targets: [
{
type: 'sftp',
name: 'sftp',
dir: site.site_root,
host: site.host,
agent: 'pageant',
user: site.user,
password: '...'
}
]
};
let msg;
// .ansible-site
msg = 'Bind current project to ' + site.domain + '?';
if (yesToAll || (!fs.existsSync(cacheJsonPath) && (await confirmAction(msg)))) {
const cacheJsonPath = settingsPath + '/.ansible-site';
try {
fs.writeFileSync(cacheJsonPath, JSON.stringify(site, null, '\t'));
} catch (err) {
vscode.window.showErrorMessage('Unable to write to ' + cacheJsonPath);
}
}
// deploy reloaded
msg = 'Write deploy reloaded config to workspace settings?';
if (yesToAll || (await confirmAction(msg))) {
const workspaceSettingsPath = settingsPath + '/settings.json';
try {
let settings = {};
if (fs.existsSync(workspaceSettingsPath)) {
settings = JSON.parse(fs.readFileSync(workspaceSettingsPath));
}
settings['deploy.reloaded'] = deployConfig;
fs.writeFileSync(workspaceSettingsPath, JSON.stringify(settings, null, '\t'));
} catch (err) {
vscode.window.showErrorMessage('Unable to write to ' + workspaceSettingsPath);
}
}
// launch.json
msg = 'Write xdebug configuration to launch.json?';
if (yesToAll || (await confirmAction(msg))) {
const launchPath = settingsPath + '/launch.json';
try {
let settings = {
version: '0.2.0',
configurations: []
};
if (fs.existsSync(launchPath)) {
settings = JSON.parse(fs.readFileSync(launchPath));
}
settings.configurations.push(debugData);
fs.writeFileSync(launchPath, JSON.stringify(settings, null, '\t'));
} catch (err) {
vscode.window.showErrorMessage('Unable to write to ' + launchPath);
}
}
// winscp.ini
msg = 'Write winscp.ini?';
if (process.platform == 'win32') {
const config = vscode.workspace.getConfiguration('ansible-server-sites');
const winscpIniPath = config.get('winscp_ini_path') || process.env.APPDATA + '\\winscp.ini';
if (fs.existsSync(winscpIniPath)) {
if (yesToAll || (await confirmAction(msg))) {
try {
fs.appendFileSync(winscpIniPath, '\n\n' + winscpConfig);
} catch (err) {
vscode.window.showErrorMessage('Unable to write to ' + winscpIniPath);
}
}
} else {
vscode.window.showErrorMessage(
winscpIniPath +
' not found, open Options - Preferences - Storage - set Configuration storage - Automatic or Custom INI file'
);
}
}
};
const confirmAction = async message => {
const answer = await vscode.window.showInformationMessage(
message,
{
title: 'Yes',
id: 'Yes'
},
{
title: 'No',
id: 'No'
}
);
return answer && answer.id == 'Yes';
};
const selectSite = sites => {
const options = sites.map(site => {
return {
label: punycode.toUnicode(site.domain),
description: site.host + (site.group ? ' / ' + site.group : '')
};
});
return new Promise((resolve, reject) => {
const p = vscode.window.showQuickPick(options, { placeHolder: 'domain' });
p.then(function(val) {
//console.log('selected: ', val);
if (val === undefined) {
return 'Nothing selected';
}
const ind = options.indexOf(val);
const site = sites[ind];
resolve(site);
});
});
};
const getSites = () => {
const config = vscode.workspace.getConfiguration('ansible-server-sites');
const cacheTime = config.get('json_cache_time', 300);
return new Promise((resolve, reject) => {
// cache
if (sitesCache.sites.length > 0) {
const cacheAgeSeconds = (new Date().getTime() - sitesCache.time.getTime()) / 1000;
// console.log('cache age: ' + cacheAgeSeconds);
if (cacheAgeSeconds < cacheTime) {
// console.log('resolve sites from runtime cache');
resolve(sitesCache.sites);
return;
}
}
// fetch
// console.log('resolve sites from url...')
const url = config.get('json_url');
fetch(url)
.then(response => {
if (response.status != 200) {
throw new Error('Failed to fetch ' + url + ', status ' + response.status);
}
return response.json();
})
.then(json => {
sitesCache.sites = json.sites;
sitesCache.time = new Date();
// console.log('store global cache');
resolve(sitesCache.sites);
})
.catch(err => console.error(err));
});
};