-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathextension.ts
212 lines (193 loc) · 7.53 KB
/
extension.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
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import vscode = require('vscode');
import tinify = require('tinify');
import path = require('path');
import { spawnSync } from 'child_process'
import { ExtensionContext, Disposable, Uri } from 'vscode';
/**
* Function to compress a single image.
* @param {Object} file
*/
const compressImage = (file: Uri) => {
const shouldOverwrite: boolean =
vscode.workspace
.getConfiguration('tinypng')
.get<boolean>('forceOverwrite') || false;
// Note: Define the destination file path for the compressed image.
let destinationFilePath = file.fsPath;
// In case the extension should not overwrite the source file (default)…
if (!shouldOverwrite) {
// …take the postfix defined in the settings.
const postfix = vscode.workspace
.getConfiguration('tinypng')
.get<string>('compressedFilePostfix');
const parsedPath = path.parse(file.fsPath);
// Generate file in format: <name><postfix>.<ext>
destinationFilePath = path.join(
parsedPath.dir,
`${parsedPath.name}${postfix}${parsedPath.ext}`
);
}
const statusBarItem = vscode.window.createStatusBarItem(
vscode.StatusBarAlignment.Left
);
statusBarItem.text = `Compressing file ${file.fsPath}...`;
statusBarItem.show();
return tinify.fromFile(file.fsPath).toFile(destinationFilePath, (error) => {
statusBarItem.hide();
if (error) {
if (error instanceof tinify.AccountError) {
// Verify your API key and account limit.
console.error(
'Authentication failed. Have you set the API Key?'
);
vscode.window.showErrorMessage(
'Authentication failed. Have you set the API Key?'
);
} else if (error instanceof tinify.ClientError) {
// Check your source image and request options.
console.error(
'Ooops, there is an error. Please check your source image and settings.'
);
vscode.window.showErrorMessage(
'Ooops, there is an error. Please check your source image and settings.'
);
} else if (error instanceof tinify.ServerError) {
// Temporary issue with the Tinify API.
console.error('TinyPNG API is currently not available.');
vscode.window.showErrorMessage(
'TinyPNG API is currently not available.'
);
} else if (error instanceof tinify.ConnectionError) {
// A network connection error occurred.
console.error(
'Network issue occurred. Please check your internet connectivity.'
);
vscode.window.showErrorMessage(
'Network issue occurred. Please check your internet connectivity.'
);
} else {
// Something else went wrong, unrelated to the Tinify API.
console.error(error.message);
vscode.window.showErrorMessage(error.message);
}
} else {
vscode.window.showInformationMessage(
`Successfully compressed ${file.fsPath} to ${destinationFilePath}!`
);
}
});
};
/**
* Validate the user.
* @param {function} onSuccess - Function to call on success
* @param {function} onFailure - Function to call on failure
*/
const validate = (
onSuccess: Function = () => {},
onFailure = (e: Error) => {}
) =>
tinify.validate(function (err: Error | null) {
if (err) {
onFailure(err);
} else {
onSuccess();
}
});
const afterValidation = (callback: Function) => validate(callback);
const compressStageFiles = (editorPath: string) => {
try {
const lines = spawnSync('git', ['diff', '--staged', '--diff-filter=ACMR', '--name-only', '-z'], { encoding: 'utf-8', cwd: editorPath })
const files = lines.stdout
.replace(/\u0000$/, '')
.split('\u0000')
.filter(f => /\.(png|jpg|jpeg|webp)$/.test(f))
if (files.length === 0) {
vscode.window.showInformationMessage(
`TinyPNG: No images found in the git stage.`
)
return
}
files.forEach(f => compressImage(Uri.parse(`${editorPath}/${f}`)))
} catch(err) {
vscode.window.showErrorMessage(
`TinyPNG: ${(err as Error).message}`
);
}
}
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
function activate(context: ExtensionContext) {
// Get API Key
const apiKey = vscode.workspace
.getConfiguration('tinypng')
.get<string>('apiKey');
if (!!apiKey) {
tinify.key = apiKey;
}
// Validate user
validate(
() => console.log('Validation successful!'),
(e: Error) => {
console.error(e.message);
vscode.window.showInformationMessage(
'TinyPNG: API validation failed. Be sure that you filled out tinypng.apiKey setting already.'
);
}
);
let disposableCompressFile = vscode.commands.registerCommand(
'extension.compressFile',
compressImage
);
context.subscriptions.push(disposableCompressFile);
let disposableCompressFolder: Disposable = vscode.commands.registerCommand(
'extension.compressFolder',
function (folder: Uri) {
vscode.workspace
.findFiles(
new vscode.RelativePattern(
folder.path,
`**/*.{png,jpg,jpeg,webp}`
)
)
.then((files: any) => files.forEach(compressImage));
}
);
context.subscriptions.push(disposableCompressFolder);
let disposableCompressionCount: Disposable =
vscode.commands.registerCommand('extension.getCompressionCount', () =>
afterValidation(() =>
vscode.window.showInformationMessage(
`TinyPNG: You already used ${tinify.compressionCount} compression(s) this month.`
)
)
);
context.subscriptions.push(disposableCompressionCount);
let disposableCompressGitStage: Disposable =
vscode.commands.registerCommand('extension.compressGitStage', () => {
const folders = vscode.workspace.workspaceFolders
if (!folders) {
vscode.window.showInformationMessage(
`TinyPNG: No editor path found.`
)
return
}
if (folders.length <= 1) {
compressStageFiles(folders[0].uri.fsPath)
return
}
const folderNames = folders.map(folder => folder.name)
vscode.window.showQuickPick(folderNames).then((folderName) => {
const folder = folders.find(folder => folder.name === folderName)
if (folder) {
compressStageFiles(folder.uri.fsPath)
}
})
});
context.subscriptions.push(disposableCompressGitStage)
}
exports.activate = activate;
// this method is called when your extension is deactivated
function deactivate() {}
exports.deactivate = deactivate;