@@ -3,6 +3,7 @@ import {languages} from 'vscode';
33import * as utils from './utils' ;
44import { Configuration } from './extension' ;
55import * as path from 'path' ;
6+ import * as os from 'os' ;
67
78class LineDiff {
89 constructor ( public isInsert : boolean ,
@@ -480,13 +481,58 @@ class PgindentDocumentFormatterProvider implements vscode.DocumentFormattingEdit
480481 return [ ] ;
481482 }
482483 }
484+
485+ async indentFileWithTemp ( document : vscode . TextDocument ) {
486+ const workspace = findSuitableWorkspace ( document ) ;
487+ const indented = await this . runPgindent ( document , workspace ) ;
488+ const tempFile = utils . joinPath (
489+ vscode . Uri . file ( os . tmpdir ( ) ) , path . basename ( document . uri . fsPath ) ) ;
490+ await utils . writeFile ( tempFile , indented ) ;
491+ return tempFile ;
492+ }
493+ }
494+
495+ function registerDiffCommand ( logger : utils . VsCodeLogger ,
496+ formatter : PgindentDocumentFormatterProvider ) {
497+ /* Preview formatter changes command */
498+ vscode . commands . registerCommand ( Configuration . Commands . FormatterDiffView , async ( ) => {
499+ if ( ! vscode . window . activeTextEditor ) {
500+ vscode . window . showWarningMessage ( 'Could not show diff for file - no active document opened' ) ;
501+ return ;
502+ }
503+
504+ const document = vscode . window . activeTextEditor . document ;
505+ let parsed ;
506+ try {
507+ parsed = await formatter . indentFileWithTemp ( document ) ;
508+ } catch ( err ) {
509+ logger . error ( 'failed to format file %s' , document . uri . fsPath , err ) ;
510+ vscode . window . showErrorMessage ( 'Failed to format document. See error in logs' ) ;
511+ logger . channel . show ( true ) ;
512+ return ;
513+ }
514+
515+ try {
516+ await vscode . commands . executeCommand ( 'vscode.diff' , document . uri , parsed , 'PostgreSQL formatting' )
517+ } catch ( err ) {
518+ logger . error ( `failed to show diff for document %s` , document . uri . fsPath , err ) ;
519+ vscode . window . showErrorMessage ( 'Failed to show diff. See error in logs' ) ;
520+ logger . channel . show ( true ) ;
521+ } finally {
522+ if ( await utils . fileExists ( parsed ) ) {
523+ await utils . deleteFile ( parsed ) ;
524+ }
525+ }
526+ } ) ;
483527}
484528
485- export async function registerFormatting ( context : vscode . ExtensionContext , logger : utils . ILogger ) {
529+ export async function registerFormatting ( logger : utils . VsCodeLogger ) {
486530 const formatter = new PgindentDocumentFormatterProvider ( logger ) ;
487531 for ( const lang of [ 'c' , 'h' ] ) {
488532 languages . registerDocumentFormattingEditProvider ( {
489533 language : lang ,
490534 } , formatter ) ;
491535 }
492- }
536+
537+ registerDiffCommand ( logger , formatter ) ;
538+ }
0 commit comments