Skip to content

Commit

Permalink
Merge pull request #8 from swagup-com/develop
Browse files Browse the repository at this point in the history
## Added
- Add a new command to format all XML files in a folder
- Improve error handling
-Add support for field filters with filter logic (Prevents the order for the criteria would change and therefore modify the logic)
## Changed
- Improve tags specific logic for sorting more accurately
  • Loading branch information
drival1994 authored Jun 7, 2021
2 parents 20f9828 + 7767f1a commit b825b71
Show file tree
Hide file tree
Showing 7 changed files with 108 additions and 30 deletions.
14 changes: 13 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,16 @@

### Changed

- Improve documentation: avoid VS Code warnings for using the publisher name in lowercase, and fill in the CHANGELOG.md file.
- Improve documentation: avoid VS Code warnings for using the publisher name in lowercase, and fill in the CHANGELOG.md file

## [0.0.3](https://github.com/swagup-com/sf-xml-formatter/releases/tag/v0.0.3) - 2021-06-07

### Added

- Add a new command to format all XML files in a folder
- Improve error handling
- Add support for field filters with filter logic (Prevents the order for the criteria would change and therefore modify the logic)

### Changed

- Improve tags specific logic for sorting more accurately
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,11 @@ You can add the following line in your VS Code settings to disable the formatter

## Commands

### Format directory command

Format all XML files in a specific folder at once from the context menu.
![Format an entire folder](/images/format_folder_example.gif)

### Open docs command

There is a command to open the docs:
Expand All @@ -68,3 +73,5 @@ There is a command to open the docs:
```
Using Command Palette (CMD/CTRL + Shift + P) -> SF XML FORMATTER: Open docs
```

![Open Docs](/images/open_docs_command.jpg)
91 changes: 64 additions & 27 deletions extension.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
const vscode = require("vscode");
const xml2js = require("xml2js");
const fs = require("fs");
const path = require("path");
const { sort } = require("./sorter.js");
const {
getFormatSettings,
isFormatDisabled,
} = require("./settings/settings.js");

const encoding = "utf-8";
const sortConfigurationFilePath = __dirname + "/xmlformatter.cfg";
const packageJsonFilePath = __dirname + "/package.json";
const sortConfigurationFilePath = `${__dirname}/xmlformatter.cfg`;
const packageJsonFilePath = `${__dirname}/package.json`;

const formatSettings = getFormatSettings();
const sortDefaultConfiguration = {
Expand All @@ -26,7 +27,7 @@ const loadFileFromDisk = function (path) {
);
}
} catch (error) {
console.error("Error trying to read file: " + path + " Details: " + error);
console.error(`Error trying to read file: "${path}". Details: ${error}`);
}
return fileObj;
};
Expand All @@ -41,6 +42,53 @@ const getSortConfiguration = function () {
return options;
};

const formatDirectory = function (dirPath) {
let xmlFiles = fs.readdirSync(dirPath).filter(isXMLFile);
let errors = [];
xmlFiles.forEach((xmlFile) => {
let filePath = `${dirPath}${path.sep}${xmlFile}`;
try {
formatFile(filePath);
} catch (err) {
let errorMsg = `Error formatting file "${filePath}". Details: ${err.message}`;
console.error(errorMsg);
errors.push(errorMsg);
}
});
vscode.window.showErrorMessage(errors.join(" | "));
};

const formatFile = function (filePath) {
let xmlContent = fs.readFileSync(filePath);
let orderedXml = formatXML(xmlContent);
fs.writeFileSync(filePath, orderedXml);
};

const isXMLFile = function (fileName) {
let nameSplittedByDot = fileName.split(".");
return nameSplittedByDot[nameSplittedByDot.length - 1] === "xml";
};
const formatXML = function (xmlContent) {
const parser = new xml2js.Parser(formatSettings.parserOptions);
let sortedXml;

parser.parseString(xmlContent, function (err, result) {
if (result) {
let builder = new xml2js.Builder(formatSettings.builderOptions);
const sortConfiguration = getSortConfiguration();
let sortedJsonObj = sort(result, sortConfiguration);
sortedXml = builder.buildObject(sortedJsonObj);
} else {
console.error(err);
throw new Error(
"The file could not be parsed. Please ensure your file is a correct XML file."
);
}
});

return sortedXml;
};

