Path: blob/master/src/applications/files/management/PhabricatorFilesManagementCompactWorkflow.php
13418 views
<?php12final class PhabricatorFilesManagementCompactWorkflow3extends PhabricatorFilesManagementWorkflow {45protected function didConstruct() {6$arguments = $this->newIteratorArguments();7$arguments[] = array(8'name' => 'dry-run',9'help' => pht('Show what would be compacted.'),10);1112$this13->setName('compact')14->setSynopsis(15pht(16'Merge identical files to share the same storage. In some cases, '.17'this can repair files with missing data.'))18->setArguments($arguments);19}2021public function execute(PhutilArgumentParser $args) {22$console = PhutilConsole::getConsole();2324$iterator = $this->buildIterator($args);25$is_dry_run = $args->getArg('dry-run');2627foreach ($iterator as $file) {28$monogram = $file->getMonogram();2930$hash = $file->getContentHash();31if (!$hash) {32$console->writeOut(33"%s\n",34pht('%s: No content hash.', $monogram));35continue;36}3738// Find other files with the same content hash. We're going to point39// them at the data for this file.40$similar_files = id(new PhabricatorFile())->loadAllWhere(41'contentHash = %s AND id != %d AND42(storageEngine != %s OR storageHandle != %s)',43$hash,44$file->getID(),45$file->getStorageEngine(),46$file->getStorageHandle());47if (!$similar_files) {48$console->writeOut(49"%s\n",50pht('%s: No other files with the same content hash.', $monogram));51continue;52}5354// Only compact files into this one if we can load the data. This55// prevents us from breaking working files if we're missing some data.56try {57$data = $file->loadFileData();58} catch (Exception $ex) {59$data = null;60}6162if ($data === null) {63$console->writeOut(64"%s\n",65pht(66'%s: Unable to load file data; declining to compact.',67$monogram));68continue;69}7071foreach ($similar_files as $similar_file) {72if ($is_dry_run) {73$console->writeOut(74"%s\n",75pht(76'%s: Would compact storage with %s.',77$monogram,78$similar_file->getMonogram()));79continue;80}8182$console->writeOut(83"%s\n",84pht(85'%s: Compacting storage with %s.',86$monogram,87$similar_file->getMonogram()));8889$old_instance = null;90try {91$old_instance = $similar_file->instantiateStorageEngine();92$old_engine = $similar_file->getStorageEngine();93$old_handle = $similar_file->getStorageHandle();94} catch (Exception $ex) {95// If the old stuff is busted, we just won't try to delete the96// old data.97phlog($ex);98}99100$similar_file101->setStorageEngine($file->getStorageEngine())102->setStorageHandle($file->getStorageHandle())103->save();104105if ($old_instance) {106$similar_file->deleteFileDataIfUnused(107$old_instance,108$old_engine,109$old_handle);110}111}112}113114return 0;115}116117}118119120