const State = require('../State') class PackState extends State { async apply() { if ( !(await this.check()) ) { const path = await this._path() const destination = await this._destination() const type = await this._get_type() const cd_cmd = await this._host.get_directory_change_command(await path.parent()) if ( type === 'tar' ) { const tar_cmd = `${cd_cmd} && tar czf "${destination.path}" "${path.name()}"` await this._host.run(tar_cmd) } else if ( type === 'zip' ) { const zip_cmd = `${cd_cmd} && zip -r "${destination.path}" "${path.name()}"` await this._host.run(zip_cmd) } } } async check() { const dest = await this._destination() return dest.is_valid() } async reverse() { if ( await this.check() ) { const destination = await this._destination() await destination.classify() if (destination.is_valid()) await destination.unlink() } } 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 dest = await this._destination() if ( dest.path.endsWith('.tar.gz') || dest.path.endsWith('.tgz') ) return 'tar' else if ( dest.path.endsWith('.zip') ) return 'zip' throw new Error(`Unable to determine unpack type from destination: ${dest}`) } } async _destination() { if ( !this._config.destination ) throw new Error('Missing destination config for PackState.') return await this._host.get_path(this._config.destination) } async _path() { const path = await this._host.get_path(this._config.path) await path.classify() if ( !path.is_valid() ) throw new Error(`Invalid path for PathState: ${path}`) return path } failure_message() { return `The archive "${this._config.destination}" does not exist on the host "${this._host.name}."` } check_message() { return this.failure_message() } } module.exports = exports = PackState