forked from mrmlnc/vscode-duplicate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextension.js
83 lines (66 loc) · 2.09 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
'use strict';
const path = require('path');
const fs = require('fs');
const co = require('co');
const copyFile = require('cp-file');
const escapeRegExp = require('lodash.escaperegexp');
const vscode = require('vscode');
function pathsExists(filepath) {
return new Promise((resolve) => {
fs.stat(filepath, (err) => resolve(!err));
});
}
function promptFileName(oldFileInfo) {
return vscode.window.showInputBox({
placeHolder: 'Enter the new path for the duplicate.',
value: `${oldFileInfo.name}-copy`
});
}
function duplicate(document) {
if (!document || !document.fsPath) {
const editor = vscode.editor || vscode.window.activeTextEditor;
if (!editor) {
return;
}
document = editor.document.uri;
}
const oldFileInfo = path.parse(document.fsPath);
co(function* () {
let newFileName = yield promptFileName(oldFileInfo);
if (!newFileName) {
return;
}
if (!path.extname(newFileName)) {
newFileName += oldFileInfo.ext;
}
const newFilePath = path.join(oldFileInfo.dir, newFileName);
const newFileExists = yield pathsExists(newFilePath);
if (newFileExists) {
const userQuestionMessage = `File **${newFileName}** already exists. Do you want to overwrite the existing file?`;
const buttonOk = {
title: 'OK',
isCloseAffordance: false
};
const userAnswer = yield vscode.window.showWarningMessage(userQuestionMessage, buttonOk);
if (!userAnswer) {
return;
}
}
return copyFile(document.fsPath, newFilePath);
}).catch((err) => {
if (err.code === 'EISDIR') {
err.message = 'you can duplicate only files.';
}
const errMsgRegExp = new RegExp(escapeRegExp(oldFileInfo.dir), 'g');
const errMsg = err.message
.replace(errMsgRegExp, '')
.replace(/[\\|\/]/g, '')
.replace(/`|'/g, '**');
vscode.window.showErrorMessage(`Error: ${errMsg}`);
});
}
function activate(context) {
const disposable = vscode.commands.registerCommand('duplicate.execute', duplicate);
context.subscriptions.push(disposable);
}
exports.activate = activate;