'use strict' ; import { PackageRegistryEntry } from './PackageRegistryEntry' ; import * as fs from 'fs-extra' ; import * as path from 'path' ; import { FileSystemUtil , FileConfigurations , LogType } from 'ibm-blockchain-platform-common' ; import { SettingConfigurations } from '../configurations' ; import { VSCodeBlockchainOutputAdapter } from '../logging/VSCodeBlockchainOutputAdapter' ; export class PackageRegistry { public static instance ( ) { return PackageRegistry . _instance ; } private static _instance : PackageRegistry = new PackageRegistry ( ) ; private constructor ( ) { } public async get ( name , version ? ) { const packages = await this . getAll ( ) ; const _package = packages . find ( ( pkg ) => { return pkg . name === name && pkg . version === version ; } ) ; return _package ; } public async getAll ( ) { return await this . getEntries ( ) ; } public async delete ( packageEntry ) { await fs . remove ( packageEntry . path ) ; } public async clear ( ) { const extDir = SettingConfigurations . getExtensionDir ( ) ; const pkgDir = path . join ( extDir , FileConfigurations . PACKAGES ) ; const resolvedPkgDir = FileSystemUtil . getDirPath ( pkgDir ) ; await fs . emptyDir ( resolvedPkgDir ) ; } private async getEntries ( ) { const extDir = SettingConfigurations . getExtensionDir ( ) ; const pkgDir = path . join ( extDir , FileConfigurations . PACKAGES ) ; const resolvedPkgDir = FileSystemUtil . getDirPath ( pkgDir ) ; await fs . ensureDir ( resolvedPkgDir ) ; const pkgRegistryEntries = [ ] ; const pkgFileNames = await fs . readdir ( resolvedPkgDir ) ; for ( const pkgFileName of pkgFileNames ) { if ( pkgFileName . startsWith ( '.' ) ) { continue ; } const pkgPath = path . join ( resolvedPkgDir , pkgFileName ) ; const stat = await fs . lstat ( pkgPath ) ; const sizeKB = Math . round ( stat . size / 1000 ) ; let name ; let version ; if ( pkgFileName . endsWith ( '.cds' ) ) { try { const pkgBuffer = await fs . readFile ( pkgPath ) ; const { PackageSmartContract } = await import ( 'ibm-blockchain-platform-environment-v1' ) ; const pkgInfo = PackageSmartContract . getPackageInfo ( pkgBuffer ) ; name = pkgInfo . name ; version = pkgInfo . version ; } catch ( error ) { VSCodeBlockchainOutputAdapter . instance ( ) . log ( LogType . ERROR , null , `Failed to parse package ${ pkgFileName }: ${ error . message }` ) ; continue ; } } else { const packageRegex = new RegExp ( /(.+?)(@(.*?)){0,1}(\.tar\.gz|\.tgz){1}$/gm ) ; const result = packageRegex . exec ( pkgFileName ) ; if ( ! result ) { continue ; } name = result [ 1 ] ; version = result [ 3 ] ; } pkgRegistryEntries . push ( new PackageRegistryEntry ( { name : name , version : version , path : pkgPath , sizeKB : sizeKB } ) ) ; } return pkgRegistryEntries ; } }