const State = require('../State') class UnpackState extends State { static get services() { return [...super.services, 'output'] } async apply() { if ( !(await this.check()) ) { const path = await this._path() await path.classify() if ( !path.is_file() ) throw new Error(`Invalid path for unpack: ${path}`) const type = await this._get_type() const destination = await this._destination() const cd_cmd = await this._host.get_directory_change_command(await destination.directory()) if ( type === 'tar' ) { const untar_cmd = `${cd_cmd} && tar -x -z -f "${path.path}"` await this._host.run(untar_cmd) } else if ( type === 'zip' ) { const unzip_cmd = `${cd_cmd} && unzip "${path.path}"` await this._host.run(unzip_cmd) } } } async check() { return false } async reverse() { this.output.warn(`Unpack state does not currently support reversal. (Host: ${this._host.name})`) } async _get_type() { if ( this._config.format ) { if ( this._config.format === 'tar' ) return 'tar' else if ( this._config.format === 'zip' ) return 'zip' throw new Error('Invalid unpack format: ' + this._config.type) } else { const path = await this._path() if ( path.path.endsWith('.tar.gz') || path.path.endsWith('.tgz') ) return 'tar' else if ( path.path.endsWith('.zip') ) return 'zip' throw new Error(`Unable to determine unpack type from archive: ${path}`) } } async _path() { if ( !this._config.path ) throw new Error('Missing path config for UnpackState.') return this._host.get_path(this._config.path) } async _destination() { if ( !this._config.destination ) throw new Error('Missing destination config for UnpackState.') const path = await this._host.get_path(this._config.destination) await path.classify() if ( !path.is_directory() ) throw new Error(`Invalid extraction path. Must be a directory: ${path}`) return path } failure_message() { return `The unpacked archive does not exist at the path "${this._config.destination}" on host "${this._host.name}."` } check_message() { return this.failure_message() } display() { return `Un-archive the contents of ${this._config.path} to ${this._config.destination}...` } } module.exports = exports = UnpackState