setName('merge:hostsfile') ->setDescription('Merge (or remove) two hostfiles to /etc/hosts.') ->setHelp('This command allows you to a new installation...') ->addArgument('file', InputArgument::REQUIRED, 'The file to use.') ->addOption('dest', null, InputOption::VALUE_REQUIRED, 'The /etc/hosts file where to write', "/etc/hosts") ->addOption('ref', null, InputOption::VALUE_REQUIRED, 'The reference to add as a comment to simplify the remove', "handled by fd3") ->addOption('del', 'd', InputOption::VALUE_NONE, 'Remove the merged values based on the ref parameter'); } protected function execute(InputInterface $input, OutputInterface $output) { $file = $input->getArgument('file'); $dest = $input->getOption("dest"); $id = $input->getOption("ref"); $del = $input->getOption("del"); $dest_content = explode("\n", file_get_contents($dest)); $orig_content = explode("\n", file_get_contents($file)); foreach ($dest_content as $k => $spect) { if (strpos($spect, $id) !== false) { unset($dest_content[$k]); } } foreach ($orig_content as $k => $spect) { $spect = trim($spect); preg_match("|[^\s]*|", $spect, $match); if (isset($match[0])) { try { $ip = \IP::create($match[0]); $orig_content[$k] = $spect . "\t#$id"; } catch (\InvalidArgumentException $e) { } } } $content = ""; foreach ($dest_content as $line) { $content .= $line . "\n"; } if (!$del) { foreach ($orig_content as $line) { $content .= $line . "\n"; } } file_put_contents($dest, $content); } }