import * as crypto from "crypto" ; import * as fse from 'fs-extra' ; import * as path from 'path' ; import { MessageItem } from "vscode" ; import { DialogResponses , IActionContext , parseError } from "vscode-azureextensionui" ; import { localize } from "../localize" ; export async function writeFormattedJson ( fsPath , data ) { await fse . writeJson ( fsPath , data , { spaces : 2 } ) ; } export async function copyFolder ( context , fromPath , toPath ) { const files = await fse . readdir ( fromPath ) ; for ( const file of files ) { const originPath = path . join ( fromPath , file ) ; const stat = await fse . stat ( originPath ) ; const targetPath = path . join ( toPath , file ) ; if ( stat . isFile ( ) ) { if ( await confirmOverwriteFile ( context , targetPath ) ) { await fse . copy ( originPath , targetPath , { overwrite : true } ) ; } } else if ( stat . isDirectory ( ) ) { await copyFolder ( context , originPath , targetPath ) ; } } } export async function confirmEditJsonFile ( context , fsPath , editJson ) { let newData ; if ( await fse . pathExists ( fsPath ) ) { try { newData = await editJson ( < { } > await fse . readJson ( fsPath ) ) ; } catch ( error ) { if ( parseError ( error ) . isUserCancelledError ) { throw error ; } else if ( await confirmOverwriteFile ( context , fsPath ) ) { newData = await editJson ( { } ) ; } else { return ; } } } else { newData = await editJson ( { } ) ; } await writeFormattedJson ( fsPath , newData ) ; } export async function confirmOverwriteFile ( context , fsPath ) { if ( await fse . pathExists ( fsPath ) ) { const result = await context . ui . showWarningMessage ( localize ( 'fileAlreadyExists' , 'File "{0}" already exists. Overwrite?' , fsPath ) , { modal : true , stepName : 'overwriteFile' } , DialogResponses . yes , DialogResponses . no ) ; if ( result === DialogResponses . yes ) { return true ; } else { return false ; } } else { return true ; } } export function getRandomHexString ( length = 10 ) { const buffer = crypto . randomBytes ( Math . ceil ( length / 2 ) ) ; return buffer . toString ( 'hex' ) . slice ( 0 , length ) ; } export function isPathEqual ( fsPath1 , fsPath2 , relativeFunc = path . relative ) { const relativePath = relativeFunc ( fsPath1 , fsPath2 ) ; return relativePath === '' ; } export function isSubpath ( expectedParent , expectedChild , relativeFunc = path . relative ) { const relativePath = relativeFunc ( expectedParent , expectedChild ) ; return relativePath !== '' && ! relativePath . startsWith ( '..' ) && relativePath !== expectedChild ; } type pathRelativeFunc = ( fsPath1 : string , fsPath2 : string ) => string ;