Repository navigation
Expand file tree
/
Copy pathextension.js
More file actions
825 lines (688 loc) · 26.7 KB
/
Copy pathextension.js
File metadata and controls
825 lines (688 loc) · 26.7 KB
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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
const vscode = require('vscode');
const fs = require('fs');
const path = require('path');
const os = require('os');
const https = require('https');
const { exec } = require('child_process');
const { promisify } = require('util');
const execAsync = promisify(exec);
/**
* @param {vscode.ExtensionContext} context
*/
function activate(context) {
console.log('CircuitPython Uploader is now active!');
// Command for setting device path
let setPathCmd = vscode.commands.registerCommand('circuitpython-uploader.setPath', async () => {
const config = vscode.workspace.getConfiguration('circuitpython-uploader');
const currentPath = config.get('devicePath') || '';
const newPath = await vscode.window.showInputBox({
prompt: 'Enter CircuitPython device path',
placeHolder: os.platform() === 'win32' ? 'D:' : '/mnt/circuitpy',
value: currentPath
});
if (newPath !== undefined) {
await config.update('devicePath', newPath, vscode.ConfigurationTarget.Global);
vscode.window.showInformationMessage(`Device path set to: ${newPath}`);
}
});
// Command for auto-detecting device
let autoDetectCmd = vscode.commands.registerCommand('circuitpython-uploader.autoDetect', async () => {
const selectedDevice = await selectDevice('Select CircuitPython device:', true);
if (!selectedDevice) return;
const config = vscode.workspace.getConfiguration('circuitpython-uploader');
await config.update('devicePath', selectedDevice.path, vscode.ConfigurationTarget.Global);
if (selectedDevice.info) {
vscode.window.showInformationMessage(
`Device set to: ${selectedDevice.info.board} (v${selectedDevice.info.version}) at ${selectedDevice.path}`
);
} else {
vscode.window.showInformationMessage(`Device set to: ${selectedDevice.path}`);
}
});
// Command for uploading file
let uploadCmd = vscode.commands.registerCommand('circuitpython-uploader.upload', async () => {
await uploadFile('code.py');
});
// Command for uploading file with original filename
let uploadAsFilenameCmd = vscode.commands.registerCommand('circuitpython-uploader.uploadAsFilename', async () => {
const editor = vscode.window.activeTextEditor;
if (!editor) {
vscode.window.showErrorMessage('Please open a Python file to upload');
return;
}
const originalFilename = path.basename(editor.document.fileName);
await uploadFile(originalFilename);
});
// Command for fixing libraries
let fixLibsCmd = vscode.commands.registerCommand('circuitpython-uploader.fixLibs', async () => {
await fixLibraries();
});
// Command for uploading single library
let uploadLibCmd = vscode.commands.registerCommand('circuitpython-uploader.uploadLib', async () => {
await uploadSingleLibrary();
});
// Command for showing device info
let showInfoCmd = vscode.commands.registerCommand('circuitpython-uploader.showInfo', async () => {
const config = vscode.workspace.getConfiguration('circuitpython-uploader');
let devicePath = config.get('devicePath');
if (!devicePath || !fs.existsSync(devicePath)) {
devicePath = await selectDevice('Select device to show info:');
if (!devicePath) return;
}
const info = getCircuitPythonInfo(devicePath);
if (info) {
// Use Output Channel for cross-platform compatibility
const outputChannel = vscode.window.createOutputChannel('CircuitPython Device Info');
outputChannel.clear();
outputChannel.show();
const infoText = `CircuitPython Device Information
Version: ${info.version}
Board: ${info.board}
Device Path: ${devicePath}`;
outputChannel.appendLine(infoText);
// Also show a quick notification
vscode.window.showInformationMessage(
`Device Info: ${info.board} (v${info.version}) - Check Output Panel for details`
);
} else {
vscode.window.showWarningMessage(`No version info found at ${devicePath}`);
}
});
context.subscriptions.push(setPathCmd, autoDetectCmd, uploadCmd, uploadAsFilenameCmd, fixLibsCmd, uploadLibCmd, showInfoCmd);
}
/**
* Upload file to CircuitPython device
* @param {string} targetFilename - Name of the file on the device (e.g., 'code.py' or original filename)
*/
async function uploadFile(targetFilename) {
const editor = vscode.window.activeTextEditor;
if (!editor || editor.document.languageId !== 'python') {
vscode.window.showErrorMessage('Please open a Python file to upload');
return;
}
const config = vscode.workspace.getConfiguration('circuitpython-uploader');
let devicePath = config.get('devicePath');
// If no path configured, try to detect
if (!devicePath) {
devicePath = await selectDevice('Select target device:');
if (!devicePath) return;
}
// Check if path exists
if (!fs.existsSync(devicePath)) {
vscode.window.showErrorMessage(`Device path does not exist: ${devicePath}`);
return;
}
const targetPath = path.join(devicePath, targetFilename);
try {
// Save current file first
await editor.document.save();
// Create backup if enabled and target file exists (will be overwritten)
if (config.get('createBackup', true) && fs.existsSync(targetPath)) {
await createBackup(targetPath);
}
// Write file to device
fs.writeFileSync(targetPath, editor.document.getText(), 'utf8');
vscode.window.showInformationMessage(`Uploaded as ${targetFilename} to ${devicePath}`);
} catch (error) {
vscode.window.showErrorMessage(`Upload failed: ${error.message}`);
}
}
/**
* Select device from detected devices
*/
async function selectDevice(placeHolder, returnDevice = false) {
const devices = await detectCircuitPythonDevices();
if (devices.length === 0) {
vscode.window.showWarningMessage('No CircuitPython device detected.');
return null;
}
if (devices.length === 1) {
if (returnDevice) {
return devices[0];
} else {
return devices[0].path;
}
}
// Multiple devices - ask user
const items = devices.map(device => ({
label: path.basename(device.path) || device.path,
description: device.info ? `v${device.info.version} - ${device.info.board}` : device.path,
detail: device.path,
path: device.path,
device: device
}));
const selected = await vscode.window.showQuickPick(items, {
placeHolder: placeHolder,
matchOnDescription: true,
matchOnDetail: true
});
if (!selected) return null;
return returnDevice ? selected.device : selected.path;
}
/**
* Get CircuitPython version info from boot_out.txt
*/
function getCircuitPythonInfo(devicePath) {
try {
const bootOutPath = path.join(devicePath, 'boot_out.txt');
if (!fs.existsSync(bootOutPath)) {
return null;
}
const content = fs.readFileSync(bootOutPath, 'utf8');
const firstLine = content.split('\n')[0];
if (!firstLine) return null;
// Extract version - look for CircuitPython followed by version number
const versionMatch = firstLine.match(/CircuitPython\s+([\d.]+)/i);
// Extract board - text after semicolon
const boardMatch = firstLine.match(/;\s*([^;]+?)(?:\s+with\s+|$)/);
return {
version: versionMatch ? versionMatch[1] : 'Unknown',
board: boardMatch ? boardMatch[1].trim() : 'Unknown board'
};
} catch (error) {
return null;
}
}
/**
* Detect CircuitPython devices
* @returns {Promise<Array<{path: string, info?: {version: string, board: string}}>>} Array of device objects
*/
async function detectCircuitPythonDevices() {
const platform = os.platform();
let searchPaths = [];
if (platform === 'win32') {
// Windows - check drive letters
'DEFGHIJKLMNOPQRSTUVWXYZ'.split('').forEach(drive => {
const drivePath = `${drive}:`;
if (fs.existsSync(drivePath)) {
searchPaths.push(drivePath);
}
});
} else if (platform === 'darwin') {
// macOS
const volumesPath = '/Volumes';
if (fs.existsSync(volumesPath)) {
fs.readdirSync(volumesPath).forEach(volume => {
searchPaths.push(path.join(volumesPath, volume));
});
}
} else {
// Linux - simplified to most common paths
const mediaPath = path.join('/media', os.userInfo().username);
if (fs.existsSync(mediaPath)) {
fs.readdirSync(mediaPath).forEach(mount => {
searchPaths.push(path.join(mediaPath, mount));
});
}
}
// Find CircuitPython devices
const devices = [];
for (const devicePath of searchPaths) {
try {
const files = fs.readdirSync(devicePath);
// Simple check for CircuitPython indicators
const hasCodePy = files.includes('code.py') || files.includes('main.py');
const hasBootOut = files.includes('boot_out.txt');
if (hasCodePy || hasBootOut) {
const info = getCircuitPythonInfo(devicePath);
devices.push({
path: devicePath,
info: info
});
}
} catch (error) {
continue;
}
}
return devices;
}
/**
* Create backup of current code.py
*/
async function createBackup(targetPath) {
try {
// Create backup directory
const backupDir = path.join(os.tmpdir(), 'circuitpy-backups');
if (!fs.existsSync(backupDir)) {
fs.mkdirSync(backupDir, { recursive: true });
}
// Create timestamped backup
const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, -5);
const backupPath = path.join(backupDir, `code.py.${timestamp}.bak`);
// Copy file
const content = fs.readFileSync(targetPath, 'utf8');
fs.writeFileSync(backupPath, content, 'utf8');
console.log(`Backup created: ${backupPath}`);
} catch (error) {
console.error('Backup failed:', error);
}
}
/**
* Known library dependencies
*/
const LIBRARY_DEPENDENCIES = {
'adafruit_asyncio': ['adafruit_ticks']
};
/**
* Internal/built-in CircuitPython modules that should not be installed from the bundle.
*/
const INTERNAL_MODULES = new Set([
'adafruit_bus_device', 'adafruit_pixelbuf', 'aesio', 'alarm', 'analogbufio',
'analogio', 'array', 'atexit', 'audiobusio', 'audiocore', 'audiomixer',
'audiomp3', 'audiopwmio', 'binascii', 'bitbangio', 'bitmapfilter',
'bitmaptools', 'bitops', 'board', 'builtins', 'busdisplay', 'busio',
'codeop', 'collections', 'countio', 'digitalio', 'displayio',
'epaperdisplay', 'errno', 'floppyio', 'fontio', 'fourwire', 'framebufferio',
'getpass', 'gifio', 'hashlib', 'i2cdisplaybus', 'i2ctarget', 'imagecapture',
'io', 'jpegio', 'json', 'keypad', 'keypad_demux', 'locale', 'lvfontio',
'math', 'memorymap', 'microcontroller', 'msgpack', 'neopixel_write', 'nvm',
'onewireio', 'os', 'paralleldisplaybus', 'picodvi', 'pulseio', 'pwmio',
'qrio', 'rainbowio', 'random', 're', 'rgbmatrix', 'rotaryio', 'rp2pio',
'rtc', 'sdcardio', 'select', 'sharpdisplay', 'storage', 'struct',
'supervisor', 'synthio', 'sys', 'terminalio', 'tilepalettemapper', 'time',
'touchio', 'traceback', 'ulab', 'usb', 'usb_cdc', 'usb_hid', 'usb_host',
'usb_midi', 'usb_video', 'vectorio', 'warnings', 'watchdog', 'zlib'
]);
/**
* Extract ZIP file using system tools
*/
async function extractZip(zipPath, destDir) {
// Clean destination directory
if (fs.existsSync(destDir)) {
fs.rmSync(destDir, { recursive: true, force: true });
}
fs.mkdirSync(destDir, { recursive: true });
try {
const platform = os.platform();
if (platform === 'win32') {
// Windows - use tar (available from Windows 10)
const command = `tar -xf "${zipPath}" -C "${destDir}"`;
await execAsync(command);
} else {
// macOS and Linux - use unzip
const command = `unzip -q "${zipPath}" -d "${destDir}"`;
await execAsync(command);
}
} catch (error) {
throw new Error(`Failed to extract ZIP: ${error.message}`);
}
}
/**
* Get bundle cache directory
*/
function getBundleCacheDir() {
return path.join(os.tmpdir(), 'circuitpy-bundle-cache');
}
/**
* Download file from URL
*/
async function downloadFile(url, destPath) {
try {
const response = await fetch(url, {
headers: { 'User-Agent': 'CircuitPython-VSCode' }
});
if (!response.ok) {
throw new Error(`Download failed: ${response.status} ${response.statusText}`);
}
if (!response.body) {
throw new Error('Response body is null');
}
const arrayBuffer = await response.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
// Write buffer to file
fs.writeFileSync(destPath, buffer);
} catch (error) {
if (fs.existsSync(destPath)) {
fs.unlinkSync(destPath);
}
throw error;
}
}
/**
* Get or download CircuitPython bundle
*/
async function getBundle(cpVersion) {
const cacheDir = getBundleCacheDir();
if (!fs.existsSync(cacheDir)) {
fs.mkdirSync(cacheDir, { recursive: true });
}
// Get major version for bundle
const cpMajor = parseInt(cpVersion.split('.')[0]);
const bundleDir = path.join(cacheDir, `bundle-${cpMajor}.x`);
const bundleInfoFile = path.join(bundleDir, 'bundle.json');
// Check if bundle exists and is recent (less than 1 week old)
if (fs.existsSync(bundleInfoFile)) {
const info = JSON.parse(fs.readFileSync(bundleInfoFile, 'utf8'));
const age = Date.now() - info.downloadDate;
const oneWeek = 7 * 24 * 60 * 60 * 1000;
if (age < oneWeek) {
return bundleDir;
}
}
// Download matching bundle
await vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: `Downloading CircuitPython ${cpMajor}.x bundle...`,
cancellable: false
}, async (progress) => {
try {
// Get latest release info
const releasesUrl = `https://api.github.com/repos/adafruit/Adafruit_CircuitPython_Bundle/releases/latest`;
const releaseData = await fetchJson(releasesUrl);
// Find bundle for this CP version
const bundleName = `adafruit-circuitpython-bundle-${cpMajor}.x-mpy-`;
const asset = releaseData.assets.find(a =>
a.name.startsWith(bundleName) && a.name.endsWith('.zip')
);
if (!asset) {
throw new Error(
`No bundle found for CircuitPython ${cpMajor}.x.\n` +
`Please update to CircuitPython 9.x or newer for library management support.`
);
}
progress.report({ message: `Downloading bundle...` });
// Download ZIP
const zipPath = path.join(cacheDir, asset.name);
await downloadFile(asset.browser_download_url, zipPath);
progress.report({ message: 'Extracting bundle...' });
// Extract ZIP
await extractZip(zipPath, bundleDir);
// Find the lib folder (it's in a subdirectory)
const entries = fs.readdirSync(bundleDir);
const bundleSubdir = entries.find(e => e.startsWith('adafruit-circuitpython-bundle'));
if (bundleSubdir) {
const libPath = path.join(bundleDir, bundleSubdir, 'lib');
if (fs.existsSync(libPath)) {
// Move lib folder to bundle root
const newLibPath = path.join(bundleDir, 'lib');
if (fs.existsSync(newLibPath)) {
fs.rmSync(newLibPath, { recursive: true, force: true });
}
fs.renameSync(libPath, newLibPath);
}
// Clean up subdirectory
fs.rmSync(path.join(bundleDir, bundleSubdir), { recursive: true, force: true });
}
// Save bundle info
fs.writeFileSync(bundleInfoFile, JSON.stringify({
bundleVersion: cpMajor + '.x',
downloadDate: Date.now()
}));
// Clean up ZIP
fs.unlinkSync(zipPath);
} catch (error) {
throw error;
}
});
return bundleDir;
}
/**
* Fetch JSON from URL
*/
async function fetchJson(url) {
return new Promise((resolve, reject) => {
const requestOptions = {
headers: { 'User-Agent': 'CircuitPython-VSCode' }
};
https.get(url, requestOptions, (res) => {
let data = '';
res.on('data', chunk => {
data += chunk;
});
res.on('end', () => {
try {
const jsonData = JSON.parse(data);
resolve(jsonData);
} catch (e) {
reject(e);
}
});
}).on('error', (err) => {
reject(err);
});
});
}
/**
* Parse imports from Python code
*/
function parseImports(code) {
const imports = new Set();
const lines = code.split('\n');
for (const line of lines) {
// Skip comments
if (line.trim().startsWith('#')) continue;
// Match imports
const importMatch = line.match(/^\s*import\s+([\w,\s]+)/);
const fromMatch = line.match(/^\s*from\s+(\w+)/);
if (importMatch) {
// Split by comma for multiple imports
importMatch[1].split(',').forEach(module => {
imports.add(module.trim().split('.')[0]);
});
} else if (fromMatch) {
imports.add(fromMatch[1]);
}
}
return Array.from(imports);
}
/**
* Get library files including dependencies
*/
function getLibraryFiles(libName, bundleLibPath) {
const files = new Set();
const processed = new Set();
function addLibrary(name) {
if (processed.has(name)) return;
processed.add(name);
// Check for .mpy file
const mpyFile = `${name}.mpy`;
const mpyPath = path.join(bundleLibPath, mpyFile);
if (fs.existsSync(mpyPath)) {
files.add(mpyFile);
}
// Check for directory (package)
const dirPath = path.join(bundleLibPath, name);
if (fs.existsSync(dirPath) && fs.statSync(dirPath).isDirectory()) {
files.add(name);
}
// Add dependencies
if (LIBRARY_DEPENDENCIES[name]) {
for (const dep of LIBRARY_DEPENDENCIES[name]) {
addLibrary(dep);
}
}
}
addLibrary(libName);
return Array.from(files);
}
/**
* Install a library with its dependencies
*/
function installLibrary(libName, bundleLibPath, deviceLibPath) {
const files = getLibraryFiles(libName, bundleLibPath);
if (files.length === 0) {
return false; // Library not found
}
for (const file of files) {
const sourcePath = path.join(bundleLibPath, file);
const destPath = path.join(deviceLibPath, file);
if (fs.statSync(sourcePath).isDirectory()) {
copyDirectory(sourcePath, destPath);
} else {
fs.copyFileSync(sourcePath, destPath);
}
}
return true; // Successfully installed
}
/**
* Fix libraries - auto-install required libraries
*/
async function fixLibraries() {
try {
// Get device path
const config = vscode.workspace.getConfiguration('circuitpython-uploader');
const devicePath = config.get('devicePath');
if (!devicePath || !fs.existsSync(devicePath)) {
vscode.window.showErrorMessage('Please set device path first');
return;
}
// Get device info
const info = getCircuitPythonInfo(devicePath);
if (!info) {
vscode.window.showErrorMessage('Cannot determine CircuitPython version');
return;
}
// Read code.py
const codePath = path.join(devicePath, 'code.py');
if (!fs.existsSync(codePath)) {
vscode.window.showWarningMessage('No code.py found on device');
return;
}
const code = fs.readFileSync(codePath, 'utf8');
const librariesAll = parseImports(code);
// Filter out built-in modules that must not be installed from the bundle
const libraries = librariesAll.filter(lib => !INTERNAL_MODULES.has(lib));
if (libraries.length === 0) {
vscode.window.showInformationMessage('No imports found in code.py');
return;
}
// Get bundle
const bundleDir = await getBundle(info.version);
const bundleLibPath = path.join(bundleDir, 'lib');
// Create lib folder on device if needed
const deviceLibPath = path.join(devicePath, 'lib');
if (!fs.existsSync(deviceLibPath)) {
fs.mkdirSync(deviceLibPath);
}
// Install libraries
let installed = [];
let notFound = [];
await vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: 'Installing libraries...',
cancellable: false
}, async (progress) => {
for (const lib of libraries) {
progress.report({ message: `Installing ${lib}...` });
if (installLibrary(lib, bundleLibPath, deviceLibPath)) {
installed.push(lib);
} else {
notFound.push(lib);
}
}
});
// Show results
if (installed.length === 0 && notFound.length === 0) {
vscode.window.showInformationMessage('All libraries already installed');
} else {
let message = [];
if (installed.length > 0) {
message.push(`✅ Installed: ${installed.join(', ')}`);
}
if (notFound.length > 0) {
message.push(`⚠️ Not in bundle: ${notFound.join(', ')}`);
}
vscode.window.showInformationMessage(message.join('\n'));
}
} catch (error) {
vscode.window.showErrorMessage(`Failed: ${error.message}`);
}
}
/**
* Upload single library
*/
async function uploadSingleLibrary() {
try {
// Get device path
const config = vscode.workspace.getConfiguration('circuitpython-uploader');
let devicePath = config.get('devicePath');
if (!devicePath || !fs.existsSync(devicePath)) {
vscode.window.showErrorMessage('Please set device path first');
return;
}
// Get device info
const info = getCircuitPythonInfo(devicePath);
if (!info) {
vscode.window.showErrorMessage('Cannot determine CircuitPython version');
return;
}
// Ask for library name
const libName = await vscode.window.showInputBox({
prompt: 'Enter library name',
placeHolder: 'e.g., adafruit_requests, adafruit_display_text',
validateInput: (value) => {
if (!value) return 'Library name required';
return null;
}
});
if (!libName) return;
// Get bundle
let bundleDir;
try {
bundleDir = await getBundle(info.version);
} catch (error) {
vscode.window.showErrorMessage(
`Failed to download bundle: ${error.message}. ` +
`Check your internet connection or try clearing the cache.`
);
return;
}
const bundleLibPath = path.join(bundleDir, 'lib');
if (!fs.existsSync(bundleLibPath)) {
vscode.window.showErrorMessage('Bundle lib folder not found');
return;
}
// Get library files with dependencies
const files = getLibraryFiles(libName, bundleLibPath);
if (files.length === 0) {
vscode.window.showErrorMessage(`Library "${libName}" not found in bundle`);
return;
}
// Create lib folder on device if needed
const deviceLibPath = path.join(devicePath, 'lib');
if (!fs.existsSync(deviceLibPath)) {
fs.mkdirSync(deviceLibPath);
}
// Install library and dependencies
for (const file of files) {
const sourcePath = path.join(bundleLibPath, file);
const destPath = path.join(deviceLibPath, file);
if (fs.statSync(sourcePath).isDirectory()) {
// Copy directory
copyDirectory(sourcePath, destPath);
} else {
// Copy file
fs.copyFileSync(sourcePath, destPath);
}
}
vscode.window.showInformationMessage(
`Installed ${libName}` +
(files.length > 1 ? ` with ${files.length - 1} dependencies` : '')
);
} catch (error) {
vscode.window.showErrorMessage(`Failed to upload library: ${error.message}`);
}
}
/**
* Copy directory recursively
*/
function copyDirectory(source, dest) {
if (!fs.existsSync(dest)) {
fs.mkdirSync(dest);
}
const files = fs.readdirSync(source);
for (const file of files) {
const sourcePath = path.join(source, file);
const destPath = path.join(dest, file);
if (fs.statSync(sourcePath).isDirectory()) {
copyDirectory(sourcePath, destPath);
} else {
fs.copyFileSync(sourcePath, destPath);
}
}
}
function deactivate() {}
module.exports = {
activate,
deactivate
}