无意间想到这个问题,如何用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 的感觉了,哈哈哈
标签:5.0,php,git,composer,diff,sebastian From: https://www.cnblogs.com/lizhaoyao/p/17283836.html