@@ -4,38 +4,35 @@ import * as vscode from "vscode";
44import * as path from "path" ;
55import * as fs from "fs" ;
66import * as child_process from "child_process" ;
7- import { getTextEditsFromPatch } from "../common/editor" ;
7+ import { getTextEditsFromPatch , getTempFileWithDocumentContents } from "../common/editor" ;
88
99export class PythonImportSortProvider {
1010 public sortImports ( extensionDir : string , document : vscode . TextDocument ) : Promise < vscode . TextEdit [ ] > {
1111 if ( document . lineCount === 1 ) {
1212 return Promise . resolve ( [ ] ) ;
1313 }
14- let filePath = document . uri . fsPath ;
15- let importScript = path . join ( extensionDir , "pythonFiles" , "sortImports.py" ) ;
1614 return new Promise < vscode . TextEdit [ ] > ( ( resolve , reject ) => {
17- let ext = path . extname ( filePath ) ;
18- let tmp = require ( "tmp" ) ;
19- tmp . file ( { postfix : ext } , function ( err , tmpFilePath , fd ) {
20- if ( err ) {
21- return reject ( err ) ;
22- }
23- fs . writeFile ( tmpFilePath , document . getText ( ) , ex => {
24- if ( ex ) {
25- return reject ( `Failed to create a temporary file, ${ ex . message } ` ) ;
15+ // isort does have the ability to read from the process input stream and return the formatted code out of the output stream
16+ // However they don't support returning the diff of the formatted text when reading data from the input stream
17+ // Yes getting text formatted that way avoids having to create a temporary file, however the diffing will have
18+ // to be done here in node (extension), i.e. extension cpu, i.e. les responsive solution
19+ let importScript = path . join ( extensionDir , "pythonFiles" , "sortImports.py" ) ;
20+ let tmpFileCreated = document . isDirty ;
21+ let filePromise = tmpFileCreated ? getTempFileWithDocumentContents ( document ) : Promise . resolve ( document . fileName ) ;
22+ filePromise . then ( filePath => {
23+ child_process . exec ( `python "${ importScript } " "${ filePath } " --diff` , ( error , stdout , stderr ) => {
24+ if ( tmpFileCreated ) {
25+ fs . unlink ( filePath ) ;
26+ }
27+ if ( error || ( stderr && stderr . length > 0 ) ) {
28+ return reject ( error ? error : stderr ) ;
2629 }
2730
28- child_process . exec ( `python "${ importScript } " "${ tmpFilePath } " --diff` , ( error , stdout , stderr ) => {
29- if ( error || ( stderr && stderr . length > 0 ) ) {
30- return reject ( error ? error : stderr ) ;
31- }
32-
33- let formattedText = stdout ;
34- let edits = getTextEditsFromPatch ( document . getText ( ) , stdout ) ;
35- resolve ( edits ) ;
36- } ) ;
31+ let formattedText = stdout ;
32+ let edits = getTextEditsFromPatch ( document . getText ( ) , stdout ) ;
33+ resolve ( edits ) ;
3734 } ) ;
38- } ) ;
35+ } ) . catch ( reject ) ;
3936 } ) ;
4037 }
4138}
0 commit comments