feat: use local bundle strategy

This commit is contained in:
Jonathan Kelley committed 2022-07-06 00:45:22 -04:00
1 parent 4a54934c8e
commit baab2b9b4f
13 files changed
+3604 -1351

No files matched your search

+2 -1
View File
@@ -1,3 +1,4 @@
/target
Cargo.lock
.idea/
.idea/
.DS_Store
+2 -4
View File
@@ -46,10 +46,8 @@ flate2 = "1.0.22"
tar = "0.4.38"
tower = "0.4.12"
dioxus-rsx = { path = "../../dioxus/packages/rsx" }
dioxus-autofmt = { path = "../../dioxus/packages/autofmt" }
# dioxus-rsx = { git = "https://github.com/dioxuslabs/dioxus.git", branch = "jk/rsx-refactor" }
# dioxus-autofmt = { git = "https://github.com/dioxuslabs/dioxus.git", branch = "jk/rsx-refactor" }
dioxus-rsx = { git = "https://github.com/dioxuslabs/dioxus.git" }
dioxus-autofmt = { git = "https://github.com/dioxuslabs/dioxus.git" }
[[bin]]
path = "src/main.rs"
+50
View File
@@ -0,0 +1,50 @@
//! Construct version in the `commit-hash date channel` format
use std::{env, path::PathBuf, process::Command};
fn main() {
set_rerun();
set_commit_info();
if option_env!("CFG_RELEASE").is_none() {
println!("cargo:rustc-env=POKE_RA_DEVS=1");
}
}
fn set_rerun() {
println!("cargo:rerun-if-env-changed=CFG_RELEASE");
let mut manifest_dir = PathBuf::from(
env::var("CARGO_MANIFEST_DIR").expect("`CARGO_MANIFEST_DIR` is always set by cargo."),
);
while manifest_dir.parent().is_some() {
let head_ref = manifest_dir.join(".git/HEAD");
if head_ref.exists() {
println!("cargo:rerun-if-changed={}", head_ref.display());
return;
}
manifest_dir.pop();
}
println!("cargo:warning=Could not find `.git/HEAD` from manifest dir!");
}
fn set_commit_info() {
let output = match Command::new("git")
.arg("log")
.arg("-1")
.arg("--date=short")
.arg("--format=%H %h %cd")
.output()
{
Ok(output) if output.status.success() => output,
_ => return,
};
let stdout = String::from_utf8(output.stdout).unwrap();
let mut parts = stdout.split_whitespace();
let mut next = || parts.next().unwrap();
println!("cargo:rustc-env=RA_COMMIT_HASH={}", next());
println!("cargo:rustc-env=RA_COMMIT_SHORT_HASH={}", next());
println!("cargo:rustc-env=RA_COMMIT_DATE={}", next())
}
+2
View File
@@ -0,0 +1,2 @@
**
!.gitignore
+3245 -1191
View File
File diff suppressed because it is too large. Load diff
+28 -14
View File
@@ -12,10 +12,10 @@
"url": "https://github.com/DioxusLabs/cli"
},
"engines": {
"vscode": "^1.32.0"
"vscode": "^1.68.1"
},
"categories": [
"Other"
"Programming Languages"
],
"activationEvents": [
"onCommand:extension.htmlToDioxusRsx",
@@ -23,7 +23,7 @@
"onCommand:extension.formatRsx",
"onCommand:extension.formatRsxDocument"
],
"main": "./out/extension",
"main": "./out/main",
"contributes": {
"commands": [
{
@@ -45,18 +45,32 @@
]
},
"scripts": {
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"lint": "eslint . --ext .ts,.tsx",
"watch": "tsc -watch -p ./",
"package": "vsce package"
"vscode:prepublish": "npm run build-base -- --minify",
"package": "vsce package -o rust-analyzer.vsix",
"build-base": "esbuild ./src/main.ts --bundle --outfile=out/main.js --external:vscode --format=cjs --platform=node --target=node16",
"build": "npm run build-base -- --sourcemap",
"watch": "npm run build-base -- --sourcemap --watch",
"lint": "prettier --check . && eslint -c .eslintrc.js --ext ts ./src ./tests",
"fix": "prettier --write . && eslint -c .eslintrc.js --ext ts ./src ./tests --fix",
"pretest": "tsc && npm run build",
"test": "cross-env TEST_VARIABLE=test node ./out/tests/runTests.js"
},
"devDependencies": {
"@types/node": "^12.12.0",
"@types/vscode": "^1.32.0",
"@typescript-eslint/eslint-plugin": "^4.16.0",
"@typescript-eslint/parser": "^4.16.0",
"eslint": "^7.21.0",
"typescript": "^4.3.5"
"@types/node": "^18.0.2",
"@types/vscode": "^1.68.1",
"@typescript-eslint/eslint-plugin": "^5.30.5",
"@typescript-eslint/parser": "^5.30.5",
"cross-env": "^7.0.3",
"esbuild": "^0.14.27",
"eslint": "^8.19.0",
"typescript": "^4.7.4",
"eslint-config-prettier": "^8.5.0",
"ovsx": "^0.5.1",
"prettier": "^2.6.2",
"tslib": "^2.3.0",
"vsce": "^2.7.0"
},
"dependencies": {
"vsce": "^2.9.2"
}
}
+3
View File
@@ -0,0 +1,3 @@
**
!Readme.md
!.gitignore
-139
View File
@@ -1,139 +0,0 @@
import * as vscode from 'vscode';
import { spawn } from "child_process";
export function activate(context: vscode.ExtensionContext) {
function translate(component: boolean) {
const editor = vscode.window.activeTextEditor;// Get the active text editor
if (!editor) return;
const html = editor.document.getText(editor.selection);
if (html.length == 0) {
vscode.window.showWarningMessage("Please select HTML fragment before invoking this command!");
return;
}
let params = ["translate"];
if (component) params.push("--component");
params.push("--raw");
params.push(html);
const child_proc = spawn("dioxus", params);
let result = '';
child_proc.stdout?.on('data', data => result += data);
child_proc.on('close', () => {
if (result.length > 0) editor.edit(editBuilder => editBuilder.replace(editor.selection, result));
});
child_proc.on('error', (err) => {
vscode.window.showWarningMessage(`Errors occurred while translating. Make sure you have the most recent Dioxus-CLI installed! \n${err}`);
});
}
function autoformat_selection() {
const editor = vscode.window.activeTextEditor;// Get the active text editor
if (!editor) return;
const unformatted = editor.document.getText(editor.selection);
if (unformatted.length == 0) {
vscode.window.showWarningMessage("Please select rsx invoking this command!");
return;
}
let args = ["fmt", "--raw", unformatted.toString()];
const child_proc = spawn("dioxus", args);
let result = '';
child_proc.stdout?.on('data', data => result += data);
child_proc.on('close', () => {
if (result.length > 0) editor.edit(editBuilder => editBuilder.replace(editor.selection, result));
});
child_proc.on('error', (err) => {
vscode.window.showWarningMessage(`Errors occurred while translating. Make sure you have the most recent Dioxus-CLI installed! \n${err}`);
});
}
function autoformat_document(document: vscode.TextDocument) {
// check the settings to make sure format on save is configured
// const formatOnSave: string | undefined = vscode.workspace.getConfiguration('rust').get('formatOnSave');
if (document.languageId === "rust" && document.uri.scheme === "file") {
const active_editor = vscode.window.activeTextEditor;// Get the active text editor
if (active_editor?.document.fileName === document.fileName) {
const text = document.getText();
console.error(text);
const child_proc = spawn("dioxus", ["fmt", "-f", text]);
let result = '';
child_proc.stdout?.on('data', data => result += data);
type RsxEdit = {
formatted: string,
start: number,
end: number
}
child_proc.on('close', () => {
if (result.length > 0) {
let decoded: RsxEdit[] = JSON.parse(result);
console.log("Decoded edits: ", decoded);
// Get the active text editor
const cur_editor = vscode.window.activeTextEditor;
// even if we build an empty edit stream, it tries to save the editor
// this makes sure the editor is actually saved
if (decoded.length > 0 && cur_editor == active_editor) {
active_editor.edit(editBuilder => {
for (let edit of decoded) {
console.log("Handling Edit: ", edit);
let start = document.positionAt(edit.start - 1);
let end = document.positionAt(edit.end + 1);
const range = new vscode.Range(start, end);
editBuilder.replace(range, `{ ${edit.formatted} }`);
// editor.edit(editBuilder => editBuilder.replace(range, `{ ${edit.formatted} }`)).then((could_be_applied) => {
// });
// editor.edit(editBuilder => editBuilder.replace(range, `{ ${edit.formatted} }`)).then((could_be_applied) => {
// console.log("Edit applied: ", could_be_applied);
// });
}
})
}
}
});
child_proc.on('error', (err) => {
vscode.window.showWarningMessage(`Errors occurred while translating. Make sure you have the most recent Dioxus-CLI installed! \n${err}`);
});
}
}
}
context.subscriptions.push(
vscode.commands.registerCommand('extension.htmlToDioxusRsx', () => translate(false)),
vscode.commands.registerCommand('extension.htmlToDioxusComponent', () => translate(true)),
vscode.commands.registerCommand('extension.formatRsx', () => autoformat_selection()),
vscode.commands.registerCommand('extension.formatRsxDocument', () => {
const editor = vscode.window.activeTextEditor;// Get the active text editor
if (!editor) return;
autoformat_document(editor.document);
}),
vscode.workspace.onDidSaveTextDocument(autoformat_document)
);
}
+184
View File
@@ -0,0 +1,184 @@
import * as vscode from 'vscode';
import { spawn } from "child_process";
let serverPath: string = "dioxus";
export async function activate(context: vscode.ExtensionContext) {
let somePath = await bootstrap(context);
if (somePath == undefined) {
await vscode.window.showErrorMessage('Could not find bundled Dioxus-CLI. Please install it manually.');
return;
} else {
serverPath = somePath;
}
context.subscriptions.push(
vscode.commands.registerTextEditorCommand('editor.action.clipboardPasteAction', onPasteHandler),
vscode.commands.registerCommand('extension.htmlToDioxusRsx', translateBlock),
vscode.commands.registerCommand('extension.htmlToDioxusComponent', translateComponent),
vscode.commands.registerCommand('extension.formatRsx', fmtSelection),
vscode.commands.registerCommand('extension.formatRsxDocument', formatRsxDocument),
vscode.workspace.onWillSaveTextDocument(fmtDocument)
);
}
function translateComponent() {
translate(true)
}
function translateBlock() {
translate(false)
}
function translate(component: boolean) {
const editor = vscode.window.activeTextEditor;
if (!editor) return;
const html = editor.document.getText(editor.selection);
if (html.length == 0) {
vscode.window.showWarningMessage("Please select HTML fragment before invoking this command!");
return;
}
let params = ["translate"];
if (component) params.push("--component");
params.push("--raw", html);
const child_proc = spawn(serverPath, params);
let result = '';
child_proc.stdout?.on('data', data => result += data);
child_proc.on('close', () => {
if (result.length > 0) editor.edit(editBuilder => editBuilder.replace(editor.selection, result));
});
child_proc.on('error', (err) => {
vscode.window.showWarningMessage(`Errors occurred while translating. Make sure you have the most recent Dioxus-CLI installed! \n${err}`);
});
}
function onPasteHandler() {
// check settings to see if we should convert HTML to Rsx
if (vscode.workspace.getConfiguration('dioxus').get('convertOnPaste')) {
convertHtmlToRsxOnPaste();
}
}
function convertHtmlToRsxOnPaste() {
const editor = vscode.window.activeTextEditor;
if (!editor) return;
// get the cursor location
const cursor = editor.selection.active;
// try to parse the HTML at the cursor location
const html = editor.document.getText(new vscode.Range(cursor, cursor));
}
function formatRsxDocument() {
const editor = vscode.window.activeTextEditor;
if (editor) {
fmtDocument();
}
}
function fmtSelection() {
const editor = vscode.window.activeTextEditor;
if (!editor) return;
const unformatted = editor.document.getText(editor.selection);
if (unformatted.length == 0) {
vscode.window.showWarningMessage("Please select rsx invoking this command!");
return;
}
const child_proc = spawn(serverPath, ["fmt", "--raw", unformatted.toString()]);
let result = '';
child_proc.stdout?.on('data', data => result += data);
child_proc.on('close', () => {
if (result.length > 0) editor.edit(editBuilder => editBuilder.replace(editor.selection, result));
});
child_proc.on('error', (err) => {
vscode.window.showWarningMessage(`Errors occurred while translating. Make sure you have the most recent Dioxus-CLI installed! \n${err}`);
});
}
function fmtDocument() {
const editor = vscode.window.activeTextEditor;
const document = editor?.document;
if (!document) return;
// check the settings to make sure format on save is configured
if (document.languageId === "rust" && document.uri.scheme === "file") {
const active_editor = vscode.window.activeTextEditor;
if (active_editor?.document.fileName === document.fileName) {
const text = document.getText();
const child_proc = spawn("dioxus", ["fmt", "-f", text]);
let result = '';
child_proc.stdout?.on('data', data => result += data);
type RsxEdit = {
formatted: string,
start: number,
end: number
}
child_proc.on('close', () => {
if (result.length > 0) {
let decoded: RsxEdit[] = JSON.parse(result);
if (decoded.length > 0) {
active_editor.edit(editBuilder => {
decoded.map((edit) => {
editBuilder.replace(new vscode.Range(
document.positionAt(edit.start),
document.positionAt(edit.end)
), edit.formatted);
});
}, {
undoStopAfter: false,
undoStopBefore: false
})
}
}
});
child_proc.on('error', (err) => {
vscode.window.showWarningMessage(`Errors occurred while translating. Make sure you have the most recent Dioxus-CLI installed! \n${err}`);
});
}
}
}
// I'm using the approach defined in rust-analyzer here
//
// We ship the server as part of the extension, but we need to handle external paths and such
//
// https://github.com/rust-lang/rust-analyzer/blob/fee5555cfabed4b8abbd40983fc4442df4007e49/editors/code/src/main.ts#L270
async function bootstrap(context: vscode.ExtensionContext): Promise<string | undefined> {
const ext = process.platform === "win32" ? ".exe" : "";
const bundled = vscode.Uri.joinPath(context.extensionUri, "server", `dioxus${ext}`);
const bundledExists = await vscode.workspace.fs.stat(bundled).then(
() => true,
() => false
);
// if bunddled doesn't exist, try using a locally-installed version
if (!bundledExists) {
return "dioxus";
}
return bundled.fsPath;
}
+2 -2
View File
@@ -15,7 +15,7 @@ pub struct Autoformat {
impl Autoformat {
pub fn autoformat(self) -> Result<()> {
if let Some(raw) = self.raw {
if let Some(inner) = dioxus_autofmt::fmt_block(&raw) {
if let Some(inner) = dioxus_autofmt::fmt_block(&raw, 0) {
println!("{}", inner);
} else {
// exit process with error
@@ -25,7 +25,7 @@ impl Autoformat {
}
if let Some(file) = self.file {
let edits = dioxus_autofmt::get_format_blocks(&file);
let edits = dioxus_autofmt::fmt_file(&file);
let as_json = serde_json::to_string(&edits).unwrap();
println!("{}", as_json);
}
+5
View File
@@ -7,6 +7,7 @@ pub mod create;
pub mod serve;
pub mod tool;
pub mod translate;
pub mod version;
use crate::{
cfg::{ConfigOptsBuild, ConfigOptsServe},
@@ -59,6 +60,10 @@ pub enum Commands {
/// Clean output artifacts.
Clean(clean::Clean),
/// Print the version of this extension
#[clap(name = "version")]
Version(version::Version),
/// Format some rsx
#[clap(name = "fmt")]
Autoformat(autoformat::Autoformat),
+76
View File
@@ -0,0 +1,76 @@
use super::*;
/// Build the Rust WASM app and all of its assets.
#[derive(Clone, Debug, Parser)]
#[clap(name = "version")]
pub struct Version {}
impl Version {
pub fn version(self) -> VersionInfo {
version()
}
}
use std::fmt;
/// Information about the git repository where rust-analyzer was built from.
pub struct CommitInfo {
pub short_commit_hash: &'static str,
pub commit_hash: &'static str,
pub commit_date: &'static str,
}
/// Cargo's version.
pub struct VersionInfo {
/// rust-analyzer's version, such as "1.57.0", "1.58.0-beta.1", "1.59.0-nightly", etc.
pub version: &'static str,
/// The release channel we were built for (stable/beta/nightly/dev).
///
/// `None` if not built via rustbuild.
pub release_channel: Option<&'static str>,
/// Information about the Git repository we may have been built from.
///
/// `None` if not built from a git repo.
pub commit_info: Option<CommitInfo>,
}
impl fmt::Display for VersionInfo {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.version)?;
if let Some(ci) = &self.commit_info {
write!(f, " ({} {})", ci.short_commit_hash, ci.commit_date)?;
};
Ok(())
}
}
/// Returns information about cargo's version.
pub const fn version() -> VersionInfo {
let version = match option_env!("CFG_RELEASE") {
Some(x) => x,
None => "0.0.0",
};
let release_channel = option_env!("CFG_RELEASE_CHANNEL");
let commit_info = match (
option_env!("RA_COMMIT_SHORT_HASH"),
option_env!("RA_COMMIT_HASH"),
option_env!("RA_COMMIT_DATE"),
) {
(Some(short_commit_hash), Some(commit_hash), Some(commit_date)) => Some(CommitInfo {
short_commit_hash,
commit_hash,
commit_date,
}),
_ => None,
};
VersionInfo {
version,
release_channel,
commit_info,
}
}
+5
View File
@@ -54,6 +54,11 @@ async fn main() -> Result<()> {
log::error!("format error: {}", e);
}
}
Commands::Version(opt) => {
let version = opt.version();
println!("{}", version);
}
}
Ok(())