vscode.languages.registerDocumentFormattingEditProvider("xml", {
provideDocumentFormattingEdits(document) {
if (isFormatDisabled()) {
Expand All @@ -52,25 +100,8 @@ vscode.languages.registerDocumentFormattingEditProvider("xml", {
return null;
}

var parser = new xml2js.Parser(formatSettings.parserOptions);
let sortedXml;
let errorMsg = "";

parser.parseString(xmlContent, function (err, result) {
if (result) {
try {
let builder = new xml2js.Builder(formatSettings.builderOptions);
const sortConfiguration = getSortConfiguration();
let sortedJsonObj = sort(result, sortConfiguration);
sortedXml = builder.buildObject(sortedJsonObj);
} catch (error) {
errorMsg = "An unexpected error has occurred. Details: " + error;
console.error(errorMsg);
}
}
});

if (sortedXml) {
try {
let sortedXml = formatXML(xmlContent);
const firstLine = document.lineAt(0);
const lastLine = document.lineAt(document.lineCount - 1);
const textRange = new vscode.Range(
Expand All @@ -79,11 +110,9 @@ vscode.languages.registerDocumentFormattingEditProvider("xml", {
);

return [vscode.TextEdit.replace(textRange, sortedXml)];
} else {
if (!sortedXml) {
vscode.window.showInformationMessage(errorMsg);
}
return null;
} catch (err) {
console.error(err.message);
vscode.window.showErrorMessage(err.message);
}
},
});
Expand All @@ -95,6 +124,8 @@ vscode.languages.registerDocumentFormattingEditProvider("xml", {
* @param {vscode.ExtensionContext} context
*/
function activate(context) {
// vscode.window.showInformationMessage("This is an info message!");

// Use the console to output diagnostic information (console.log) and errors (console.error)
// This line of code will only be executed once when your extension is activated

Expand All @@ -112,7 +143,13 @@ function activate(context) {
}
);

let formatDirCommand = vscode.commands.registerCommand(
"sf-xml-formatter.formatDirectory",
(context) => formatDirectory(context["fsPath"])
);

context.subscriptions.push(openRepoUrl);
context.subscriptions.push(formatDirCommand);
}

// this method is called when your extension is deactivated
Expand Down
Binary file added images/format_folder_example.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/open_docs_command.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
21 changes: 20 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"contributors": [
"Mauricio Perdomo <mauricio@swagup.com> (https://github.com/stdevMauricio1802)"
],
"version": "0.0.2",
"version": "0.0.3",
"engines": {
"vscode": "^1.55.0"
},
Expand Down Expand Up @@ -43,8 +43,27 @@
{
"command": "sf-xml-formatter.openDocs",
"title": "SF XML FORMATTER: Open docs"
},
{
"command": "sf-xml-formatter.formatDirectory",
"title": "SF XML FORMATTER: Format XML files"
}
],
"menus" : {
"explorer/context" : [
{
"command": "sf-xml-formatter.formatDirectory",
"group": "Salesforce Formatter",
"when": "explorerResourceIsFolder"
}
],
"commandPalette": [
{
"command": "sf-xml-formatter.formatDirectory",
"when": "false"
}
]
},
"breakpoints": [
{
"language": "xml"
Expand Down
5 changes: 4 additions & 1 deletion xmlformatter.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"values": ["field"],
"duplicateRuleMatchRules": ["matchingRule"],
"componentInstanceProperties": ["name"],
"objectMapping": ["outputObject"],
"mappingFields": ["inputField"],
"managedContentNodeTypes": ["nodeName"],
"matchingRuleItems": ["fieldName"],
Expand All @@ -41,7 +42,9 @@
"assignmentRule",
"GlobalValueSet",
"Layout",
"FlexiPage",
"picklistValues",
"sections"
"sections",
"lookupFilter"
]
}

0 comments on commit b825b71

Please sign in to comment.