Skip to content

Commit

Permalink
Initial implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
raphaelstolt committed Jan 24, 2025
0 parents commit 76ff69e
Show file tree
Hide file tree
Showing 14 changed files with 429 additions and 0 deletions.
19 changes: 19 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
; This file is for unifying the coding style for different editors and IDEs.
; More information at http://editorconfig.org

root = true

[*]
charset = utf-8
indent_size = 4
indent_style = space
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

[*.md]
trim_trailing_whitespace = false

[*.yml]
indent_style = space
indent_size = 2
13 changes: 13 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
* text=auto eol=lf

.editorconfig export-ignore
.gitattributes export-ignore
.github/ export-ignore
.gitignore export-ignore
.php-cs-fixer.php export-ignore
CHANGELOG.md export-ignore
LICENSE.md export-ignore
phpstan.neon.dist export-ignore
phpunit.xml.dist export-ignore
README.md export-ignore
tests/ export-ignore
32 changes: 32 additions & 0 deletions .github/workflows/lint.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
name: lint

on: push

jobs:
build:
name: lint
runs-on: ubuntu-latest

strategy:
fail-fast: true
matrix:
php:
- "8.3"

steps:
- name: Checkout
uses: actions/checkout@v4

- name: Install difftastic
run: sudo snap install difftastic

- name: Install PHP
uses: shivammathur/setup-php@v2
with:
php-version: "${{ matrix.php }}"

- name: Install Composer dependencies
run: composer install --no-progress --prefer-dist --optimize-autoloader

- name: Check coding styles
run: composer run-script cs-lint
34 changes: 34 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
name: test

on: push

jobs:
build:
name: "PHPUnit (PHP ${{ matrix.php }})"
runs-on: ubuntu-latest

strategy:
matrix:
php:
- "8.1"
- "8.2"
- "8.3"
- "8.4"

steps:
- name: Checkout
uses: actions/checkout@v4

- name: Install difftastic
run: sudo snap install difftastic

- name: Install PHP
uses: shivammathur/setup-php@v2
with:
php-version: "${{ matrix.php }}"

- name: Install Composer dependencies
run: composer install --no-progress --prefer-dist --optimize-autoloader

- name: Run tests
run: composer run-script test
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
vendor/
coverage-reports/
composer.lock
.php_cs.cache
.phpunit.result.cache
.phpunit.cache
.idea/
28 changes: 28 additions & 0 deletions .php-cs-fixer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

use PhpCsFixer\Config;
use PhpCsFixer\Finder;
use PhpCsFixer\Runner\Parallel\ParallelConfigFactory;

$finder = Finder::create()
->in([__DIR__, __DIR__ . DIRECTORY_SEPARATOR . 'tests']);

$rules = [
'psr_autoloading' => false,
'@PSR2' => true,
'phpdoc_order' => true,
'ordered_imports' => true,
'native_function_invocation' => [
'include' => ['@internal'],
'exclude' => ['file_put_contents']
]
];

$cacheDir = \getenv('HOME') ? \getenv('HOME') : __DIR__;

$config = new Config();

