|
| 1 | +#!/usr/bin/env php |
| 2 | +<?php |
| 3 | + |
| 4 | +require 'vendor/autoload.php'; |
| 5 | + |
| 6 | + |
| 7 | +use Symfony\Component\Console\Command\Command; |
| 8 | +use Symfony\Component\Console\Input\InputArgument; |
| 9 | +use Symfony\Component\Console\Input\InputInterface; |
| 10 | +use Symfony\Component\Console\Output\OutputInterface; |
| 11 | +use Symfony\Component\Console\SingleCommandApplication; |
| 12 | +use Symfony\Component\Console\Style\SymfonyStyle; |
| 13 | + |
| 14 | + |
| 15 | +$command = (new SingleCommandApplication(name: 'file-diff')) |
| 16 | + ->addArgument('oldFile', InputArgument::REQUIRED, 'old file name') |
| 17 | + ->addArgument('newFile', InputArgument::REQUIRED, 'new file name') |
| 18 | + ->setCode(function (InputInterface $input, OutputInterface $output): int { |
| 19 | + $io = new SymfonyStyle($input, $output); |
| 20 | + $oldFile = $input->getArgument('oldFile'); |
| 21 | + $newFile = $input->getArgument("newFile"); |
| 22 | + |
| 23 | + if (!file_exists($oldFile) || !file_exists($newFile)) { |
| 24 | + $io->error("file does not exists"); |
| 25 | + return Command::FAILURE; |
| 26 | + } |
| 27 | + |
| 28 | + fileDiff($oldFile, $newFile); |
| 29 | + return Command::SUCCESS; |
| 30 | + })->run(); |
| 31 | + |
| 32 | + |
| 33 | +function fileDiff($oldFilePath, $newFilePath) |
| 34 | +{ |
| 35 | + $oldLines = file($oldFilePath, FILE_IGNORE_NEW_LINES); |
| 36 | + $newLines = file($newFilePath, FILE_IGNORE_NEW_LINES); |
| 37 | + |
| 38 | + |
| 39 | + $oldLineCount = count($oldLines); |
| 40 | + $newLineCount = count($newLines); |
| 41 | + |
| 42 | + |
| 43 | + $maxLineCount = max($oldLineCount, $newLineCount); |
| 44 | + |
| 45 | + $changes = []; |
| 46 | + for ($i = 0; $i < $maxLineCount; $i++) { |
| 47 | + $oldLine = $i < $oldLineCount ? $oldLines[$i] : null; |
| 48 | + $newLine = $i < $newLineCount ? $newLines[$i] : null; |
| 49 | + |
| 50 | + if ($oldLine === $newLine) { |
| 51 | + continue; |
| 52 | + } |
| 53 | + |
| 54 | + $colorGreen = "\e[32m"; |
| 55 | + $colorRed = "\e[31m"; |
| 56 | + $colorReset = "\e[0m"; |
| 57 | + |
| 58 | + |
| 59 | + $oldLineNumber = $i + 1; |
| 60 | + $newLineNumber = $i + 1; |
| 61 | + |
| 62 | + |
| 63 | + $changes[] = ($oldLine === null ? "$colorGreen+ New (Line $newLineNumber): " : "$colorRed- Old (Line $oldLineNumber): ") . ($oldLine ?? $newLine) . "$colorReset"; |
| 64 | + |
| 65 | + if ($oldLine !== null && $newLine !== null) { |
| 66 | + $changes[] = "$colorGreen+ New (Line $newLineNumber): " . $newLine . "$colorReset"; |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + |
| 71 | + $console = fopen("php://stdout", "w"); |
| 72 | + foreach ($changes as $change) { |
| 73 | + fwrite($console, $change . PHP_EOL); |
| 74 | + } |
| 75 | + |
| 76 | + fclose($console); |
| 77 | +} |
0 commit comments