Skip to content

Commit

Permalink
Resolve issues reported by DeepSource (#110)
Browse files Browse the repository at this point in the history
  • Loading branch information
pascalre committed Jan 4, 2023
1 parent 89a7c4d commit 4e61b4e
Show file tree
Hide file tree
Showing 22 changed files with 385 additions and 392 deletions.
4 changes: 4 additions & 0 deletions .deepsource.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,8 @@ version = 1

[[analyzers]]
name = "javascript"
enabled = true

[[analyzers]]
name = "test-coverage"
enabled = true
26 changes: 13 additions & 13 deletions .dependency-cruiser.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,19 +45,19 @@ module.exports = {
'core'
],
path: [
'^(v8\/tools\/codemap)$',
'^(v8\/tools\/consarray)$',
'^(v8\/tools\/csvparser)$',
'^(v8\/tools\/logreader)$',
'^(v8\/tools\/profile_view)$',
'^(v8\/tools\/profile)$',
'^(v8\/tools\/SourceMap)$',
'^(v8\/tools\/splaytree)$',
'^(v8\/tools\/tickprocessor-driver)$',
'^(v8\/tools\/tickprocessor)$',
'^(node-inspect\/lib\/_inspect)$',
'^(node-inspect\/lib\/internal\/inspect_client)$',
'^(node-inspect\/lib\/internal\/inspect_repl)$',
'^(v8/tools/codemap)$',
'^(v8/tools/consarray)$',
'^(v8/tools/csvparser)$',
'^(v8/tools/logreader)$',
'^(v8/tools/profile_view)$',
'^(v8/tools/profile)$',
'^(v8/tools/SourceMap)$',
'^(v8/tools/splaytree)$',
'^(v8/tools/tickprocessor-driver)$',
'^(v8/tools/tickprocessor)$',
'^(node-inspect/lib/_inspect)$',
'^(node-inspect/lib/internal/inspect_client)$',
'^(node-inspect/lib/internal/inspect_repl)$',
'^(async_hooks)$',
'^(punycode)$',
'^(domain)$',
Expand Down
21 changes: 18 additions & 3 deletions .github/workflows/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,25 +10,40 @@ jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Use Node.js
- name: Checkout code
uses: actions/checkout@v3

- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: 16

- name: install
run: |
npm install
npm install -g yarn
npm install -g vsce
- name: lint
run: npm run lint

- name: static code analysis
run: npm run code-analysis

- name: test
uses: GabrielBB/xvfb-action@v1
with:
run: npm run coverage
- name: coverage

- name: Report test coverage to Coveralls
uses: coverallsapp/github-action@master
with:
github-token: ${{ secrets.GITHUB_TOKEN }}

- name: Report test coverage to DeepSource
uses: deepsourcelabs/test-coverage-action@master
with:
key: javascript
coverage-file: coverage/lcov.info
dsn: ${{ secrets.DEEPSOURCE_DSN }}

10 changes: 9 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ The following commands support you at developing good code:
* `npm run test`: Run the tests
* `npm run lint`: Run the linter

### SonarQube
### Static code analysis
#### SonarQube
##### Local
* `docker-compose up -d`: Start the sonarqube container. This will take some time.
* `docker-compose stop`: Stop the container
* `docker-compose down`: Remove the container
Expand All @@ -22,6 +24,12 @@ SonarQube will be reachable on `http://localhost:9000`.

* `npm run sonar`: Start sonarscanner and upload result to local container

##### SonarCloud
Find analysis on [sonarcloud.io](https://sonarcloud.io/project/overview?id=pascalre_vscode-yaml-sort)

#### DeepSource
Find analysis on [deepsource.io](https://deepsource.io/gh/pascalre/vscode-yaml-sort)

### Commit changes
Refer to [this blogpost](https://cbea.ms/git-commit/#end) by cbeams when committing changes. Issue numbers can be added in braces to the end of the commit message.

Expand Down
8 changes: 4 additions & 4 deletions src/adapter/js-yaml-adapter.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Settings } from "../settings"
import * as jsyaml from "js-yaml"
import { load, dump } from "js-yaml"
import { SortUtil } from "../util/sort-util"
import { removeTrailingCharacters, splitYaml } from "../util/yaml-util"

Expand All @@ -15,7 +15,7 @@ export class JsYamlAdapter {
}

load(text: string) {
return jsyaml.load(text, this.getLoadOptions())
return load(text, this.getLoadOptions())
}

/**
Expand All @@ -25,7 +25,7 @@ export class JsYamlAdapter {
*/
validateYaml(text: string): boolean {
splitYaml(text).forEach((yaml) => {
jsyaml.load(yaml, { schema: this.settings.getSchema() })
load(yaml, { schema: this.settings.getSchema() })
})
return true
}
Expand All @@ -45,7 +45,7 @@ export class JsYamlAdapter {

const sort = new SortUtil(settings, custom)

let yaml = jsyaml.dump(text, {
let yaml = dump(text, {
indent: settings.getIndent(),
forceQuotes: settings.getForceQuotes(),
lineWidth: settings.getLineWidth(),
Expand Down
48 changes: 24 additions & 24 deletions src/adapter/vs-code-adapter.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as vscode from "vscode"
import { workspace, TextEditor, Range, Position, Selection, TextEdit, WorkspaceEdit, window, DocumentFormattingEditProvider, languages, Disposable } from "vscode"
import { Settings } from "../settings"

export enum Severity {
Expand All @@ -14,69 +14,69 @@ export class VsCodeAdapter {
}

getProperty(property: string) {
return vscode.workspace.getConfiguration().get(`${this.section}.${property}`)
return workspace.getConfiguration().get(`${this.section}.${property}`)
}

getActiveDocument(textEditor: vscode.TextEditor) {
getActiveDocument(textEditor: TextEditor) {
return textEditor.document.getText()
}

getFullDocumentRange(textEditor: vscode.TextEditor) {
return new vscode.Range(
new vscode.Position(0, 0),
new vscode.Position(textEditor.document.lineCount + 1, 0))
getFullDocumentRange(textEditor: TextEditor) {
return new Range(
new Position(0, 0),
new Position(textEditor.document.lineCount + 1, 0))
}

getSelectedRange(textEditor: vscode.TextEditor) {
getSelectedRange(textEditor: TextEditor) {
let endLine = textEditor.selection.end.line
// if selection ends on the first character on a new line ignore this line
if (textEditor.selection.end.character === 0) {
endLine--
}

// ensure selection covers whole start and end line
return new vscode.Selection(
return new Selection(
textEditor.selection.start.line, 0,
endLine, textEditor.document.lineAt(endLine).range.end.character)
}

getRange(textEditor: vscode.TextEditor) {
getRange(textEditor: TextEditor) {
if (textEditor.selection.isEmpty) {
return this.getFullDocumentRange(textEditor)
} else {
return this.getSelectedRange(textEditor)
}
}

getText(textEditor: vscode.TextEditor, range: vscode.Range) {
getText(textEditor: TextEditor, range: Range) {
return textEditor.document.getText(range)
}

getEdits(textEditor: vscode.TextEditor, text: string) {
getEdits(textEditor: TextEditor, text: string) {
const range = this.getRange(textEditor)
return vscode.TextEdit.replace(range, text)
return TextEdit.replace(range, text)
}

/**
* Applys edits to a text editor
* @param activeEditor Editor to apply the changes
* @param edits Changes to apply
*/
applyEdits(edit: [vscode.TextEdit]) {
if (vscode.window.activeTextEditor) {
const workspaceEdit = new vscode.WorkspaceEdit()
workspaceEdit.set(vscode.window.activeTextEditor.document.uri, edit)
vscode.workspace.applyEdit(workspaceEdit)
applyEdits(edit: [TextEdit]) {
if (window.activeTextEditor) {
const workspaceEdit = new WorkspaceEdit()
workspaceEdit.set(window.activeTextEditor.document.uri, edit)
workspace.applyEdit(workspaceEdit)
}
}

// have a function that adds/removes the formatter based
// on a configuration setting
registerFormatter(formatter: vscode.DocumentFormattingEditProvider) {
let registration: vscode.Disposable | undefined
registerFormatter(formatter: DocumentFormattingEditProvider) {
let registration: Disposable | undefined
const useAsFormatter = this.settings.getUseAsFormatter()
if (useAsFormatter && !registration) {
vscode.languages.registerDocumentFormattingEditProvider('yaml', formatter)
languages.registerDocumentFormattingEditProvider('yaml', formatter)
} else if (!useAsFormatter && registration) {
registration.dispose()
}
Expand All @@ -85,11 +85,11 @@ export class VsCodeAdapter {
showMessage(severity: Severity, message: string) {
switch(severity) {
case Severity.ERROR :
vscode.window.showErrorMessage(message)
window.showErrorMessage(message)
break
case Severity.INFO :
default :
if (this.settings.getNotifySuccess()) {
vscode.window.showInformationMessage(message)
window.showInformationMessage(message)
}
break
}
Expand Down
36 changes: 18 additions & 18 deletions src/controller.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as vscode from "vscode"
import * as fs from "fs"
import { TextEdit, Uri, window } from "vscode"
import { readFileSync, writeFileSync } from "fs"
import { JsYamlAdapter } from "./adapter/js-yaml-adapter"
import { Severity, VsCodeAdapter } from "./adapter/vs-code-adapter"
import { prependWhitespacesOnEachLine, removeLeadingLineBreakOfFirstElement } from "./lib"
Expand All @@ -12,8 +12,8 @@ const jsyamladapter = new JsYamlAdapter()
const vscodeadapter = new VsCodeAdapter()
const yamlutil = new YamlUtil()

export function sortYamlWrapper(customSort = 0): vscode.TextEdit[] {
const activeEditor = vscode.window.activeTextEditor
export function sortYamlWrapper(customSort = 0): TextEdit[] {
const activeEditor = window.activeTextEditor

if (activeEditor) {
const textRange = vscodeadapter.getRange(activeEditor)
Expand All @@ -26,7 +26,7 @@ export function sortYamlWrapper(customSort = 0): vscode.TextEdit[] {
if (e instanceof Error) {
vscodeadapter.showMessage(Severity.ERROR, e.message)
}
return []
return [] as TextEdit[]
}

let numberOfLeadingSpaces = 0
Expand All @@ -36,7 +36,7 @@ export function sortYamlWrapper(customSort = 0): vscode.TextEdit[] {
const matchMetadata = /^%.*\n/gm
// set metadata tags, if there is no metadata tag it should be an emtpy array
let newText = ""
if (text.match(matchMetadata)) {
if (matchMetadata.test(text)) {
delimiters.shift()
delimiters = removeLeadingLineBreakOfFirstElement(delimiters)
}
Expand All @@ -58,23 +58,23 @@ export function sortYamlWrapper(customSort = 0): vscode.TextEdit[] {
}
newText += delimiters.shift() + sortedYaml
} else {
return []
return [] as TextEdit[]
}
})
if (activeEditor.selection.isEmpty && settings.getUseLeadingDashes()) {
newText = "---\n" + newText
newText = `---\n${newText}`
}

const edits = vscodeadapter.getEdits(activeEditor, newText)
vscodeadapter.showMessage(Severity.INFO, "Keys resorted successfully")
vscodeadapter.applyEdits([edits])
return [edits]
}
return []
return [] as TextEdit[]
}

export function validateYamlWrapper(): boolean {
const activeEditor = vscode.window.activeTextEditor
const activeEditor = window.activeTextEditor

if (activeEditor) {
const text = vscodeadapter.getActiveDocument(activeEditor)
Expand All @@ -91,16 +91,16 @@ export function validateYamlWrapper(): boolean {
return false
}

export function formatYamlWrapper(): vscode.TextEdit[] {
const activeEditor = vscode.window.activeTextEditor
export function formatYamlWrapper(): TextEdit[] {
const activeEditor = window.activeTextEditor

if (activeEditor) {
let doc = activeEditor.document.getText()
let delimiters = getDelimiters(doc, true, settings.getUseLeadingDashes())
// remove yaml metadata tags
const matchMetadata = /^%.*\n/gm
// set metadata tags, if there is no metadata tag it should be an emtpy array
if (doc.match(matchMetadata)) {
if (matchMetadata.test(doc)) {
delimiters.shift()
delimiters = removeLeadingLineBreakOfFirstElement(delimiters)
}
Expand All @@ -119,7 +119,7 @@ export function formatYamlWrapper(): vscode.TextEdit[] {
}
}
if (settings.getUseLeadingDashes()) {
newText = "---\n" + newText
newText = `---\n${newText}`
}
const edits = vscodeadapter.getEdits(activeEditor, newText)
vscodeadapter.applyEdits([edits])
Expand All @@ -130,17 +130,17 @@ export function formatYamlWrapper(): vscode.TextEdit[] {

/**
* Sorts all yaml files in a directory
* @param {vscode.Uri} uri Base URI
* @param {Uri} uri Base URI
*/
export function sortYamlFiles(uri: vscode.Uri): boolean {
export function sortYamlFiles(uri: Uri): boolean {
const files = new FileUtil().getFilesWithExtensions(uri.fsPath)
files.forEach((file: string) => {
const yaml = fs.readFileSync(file, 'utf-8').toString()
const yaml = readFileSync(file, 'utf-8').toString()
const sortedYaml = yamlutil.sortYaml(yaml, 0)

if (sortedYaml) {
try {
fs.writeFileSync(file, sortedYaml)
writeFileSync(file, sortedYaml)
} catch (e) {
/* istanbul ignore next */
vscodeadapter.showMessage(Severity.ERROR, `File ${file} could not be sorted`)
Expand Down
4 changes: 2 additions & 2 deletions src/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,12 @@ export function addNewLineBeforeKeywordsUpToLevelN(n: number, indent: number, te
let result = text;

while (level < n) {
if (level == 0) {
if (level === 0) {
result = result.replace(/\n[^\s].*:/g, "\n$&")
} else {
let spaces = " ".repeat(indent)
spaces = spaces.repeat(level)
const regex = new RegExp("\n" + spaces + "[\\w-]*:", "g")
const regex = new RegExp(`\n${spaces}[\\w-]*:`, "g")
result = result.replace(regex, "\n$&")
}
level++;
Expand Down
Loading

0 comments on commit 4e61b4e

Please sign in to comment.