return $config->setRules($rules)
->setParallelConfig(ParallelConfigFactory::detect())
->setFinder($finder)
->setCacheFile($cacheDir . '/.php-cs-fixer.cache');
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Change Log

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to
[Semantic Versioning](http://semver.org/).

## [Unreleased]

## v0.0.1 - 2025-01-24

- Initial release.

[Unreleased]: https://github.com/raphaelstolt/difftastic-php/compare/v0.0.1...HEAD
21 changes: 21 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2025 - ∞ Raphael Stolt

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
39 changes: 39 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Difftastic PHP

This Composer package provides a wrapper around [difftastic](https://github.com/Wilfred/difftastic)
for usage in PHP based projects; therefor it requires `difftastic` to be [installed](https://difftastic.wilfred.me.uk/installation.html).

## Installation

The difftastic wrapper for PHP can be installed through Composer.

``` bash
composer require stolt/difftastic-php
```

## Usage

```php
use Stolt\Difftastic;

$difftastic = new Difftastic();
$diff = $difftastic->diff('[1, 2, 3]', '[3, 2, 1]');
```

### Running tests

``` bash
composer test
```

### License

This PHP package is licensed under the MIT license. Please see [LICENSE.md](LICENSE.md) for more details.

### Changelog

Please see [CHANGELOG.md](CHANGELOG.md) for more details.

### Contributing

Please see [CONTRIBUTING.md](.github/CONTRIBUTING.md) for more details.
48 changes: 48 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
{
"name": "stolt/difftastic-php",
"description": "A wrapper around the difftastic CLI.",
"keywords": ["difftastic", "wrapper", "dev"],
"type": "library",
"license": "MIT",
"autoload": {
"psr-4": {
"Stolt\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Stolt\\Tests\\": "tests/"
}
},
"authors": [
{
"name": "Raphael Stolt",
"email": "raphael.stolt@gmail.com"
}
],
"require": {
"php": ">=8.1"
},
"scripts": {
"test": "phpunit",
"test-with-coverage": "export XDEBUG_MODE=coverage && phpunit --coverage-html coverage-reports",
"cs-fix": "php-cs-fixer --allow-risky=yes fix . -vv || true",
"cs-lint": "php-cs-fixer fix --diff --stop-on-violation --verbose --dry-run --allow-risky=yes",
"static-analyse": "phpstan analyse --configuration phpstan.neon.dist",
"pre-commit-check": [
"@test",
"@cs-lint",
"@static-analyse"
]
},
"config": {
"preferred-install": "dist",
"sort-packages": true,
"optimize-autoloader": true
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^3.0",
"phpstan/phpstan": "^2.0",
"phpunit/phpunit": "^11.4.4||^10.5.25"
}
}
21 changes: 21 additions & 0 deletions phpstan.neon.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
parameters:
level: 8
paths:
- src
- tests
treatPhpDocTypesAsCertain: false
reportUnmatchedIgnoredErrors: false
ignoreErrors:
- identifier: missingType.iterableValue
- identifier: argument.type
- identifier: identical.alwaysTrue
- identifier: method.alreadyNarrowedType
- '#Constant WORKING_DIRECTORY not found.#'
- '#Mockery\\MockInterface#'
- '#Mockery\\LegacyMockInterface#'
- '#Mockery\\ExpectationInterface#'
- '#array_filter#'
- '#is never read#'
- '#TMock#'
- '#unknown class#'
- '#set_error_handler expects#'
18 changes: 18 additions & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
backupGlobals="false" bootstrap="vendor/autoload.php"
colors="true" processIsolation="false" stopOnFailure="true"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.3/phpunit.xsd"
cacheDirectory=".phpunit.cache" backupStaticProperties="false">
<coverage/>
<testsuites>
<testsuite name="Lean Package Validator">
<directory>tests/</directory>
</testsuite>
</testsuites>
<source>
<include>
<directory suffix=".php">src/</directory>
</include>
</source>
</phpunit>
87 changes: 87 additions & 0 deletions src/Difftastic.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
<?php

declare(strict_types=1);

namespace Stolt;

use RuntimeException;

final class Difftastic
{
private string $difftasticBinaryCommand;

/**
* @throws RuntimeException
*/
public function __construct()
{
if ($this->isDifftasticCommandAvailable() === false) {
throw new RuntimeException('Difftastic CLI not available');
}
// is difftastic binary installed [x]
// set config/option values [x] (see https://github.com/joeldrapper/difftastic-ruby/blob/main/lib/difftastic/differ.rb)
// determine which difftastic binary to use, difftastic or difft [x]
}

private function isDifftasticCommandAvailable(): bool
{
$this->difftasticBinaryCommand = $this->getDifftasticBinaryByOs();

\exec('where ' . $this->difftasticBinaryCommand . ' 2>&1', $output, $returnValue);
if ($this->isWindows() === false) {
\exec('which ' . $this->difftasticBinaryCommand . ' 2>&1', $output, $returnValue);
}

return $returnValue === 0;
}

private function getDifftasticBinaryByOs(): string
{
return match (\strtolower(PHP_OS_FAMILY)) {
'darwin' => 'difft',
'linux' => 'difftastic',
'windows' => 'difftastic',
default => throw new RuntimeException(
'Unsupported operating system ' . PHP_OS_FAMILY
)
};
}
private function createTemporaryFile($name, $content): string
{
$file = DIRECTORY_SEPARATOR .
\trim(\sys_get_temp_dir(), DIRECTORY_SEPARATOR) .
DIRECTORY_SEPARATOR .
\ltrim($name, DIRECTORY_SEPARATOR);

file_put_contents($file, $content);

\register_shutdown_function(function () use ($file) {
\unlink($file);
});

return $file;
}

private function isWindows($os = PHP_OS): bool
{
if (\strtoupper(\substr($os, 0, 3)) !== 'WIN') {
return false;
}

return true;
}

public function diff(string $a, string $b): string
{
$aFile = $this->createTemporaryFile('a', $a);
$bFile = $this->createTemporaryFile('b', $b);

\exec(
$this->difftasticBinaryCommand . ' ' . $aFile . ' ' . $bFile . ' 2>&1',
$output,
$returnValue
);

return \implode(PHP_EOL, $output);
}
}
Loading

0 comments on commit 76ff69e

Please sign in to comment.