Skip to content

Commit 72e07a7

Browse files
[test] Added -v func
1 parent f2732f7 commit 72e07a7

File tree

6 files changed

+200
-130
lines changed

6 files changed

+200
-130
lines changed

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "css-linter"
3-
version = "0.1.0"
3+
version = "1.8.0"
44
edition = "2021"
55

66
[dependencies]

src/main.rs

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -52,15 +52,30 @@ fn main() -> Result<()> {
5252
const COLOR_RESET: &str = "\u{001B}[0m";
5353

5454
let args: Vec<String> = env::args().collect();
55-
let path = args.get(1).unwrap_or_else(|| {
56-
eprintln!(
57-
"\n{}Error{}: Linting path must be specified",
58-
COLOR_RED, COLOR_RESET
59-
);
60-
process::exit(1);
61-
});
6255

63-
let minify_output = args.get(2);
56+
let path = match args.get(1) {
57+
Some(arg) if arg == "-v" => {
58+
println!("v{}", env!("CARGO_PKG_VERSION"));
59+
process::exit(0);
60+
}
61+
Some(arg) if arg == "--lint" => args.get(2).unwrap_or_else(|| {
62+
eprintln!(
63+
"\n{}Error{}: Linting path must be specified",
64+
COLOR_RED, COLOR_RESET
65+
);
66+
process::exit(1);
67+
}),
68+
Some(arg) => {
69+
eprintln!(
70+
"{}Error{}: Invalid argument: {}",
71+
COLOR_RED, COLOR_RESET, arg
72+
);
73+
process::exit(1);
74+
}
75+
None => todo!(),
76+
};
77+
78+
let minify = args.get(3).map_or("", |v| v) == "--minify";
6479

6580
if let Err(e) = env::set_current_dir(Path::new(path)) {
6681
eprintln!(
@@ -119,7 +134,6 @@ fn main() -> Result<()> {
119134

120135
let mut files_count = 0;
121136
let mut errors_count = 0;
122-
let minify = minify_output.map_or("", |v| v) == "--minify";
123137

124138
for (css_file, mut classes_tsx) in defined_classnames.clone() {
125139
if let Some(used_css) = used_classnames.get(&css_file) {

vscode-ext/.prettierrc

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
{
2+
"singleQuote": true,
3+
"trailingComma": "none",
4+
"endOfLine": "crlf",
5+
"bracketSpacing": true,
6+
"useTabs": false,
7+
"arrowParens": "avoid",
8+
"tabWidth": 4,
9+
"printWidth": 100
10+
}

vscode-ext/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
"name": "next-css-lint",
33
"displayName": "Next.Js CSS linter",
44
"description": "Displaying unused CSS classes in Next.Js projects",
5-
"version": "1.6.2",
5+
"version": "1.7.1",
66
"license": "MIT",
77
"repository": "https://github.com/Andcool-Systems/css-linter",
88
"author": {

vscode-ext/src/extension.ts

Lines changed: 114 additions & 99 deletions
Original file line numberDiff line numberDiff line change
@@ -5,107 +5,122 @@ import { binaries, install } from './installer';
55
import os from 'os';
66

77
export function activate(context: vscode.ExtensionContext) {
8-
const extension = vscode.extensions.getExtension('AndcoolSystems.next-css-lint');
9-
const version = extension!.packageJSON.version;
10-
11-
const diagnosticCollection = vscode.languages.createDiagnosticCollection('css-linter-diags');
12-
context.subscriptions.push(diagnosticCollection);
13-
14-
const platform = os.platform();
15-
const binary = binaries[platform];
16-
17-
const homedir = os.homedir();
18-
const exec_path = join(homedir, '.css-linter', binary);
19-
20-
function run_diag() {
21-
const workspacePath = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
22-
if (!workspacePath) {
23-
return;
24-
}
25-
26-
exec(`${exec_path} ${workspacePath} --minify`, (error, stdout, stderr) => {
27-
if (error || stderr) {
28-
console.error(`CSS-lint error: ${error || stderr}`);
29-
return;
30-
}
31-
32-
console.log(stdout);
33-
34-
diagnosticCollection.clear();
35-
const error_lines = stdout.split('\n');
36-
37-
if (error_lines.length === 0) {
38-
return;
39-
}
40-
41-
const diagnosticsMap: Map<string, vscode.Diagnostic[]> = new Map();
42-
for (let e_line of error_lines) {
43-
let frags = e_line.split(':');
44-
if (frags.length < 4) {
45-
continue;
46-
}
47-
48-
const filePath = frags[0];
49-
const line = parseInt(frags[1]) - 1;
50-
const col = parseInt(frags[2]);
51-
const len = parseInt(frags[3]);
52-
const message = frags[4];
53-
54-
const range = new vscode.Range(line, col, line, col + len);
55-
const diagnostic = new vscode.Diagnostic(range, message, vscode.DiagnosticSeverity.Warning);
56-
57-
const diagnostics = diagnosticsMap.get(filePath) || [];
58-
diagnostics.push(diagnostic);
59-
diagnosticsMap.set(filePath, diagnostics);
60-
}
61-
62-
diagnosticsMap.forEach((diags, file) => {
63-
const fileUri = vscode.Uri.file(join(workspacePath, file.replace(new RegExp(`^./`), '')));
64-
diagnosticCollection.set(fileUri, diags);
65-
});
66-
});
67-
}
68-
69-
const save_evt = vscode.workspace.onDidSaveTextDocument(() => {
70-
run_diag();
71-
});
72-
73-
const code_action = vscode.languages.registerCodeActionsProvider("css", new CssFixProvider(diagnosticCollection), {
74-
providedCodeActionKinds: [vscode.CodeActionKind.QuickFix],
75-
});
76-
77-
install(version)
78-
.then(() => {
79-
context.subscriptions.push(save_evt);
80-
context.subscriptions.push(code_action);
81-
run_diag();
82-
})
83-
.catch((e) => console.error(`[CSS-linter][ERROR]: ${e}`));
8+
const diagnosticCollection = vscode.languages.createDiagnosticCollection('css-linter-diags');
9+
context.subscriptions.push(diagnosticCollection);
10+
11+
const platform = os.platform();
12+
const binary = binaries[platform];
13+
14+
const homedir = os.homedir();
15+
const exec_path = join(homedir, '.css-linter', binary);
16+
17+
function run_diag() {
18+
const workspacePath = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
19+
if (!workspacePath) {
20+
return;
21+
}
22+
23+
exec(`${exec_path} ${workspacePath} --minify`, (error, stdout, stderr) => {
24+
if (error || stderr) {
25+
console.error(`[CSS-linter][ERROR]: ${error || stderr}`);
26+
return;
27+
}
28+
29+
console.log(stdout);
30+
31+
diagnosticCollection.clear();
32+
const error_lines = stdout.split('\n');
33+
34+
if (error_lines.length === 0) {
35+
return;
36+
}
37+
38+
const diagnosticsMap: Map<string, vscode.Diagnostic[]> = new Map();
39+
for (let e_line of error_lines) {
40+
let frags = e_line.split(':');
41+
if (frags.length < 4) {
42+
continue;
43+
}
44+
45+
const filePath = frags[0];
46+
const line = parseInt(frags[1]) - 1;
47+
const col = parseInt(frags[2]);
48+
const len = parseInt(frags[3]);
49+
const message = frags[4];
50+
51+
const range = new vscode.Range(line, col, line, col + len);
52+
const diagnostic = new vscode.Diagnostic(
53+
range,
54+
message,
55+
vscode.DiagnosticSeverity.Warning
56+
);
57+
58+
const diagnostics = diagnosticsMap.get(filePath) || [];
59+
diagnostics.push(diagnostic);
60+
diagnosticsMap.set(filePath, diagnostics);
61+
}
62+
63+
diagnosticsMap.forEach((diags, file) => {
64+
const fileUri = vscode.Uri.file(
65+
join(workspacePath, file.replace(new RegExp(`^./`), ''))
66+
);
67+
diagnosticCollection.set(fileUri, diags);
68+
});
69+
});
70+
}
71+
72+
const save_evt = vscode.workspace.onDidSaveTextDocument(() => {
73+
run_diag();
74+
});
75+
76+
const code_action = vscode.languages.registerCodeActionsProvider(
77+
'css',
78+
new CssFixProvider(diagnosticCollection),
79+
{
80+
providedCodeActionKinds: [vscode.CodeActionKind.QuickFix]
81+
}
82+
);
83+
84+
install()
85+
.then(() => {
86+
context.subscriptions.push(save_evt);
87+
context.subscriptions.push(code_action);
88+
run_diag();
89+
})
90+
.catch(e => console.error(`[CSS-linter][ERROR]: ${e}`));
8491
}
8592

8693
class CssFixProvider implements vscode.CodeActionProvider {
87-
constructor(private diagnostics: vscode.DiagnosticCollection) { }
88-
89-
provideCodeActions(document: vscode.TextDocument, range: vscode.Range): vscode.CodeAction[] {
90-
const actions: vscode.CodeAction[] = [];
91-
const disable_rule = '/* css-lint-disable-rule unused-class*/';
92-
93-
const diagnostics = this.diagnostics.get(document.uri) || [];
94-
for (const diagnostic of diagnostics) {
95-
if (diagnostic.range.intersection(range)) {
96-
const fix = new vscode.CodeAction(`Add ${disable_rule}`, vscode.CodeActionKind.QuickFix);
97-
fix.edit = new vscode.WorkspaceEdit();
98-
99-
fix.edit.insert(document.uri, new vscode.Position(diagnostic.range.start.line, 0), `${disable_rule}\n`);
100-
fix.diagnostics = [diagnostic];
101-
fix.isPreferred = true;
102-
103-
actions.push(fix);
104-
}
105-
}
106-
107-
return actions;
108-
}
94+
constructor(private diagnostics: vscode.DiagnosticCollection) {}
95+
96+
provideCodeActions(document: vscode.TextDocument, range: vscode.Range): vscode.CodeAction[] {
97+
const actions: vscode.CodeAction[] = [];
98+
const disable_rule = '/* css-lint-disable-rule unused-class*/';
99+
100+
const diagnostics = this.diagnostics.get(document.uri) || [];
101+
for (const diagnostic of diagnostics) {
102+
if (diagnostic.range.intersection(range)) {
103+
const fix = new vscode.CodeAction(
104+
`Add ${disable_rule}`,
105+
vscode.CodeActionKind.QuickFix
106+
);
107+
fix.edit = new vscode.WorkspaceEdit();
108+
109+
fix.edit.insert(
110+
document.uri,
111+
new vscode.Position(diagnostic.range.start.line, 0),
112+
`${disable_rule}\n`
113+
);
114+
fix.diagnostics = [diagnostic];
115+
fix.isPreferred = true;
116+
117+
actions.push(fix);
118+
}
119+
}
120+
121+
return actions;
122+
}
109123
}
110124

111-
export function deactivate() { }
125+
export function deactivate() {}
126+

vscode-ext/src/installer.ts

Lines changed: 51 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,56 @@
1-
import { chmod, chmodSync, createWriteStream, existsSync, mkdirSync } from 'fs';
1+
import { chmodSync, createWriteStream, existsSync, mkdirSync, unlink, unlinkSync } from 'fs';
22
import os from 'os';
33
import path from 'path';
44
import axios from 'axios';
5+
import { exec } from 'child_process';
56

67
export const binaries: { [key: string]: string } = {
7-
linux: "css-linter-linux",
8-
darwin: "css-linter-macos",
9-
win32: "css-linter-win.exe",
8+
linux: 'css-linter-linux',
9+
darwin: 'css-linter-macos',
10+
win32: 'css-linter-win.exe'
1011
};
12+
const remote_repo = 'Andcool-Systems/css-linter';
13+
const url = `https://github.com/${remote_repo}/releases/latest/download`;
14+
const version_api_url = `https://api.github.com/repos/${remote_repo}/releases/latest`;
1115

12-
const url = `https://github.com/Andcool-Systems/css-linter/releases/download`;
16+
const getLatestVer = async (): Promise<string> => {
17+
const response = await axios.get(version_api_url);
1318

14-
const download = (file_path: string, file_name: string): Promise<void> => new Promise<void>((resolve, reject) => {
15-
axios.get(file_path, {responseType: 'stream'})
16-
.then((response) => {
17-
const writer = createWriteStream(file_name);
18-
response.data.pipe(writer);
19-
writer.on("finish", resolve);
20-
writer.on("error", reject);
21-
})
22-
.catch(reject);
23-
});
19+
if (response.status !== 200) {
20+
throw Error('[CSS-linter][ERROR]: Got unexpected status code');
21+
}
22+
23+
return response.data.tag_name;
24+
};
2425

26+
const getCurrVer = (exec_path: string): Promise<string> =>
27+
new Promise((resolve, reject) => {
28+
exec(`${exec_path} -v`, (error, stdout, stderr) => {
29+
if (error || stderr) reject(error || stderr);
30+
resolve(stdout.trim());
31+
});
32+
});
2533

26-
export const install = async (version: string) => {
27-
let exe_ver = version.split('.').slice(0, 2).join('.');
34+
const download = (file_path: string, file_name: string): Promise<void> =>
35+
new Promise<void>((resolve, reject) => {
36+
axios
37+
.get(file_path, { responseType: 'stream' })
38+
.then(response => {
39+
const writer = createWriteStream(file_name);
40+
response.data.pipe(writer);
41+
writer.on('finish', () => {
42+
chmodSync(file_name, 0o755);
43+
resolve();
44+
});
45+
writer.on('error', reject);
46+
})
47+
.catch(reject);
48+
});
2849

50+
export const install = async () => {
2951
const platform = os.platform();
3052
const binary = binaries[platform];
31-
const bin_url = `${url}/v${exe_ver}/${binary}`;
53+
const bin_url = `${url}/${binary}`;
3254

3355
if (!binary) {
3456
throw Error(`[CSS-linter][ERROR]: Unsupported platform`);
@@ -40,6 +62,15 @@ export const install = async (version: string) => {
4062
mkdirSync(path.join(homedir, '.css-linter'), { recursive: true });
4163

4264
await download(bin_url, exec_path);
43-
chmodSync(exec_path, 0o755);
65+
} else {
66+
const current_ver = await getCurrVer(exec_path);
67+
const latest_ver = await getLatestVer();
68+
69+
if (current_ver === latest_ver) {
70+
return;
71+
}
72+
73+
unlinkSync(exec_path);
74+
await download(bin_url, exec_path);
4475
}
45-
};
76+
};

0 commit comments

Comments
 (0)