import * as assert from 'assert' ; import * as fs from 'fs' ; import { commands , TextDocument , TextEditor , Uri , window , workspace } from 'vscode' ; import { getTempFilePath } from './getTempFilePath' ; export class TempFile { public readonly fsPath : string ; public readonly shouldDelete : boolean ; public readonly uri : Uri ; public static fromContents ( contents , baseFilename ? , extension ? ) { return new TempFile ( { contents , baseFilename , extension } ) ; } public static fromExistingFile ( existingFilePath ) { assert ( fs . existsSync ( existingFilePath ) , `TempFile: Couldn't find path ${ existingFilePath }` ) ; return new TempFile ( { path : existingFilePath } ) ; } private constructor ( args ) { if ( "path" in args ) { this . fsPath = args . path ; this . shouldDelete = false ; } else { this . fsPath = getTempFilePath ( args . baseFilename , args . extension ) ; this . shouldDelete = true ; fs . writeFileSync ( this . fsPath , args . contents ) ; } this . uri = Uri . file ( this . fsPath ) ; } public dispose ( ) { if ( this . shouldDelete && fs . existsSync ( this . fsPath ) ) { fs . unlinkSync ( this . fsPath ) ; } } } export class TempEditor { private _editor : TextEditor | undefined ; public constructor ( public readonly document ) { } public get realEditor ( ) : TextEditor { assert ( this . _editor ) ; return this . _editor ! ; } public async open ( ) { if ( ! this . _editor ) { await this . document . open ( ) ; this . _editor = await window . showTextDocument ( this . document . realDocument ! ) ; } } public async dispose ( ) { await this . document . dispose ( ) ; } } export class TempDocument { private _document : TextDocument | undefined ; public constructor ( public readonly tempFile ) { } public get realDocument ( ) : TextDocument { assert ( this . _document ) ; return this . _document ! ; } public async open ( ) { if ( ! this . _document ) { this . _document = await workspace . openTextDocument ( this . tempFile . fsPath ) ; } } public async dispose ( ) { this . tempFile . dispose ( ) ; await commands . executeCommand ( 'workbench.action.closeActiveEditor' ) ; await commands . executeCommand ( 'workbench.action.closeAllEditors' ) ; } }