無意間想到這個問題,如何用php來實現git diff,如果實現了這個功能,豈不是能夠使用php對在線編輯文件的功能做更進一步的優化和提升?
查了一下還真有這樣的庫,話不多說,開始執行
composer require --dev sebastian/diff
得到結果
Info from https://repo.packagist.org: #StandWithUkraine Using version ^5.0 for sebastian/diff ./composer.json has been created Running composer update sebastian/diff Loading composer repositories with package information Updating dependencies Lock file operations: 1 install, 0 updates, 0 removals - Locking sebastian/diff (5.0.1) Writing lock file Installing dependencies from lock file (including require-dev) Package operations: 1 install, 0 updates, 0 removals - Downloading sebastian/diff (5.0.1) - Installing sebastian/diff (5.0.1): Extracting archive Generating autoload files 1 package you are using is looking for funding. Use the `composer fund` command to find out more!
好,安裝成功,創建index.php如下
<?php include("./vendor/autoload.php"); use SebastianBergmann\Diff\Differ; use SebastianBergmann\Diff\Output\UnifiedDiffOutputBuilder; $builder = new UnifiedDiffOutputBuilder( "--- Original\n+++ New\n", // custom header true // do not add line numbers to the diff ); $differ = new Differ($builder); $before_string = file_get_contents("functions.php"); $after_string = file_get_contents("functions.php-new"); $diff_value = $differ->diff($before_string, $after_string); echo $diff_value;
好,然後創建兩個文件用來代表我們修改過文件的內容,修改之前的文件叫 functions.php 內容是
<?php function get_rand_id ($id = 0) { static $id; if ($id) { return $id; } $id = rand(1, 1000); $id += 1000; return $id; }
修改之後的文件叫 functions.php-new 內容是
<?php function get_random_id (int $id = 0) { static $id; if (!$id) { $id = rand(1, 1000); $id = $id * $id; } return $id; }
執行一下看看
php index.php &> diff.patch
得到結果
--- Original +++ New @@ -1,12 +1,11 @@ <?php -function get_rand_id ($id = 0) { +function get_random_id (int $id = 0) { static $id; - if ($id) { - return $id; + if (!$id) { + $id = rand(1, 1000); + $id = $id * $id; } - $id = rand(1, 1000); - $id += 1000; return $id; }
那這樣的結果呢也能作爲patch查看,要怎麼有更好的查看方式呢?
我們可以在vscode編輯器裏面安裝一個叫做 Diff Viewer 的插件 點擊這裏
安裝完畢, 打開這個 diff.patch 文件後是這樣的
怎麼樣,是不是很不錯,有點像 git 的感覺了,哈哈哈