Skip to content

Commit

Permalink
update prettier move plugin prettierrc config
Browse files Browse the repository at this point in the history
  • Loading branch information
daoauth committed Nov 24, 2024
1 parent 9acd8be commit 87eec0c
Show file tree
Hide file tree
Showing 6 changed files with 142 additions and 141 deletions.
36 changes: 35 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,43 @@ The Sui extension provides seamless support for compiling, deploying, and testin
- **Compile Sui Smart Contracts**: Easily compile your Sui smart contracts from within VS Code.
- **Deploy and Test**: Deploy and test your smart contracts using the zkLogin-generated wallet, all from within the extension.
- **Format Sui Smart Contracts**: Format your Move smart contracts with Prettier, using `@mysten/prettier-plugin-move` for clean, readable, and consistent code.

> Note: The extension supports formatting configurations defined in a `.prettierrc.json` file located in your project. These configurations allow you to customize the formatting rules for your Move files. If no configuration is found, the extension falls back to its default settings:
```json
{
"tabWidth": 4,
"printWidth": 100,
"useModuleLabel": true,
"autoGroupImports": "module",
"enableErrorDebug": false,
"wrapComments": false
}
```

> Customize: To use a custom configuration, create a .prettierrc.json file in the root of your project directory with your preferred settings. For example:
+ Configuration Options:
+ tabWidth: Number of spaces per tab (default: 4).
+ printWidth: Maximum line length before wrapping (default: 100).
+ useModuleLabel: Converts old module blocks to a module label (default: true).
+ autoGroupImports: Controls how imports are grouped. Options: "module" (default) or "package".
+ enableErrorDebug: Enables debug information for formatting errors (default: false).
+ wrapComments: Wraps comments to adhere to the printWidth (default: false).

```json
{
"tabWidth": 2,
"printWidth": 80,
"useModuleLabel": false,
"autoGroupImports": "package",
"wrapComments": true
}
```

- **GitHub Codespaces Integration**: Increase the efficiency of your development workflow with full support for GitHub Codespaces.
- **Unified Development**: Manage both front-end and back-end code in a single repository for streamlined development.
- **Upgrade Smart Contracts**: Seamlessly upgrade and test your smart contracts.

