Skip to content
This repository was archived by the owner on Jul 6, 2022. It is now read-only.

Commit 9e3a159

Browse files
sprinkle some extra comments
1 parent c66bba0 commit 9e3a159

3 files changed

Lines changed: 30 additions & 10 deletions

File tree

‎src/core/Formatter.ts‎

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@ export default class Formatter {
105105
const lines = query.split('\n');
106106
let newQuery: string[] = [];
107107
for (let i = 0; i < lines.length; i++) {
108+
// if line has trailing comma
108109
if (lines[i].match(/.*,$/)) {
109110
let commaLines = [lines[i]];
110111
// find all lines in comma-bound clause, + 1
@@ -113,8 +114,9 @@ export default class Formatter {
113114
}
114115

115116
if (this.cfg.commaPosition === CommaPosition.tabular) {
116-
commaLines = commaLines.map(commaLine => commaLine.replace(/,$/, ''));
117+
commaLines = commaLines.map(commaLine => commaLine.replace(/,$/, '')); // trim all trailing commas
117118
const commaMaxLength = maxLength(commaLines); // get longest for alignment
119+
// make all lines the same length by appending spaces before comma
118120
commaLines = commaLines.map((commaLine, j) =>
119121
j < commaLines.length - 1 // do not add comma for last item
120122
? commaLine + ' '.repeat(commaMaxLength - commaLine.length) + ','
@@ -183,6 +185,7 @@ export default class Formatter {
183185
const aliasMaxLength = maxLength(
184186
splitLines.map(({ precedingText }) => precedingText.replace(/\s*,\s*$/, '')) // get longest of precedingText, trim trailing comma for non-alias columns
185187
);
188+
// re-construct line, aligning by inserting space before AS or alias
186189
aliasLines = splitLines.map(
187190
({ precedingText, as, alias }) =>
188191
precedingText +
@@ -208,13 +211,14 @@ export default class Formatter {
208211
for (this.index = 0; this.index < this.tokens.length; this.index++) {
209212
let token = this.tokenOverride(this.tokens[this.index]);
210213

214+
// if token is a Reserved Keyword, Command, Binary Command, Dependent Clause, Logical Operator
211215
if (isReserved(token)) {
212216
this.previousReservedToken = token;
213217
if (token.type !== TokenType.RESERVED_KEYWORD) {
214-
token = this.tenSpacedToken(token);
218+
token = this.tenSpacedToken(token); // convert Reserved Command or Logical Operator to tenSpace format if needed
215219
}
216220
if (token.type === TokenType.RESERVED_COMMAND) {
217-
this.withinSelect = isToken.SELECT(token);
221+
this.withinSelect = isToken.SELECT(token); // set withinSelect flag if entering a SELECT clause, else reset
218222
}
219223
}
220224

@@ -246,7 +250,7 @@ export default class Formatter {
246250
formattedQuery = this.formatWord(token, formattedQuery);
247251
}
248252
}
249-
return formattedQuery.replace(new RegExp(ZWS, 'ugim'), ' ');
253+
return formattedQuery.replace(new RegExp(ZWS, 'ugim'), ' '); // replace all ZWS with whitespace for TenSpace formats
250254
}
251255

252256
/**
@@ -316,8 +320,9 @@ export default class Formatter {
316320
* @return {boolean} Whether or not a newline should be inserted
317321
*/
318322
checkNewline(index: number): boolean {
319-
const tail = this.tokens.slice(index + 1);
323+
const tail = this.tokens.slice(index + 1); // get all tokens after current token
320324
const nextTokens = tail.slice(
325+
// get all tokens between current token and next Reserved Command or query end
321326
0,
322327
tail.length
323328
? tail.findIndex(
@@ -395,15 +400,17 @@ export default class Formatter {
395400

396401
query = this.addNewline(query);
397402

403+
// indent TenSpace formats, except when preceding a (
398404
if (this.cfg.tenSpace) {
399405
if (this.tokenLookAhead()?.value !== '(') {
400406
this.indentation.increaseTopLevel();
401407
}
408+
// indent standard format, except when is [FROM] (
402409
} else if (!(this.tokenLookAhead()?.value === '(' && isToken.FROM(token))) {
403410
this.indentation.increaseTopLevel();
404411
}
405412

406-
query += this.equalizeWhitespace(this.show(token));
413+
query += this.equalizeWhitespace(this.show(token)); // print token onto query
407414
if (this.currentNewline && !this.cfg.tenSpace) {
408415
query = this.addNewline(query);
409416
} else {
@@ -418,7 +425,7 @@ export default class Formatter {
418425
* @param {string} query - formatted query so far
419426
*/
420427
formatBinaryCommand(token: Token, query: string): string {
421-
const isJoin = /JOIN/i.test(token.value);
428+
const isJoin = /JOIN/i.test(token.value); // check if token contains JOIN
422429
if (!isJoin || this.cfg.tenSpace) {
423430
// decrease for boolean set operators or in tenSpace modes
424431
this.indentation.decreaseTopLevel();
@@ -490,6 +497,7 @@ export default class Formatter {
490497
* @param {string} query - formatted query so far
491498
*/
492499
formatLogicalOperator(token: Token, query: string): string {
500+
// ignore AND when BETWEEN x [AND] y
493501
if (isToken.AND(token) && isToken.BETWEEN(this.tokenLookBehind(2))) {
494502
return this.formatWithSpaces(token, query);
495503
}
@@ -637,6 +645,8 @@ export default class Formatter {
637645
formatQuerySeparator(token: Token, query: string): string {
638646
this.indentation.resetIndentation();
639647
query = trimSpacesEnd(query);
648+
649+
// move delimiter to new line if specified
640650
if (this.cfg.semicolonNewline) {
641651
query += '\n';
642652
if (this.cfg.tenSpace) {

‎src/core/Tokenizer.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,15 +168,18 @@ export default class Tokenizer {
168168
*/
169169
getPlaceholderToken(input: string): Token | undefined {
170170
const placeholderTokenRegexMap: { regex: RegExp; parseKey: (s: string) => string }[] = [
171+
// pattern for placeholder with identifier name
171172
{
172173
regex: this.IDENT_NAMED_PLACEHOLDER_REGEX ?? NULL_REGEX,
173174
parseKey: v => v.slice(1),
174175
},
176+
// pattern for placeholder with string name
175177
{
176178
regex: this.STRING_NAMED_PLACEHOLDER_REGEX ?? NULL_REGEX,
177179
parseKey: v =>
178180
this.getEscapedPlaceholderKey({ key: v.slice(2, -1), quoteChar: v.slice(-1) }),
179181
},
182+
// pattern for placeholder with numeric index
180183
{
181184
regex: this.INDEXED_PLACEHOLDER_REGEX ?? NULL_REGEX,
182185
parseKey: v => v.slice(1),
@@ -204,6 +207,7 @@ export default class Tokenizer {
204207
return undefined;
205208
}
206209

210+
// prioritised list of Reserved token types
207211
const reservedTokenList = [
208212
TokenType.RESERVED_COMMAND,
209213
TokenType.RESERVED_BINARY_COMMAND,

‎vscode/src/extension.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,17 +14,18 @@ const getConfigs = (
1414
language: FormatterLanguage
1515
) => {
1616
const ignoreTabSettings = settings.get<boolean>('ignoreTabSettings');
17-
const { tabSize, insertSpaces } = ignoreTabSettings
17+
const { tabSize, insertSpaces } = ignoreTabSettings // override tab settings if ignoreTabSettings is true
1818
? {
1919
tabSize: settings.get<number>('tabSizeOverride')!,
2020
insertSpaces: settings.get<boolean>('insertSpacesOverride')!,
2121
}
2222
: formattingOptions;
2323
const indent = insertSpaces ? ' '.repeat(tabSize) : '\t';
2424

25+
// build format configs from settings
2526
const formatConfigs = {
2627
language:
27-
language === 'sql'
28+
language === 'sql' // override default SQL language mode if SQLFlavourOverride is set
2829
? settings.get<FormatterLanguage>('SQLFlavourOverride') ?? 'sql'
2930
: language,
3031
indent,
@@ -36,7 +37,7 @@ const getConfigs = (
3637
commaPosition: settings.get<CommaPosition>('commaPosition'),
3738
newline: (newlineSetting =>
3839
newlineSetting === 'itemCount'
39-
? settings.get<number>('itemCount')
40+
? settings.get<number>('itemCount') // pass itemCount number if keywordNewline is itemCount mode
4041
: (newlineSetting as NewlineMode))(settings.get<string>('keywordNewline')),
4142
parenOptions: {
4243
openParenNewline: settings.get<boolean>('parenOptions.openParenNewline'),
@@ -60,6 +61,7 @@ export function activate(context: vscode.ExtensionContext) {
6061
const settings = vscode.workspace.getConfiguration('Prettier-SQL');
6162
const formatConfigs = getConfigs(settings, options, language);
6263

64+
// extract all lines from document
6365
const lines = [...new Array(document.lineCount)].map((_, i) => document.lineAt(i).text);
6466
let text;
6567
try {
@@ -69,6 +71,7 @@ export function activate(context: vscode.ExtensionContext) {
6971
return [];
7072
}
7173

74+
// replace document with formatted text
7275
return [
7376
vscode.TextEdit.replace(
7477
new vscode.Range(
@@ -90,6 +93,7 @@ export function activate(context: vscode.ExtensionContext) {
9093
'hive-sql': 'sql',
9194
'sql-bigquery': 'bigquery',
9295
};
96+
// add Prettier-SQL as a format provider for each language
9397
Object.entries(languages).forEach(([vscodeLang, prettierLang]) =>
9498
context.subscriptions.push(
9599
vscode.languages.registerDocumentFormattingEditProvider(
@@ -107,6 +111,7 @@ export function activate(context: vscode.ExtensionContext) {
107111

108112
const settings = vscode.workspace.getConfiguration('Prettier-SQL');
109113

114+
// get tab settings from workspace
110115
const workspaceConfig = vscode.workspace.getConfiguration('editor');
111116
const tabOptions = {
112117
tabSize: workspaceConfig.get<number>('tabSize')!,
@@ -117,6 +122,7 @@ export function activate(context: vscode.ExtensionContext) {
117122

118123
const editor = vscode.window.activeTextEditor;
119124
try {
125+
// format and replace each selection
120126
editor?.edit(editBuilder => {
121127
editor.selections.forEach(sel =>
122128
editBuilder.replace(sel, format(editor.document.getText(sel), formatConfigs))

0 commit comments

Comments
 (0)