> Note: To upgrade, add an `upgrade.toml` file in the same directory as your `move.toml` file. The format is as follows:
```toml
[upgrade]
Expand All @@ -26,7 +60,7 @@ The Sui extension provides seamless support for compiling, deploying, and testin
1. **Owner Objects Explorer**: This section of the interface allows you to load and inspect owner objects, one of the key features of Sui. By loading objects, you can check its `type` to verify that it contains the appropriate information required for the function arguments of a deployed smart contract.
1. **Object Explorer**: This section of the interface allows you to load and inspect objects, one of the key features of Sui. By loading an object, you can check its `type` to verify that it contains the appropriate information required for the function arguments of a deployed smart contract.
1. **Package Explorer**: This section of the user interface allows you to test smart contracts. When you deploy a Smart Contract, it is automatically registered here. You can also manually enter the address of a previously deployed Smart Contract to register it. If the smart contract is loaded correctly, you will see a list of functions available to interact with the contract.
1. **Fromat**: Use the `Format` button or command to format Move smart contracts with `@mysten/prettier-plugin-move`. This ensures your code adheres to a consistent style, improving readability and maintainability.
1. **Fromat**: Use the `Format` button. This ensures your code adheres to a consistent style, improving readability and maintainability.
1. **Output**: In this section, you can view the transaction execution data in raw format. Please select `Sui Extension` in the Task.

## Requirements
Expand Down
11 changes: 0 additions & 11 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,6 @@
"dark": "media/docs-dark.svg",
"light": "media/docs-light.svg"
}
},
{
"command": "sui-extension.formatMoveFile",
"title": "Format Move File"
}
],
"menus": {
Expand All @@ -68,13 +64,6 @@
"when": "view == webviewViewProviderSui",
"group": "navigation"
}
],
"editor/context": [
{
"command": "sui-extension.formatMoveFile",
"when": "editorTextFocus && resourceLangId == move",
"group": "moveTools@1"
}
]
},
"languages": [
Expand Down
3 changes: 0 additions & 3 deletions src/extension.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import * as vscode from 'vscode';
import { WebviewViewProvider } from './webviewPovider';
import { initPrettierMovePlugin } from './utilities/initPrettierMovePlugin';

export function activate(context: vscode.ExtensionContext) {
const provider = new WebviewViewProvider(context);
Expand All @@ -15,8 +14,6 @@ export function activate(context: vscode.ExtensionContext) {
vscode.env.openExternal(vscode.Uri.parse('https://docs.zktx.io'));
}),
);

initPrettierMovePlugin(context);
}

// This method is called when your extension is deactivated
Expand Down
140 changes: 107 additions & 33 deletions src/utilities/format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,57 @@ import * as prettier from 'prettier';
import * as Parser from 'web-tree-sitter';
import * as tree from '@mysten/prettier-plugin-move/out/tree.js';
import * as printer from '@mysten/prettier-plugin-move/out/printer.js';
import { initParser } from './initParser';

let parser: Parser | undefined = undefined;

const Default = {
tabWidth: 4,
printWidth: 100,
useModuleLabel: true,
autoGroupImports: 'module',
enableErrorDebug: false,
wrapComments: false,
};

const initParser = async (extensionUri: vscode.Uri): Promise<Parser> => {
if (parser) {
return parser;
}

await Parser.init();
const wasmPath = vscode.Uri.joinPath(
extensionUri,
'out/tree-sitter-move.wasm',
).path;
const Lang = await Parser.Language.load(wasmPath);
parser = new Parser();
parser.setLanguage(Lang);

return parser;
};

const loadPrettierConfig = async (
folderUri: string,
): Promise<Record<string, any>> => {
try {
const workspaceFolder = vscode.workspace.workspaceFolders?.[0];
if (!workspaceFolder) {
return Default;
}
const prettierConfigPath = vscode.Uri.joinPath(
workspaceFolder.uri,
folderUri,
'.prettierrc.json',
).fsPath;
const document =
await vscode.workspace.openTextDocument(prettierConfigPath);
const config = JSON.parse(document.getText());
return config ? { ...Default, ...config } : Default;
} catch (error) {
vscode.window.showErrorMessage(`Error loading .prettierrc: ${error}`);
return Default;
}
};

const getMoveFilesFromFolder = async (folderUri: string) => {
try {
Expand All @@ -24,12 +74,59 @@ const getMoveFilesFromFolder = async (folderUri: string) => {
}
};

const tryFormat = async (
plugin: prettier.Plugin<any>,
workspaceFolder: vscode.WorkspaceFolder,
file: vscode.Uri,
config: any,
channel?: vscode.OutputChannel,
) => {
try {
const document = await vscode.workspace.openTextDocument(file);
const originalText = document.getText();
const formatted = await prettier.format(originalText, {
parser: 'move-parse',
plugins: [plugin],
...config,
});

if (originalText !== formatted) {
const edit = new vscode.WorkspaceEdit();
const fullRange = new vscode.Range(
document.positionAt(0),
document.positionAt(originalText.length),
);
edit.replace(document.uri, fullRange, formatted);
await vscode.workspace.applyEdit(edit);
await document.save();

channel &&
workspaceFolder &&
channel.appendLine(
`${file.fsPath.replace(new RegExp(`^${workspaceFolder.uri.path}`), '')}`,
);
} else {
channel &&
workspaceFolder &&
channel.appendLine(
`${file.fsPath.replace(new RegExp(`^${workspaceFolder.uri.path}`), '')} (unchanged)`,
);
}
} catch (error) {
vscode.window.showErrorMessage(`Error formatting file: ${file.fsPath}`);
channel &&
channel.appendLine(`Error formatting file: ${file.fsPath} - ${error}`);
}
};

const formatAndSaveMoveFiles = async (
folderUri: string,
files: vscode.Uri[],
parser: Parser,
channel?: vscode.OutputChannel,
) => {
try {
const config = await loadPrettierConfig(folderUri);
const plugin = {
parsers: {
'move-parse': {
Expand All @@ -44,45 +141,22 @@ const formatAndSaveMoveFiles = async (
},
},
printers: {
'move-format': { print: printer.print },
'move-format': {
print: (path: any, options: any, print: any) => {
return printer.print(path, { ...options, ...config }, print);
},
},
},
};

const workspaceFolder = vscode.workspace.workspaceFolders?.[0];

for (const file of files) {
const document = await vscode.workspace.openTextDocument(file);
const originalText = document.getText(); // 원본 텍스트 가져오기
const formatted = await prettier.format(originalText, {
parser: 'move-parse',
plugins: [plugin],
});

if (originalText !== formatted) {
const edit = new vscode.WorkspaceEdit();
const fullRange = new vscode.Range(
document.positionAt(0),
document.positionAt(originalText.length),
);
edit.replace(document.uri, fullRange, formatted);
await vscode.workspace.applyEdit(edit);
await document.save();

channel &&
workspaceFolder &&
channel.appendLine(
`${file.fsPath.replace(new RegExp(`^${workspaceFolder.uri.path}`), '')}`,
);
} else {
channel &&
workspaceFolder &&
channel.appendLine(
`${file.fsPath.replace(new RegExp(`^${workspaceFolder.uri.path}`), '')} (unchanged)`,
);
}
workspaceFolder &&
(await tryFormat(plugin, workspaceFolder, file, config, channel));
}
} catch (error) {
vscode.window.showErrorMessage(`Error formatting files: ${error}`);
vscode.window.showErrorMessage(`Unexpected error: ${error}`);
}
};

Expand All @@ -94,7 +168,7 @@ export const format = async (
try {
const parser = await initParser(context.extensionUri);
const files = await getMoveFilesFromFolder(folderUri);
await formatAndSaveMoveFiles(files, parser, channel);
await formatAndSaveMoveFiles(folderUri, files, parser, channel);
} catch (error) {
vscode.window.showErrorMessage(`Error getting .move files: ${error}`);
}
Expand Down
21 changes: 0 additions & 21 deletions src/utilities/initParser.ts

This file was deleted.

72 changes: 0 additions & 72 deletions src/utilities/initPrettierMovePlugin.ts

This file was deleted.

0 comments on commit 87eec0c

Please sign in to comment.