25 use Wikimedia\Assert\Assert;
66 public static function diff( $oldText, $newText ) {
70 '@phan-var TextSlotDiffRenderer $slotDiffRenderer';
71 return $slotDiffRenderer->getTextDiff( $oldText, $newText );
89 Assert::parameter( in_array(
$type, $engines,
true ),
'$type',
90 'must be one of the TextSlotDiffRenderer::ENGINE_* constants' );
91 if (
$type === self::ENGINE_EXTERNAL ) {
92 Assert::parameter( is_string( $executable ) && is_executable( $executable ),
'$executable',
93 'must be a path to a valid executable' );
95 Assert::parameter( is_null( $executable ),
'$executable',
96 'must not be set unless $type is ENGINE_EXTERNAL' );
98 $this->engine =
$type;
99 $this->externalEngine = $executable;
106 $oldText = $oldContent->serialize();
107 $newText = $newContent->serialize();
119 Assert::parameterType(
'string', $oldText,
'$oldText' );
120 Assert::parameterType(
'string', $newText,
'$newText' );
122 $diff =
function () use ( $oldText, $newText ) {
123 $time = microtime(
true );
127 $time = intval( ( microtime(
true ) - $time ) * 1000 );
128 if ( $this->statsdDataFactory ) {
129 $this->statsdDataFactory->timing(
'diff_time', $time );
148 $error =
function (
$status ) {
153 if ( strlen( $oldText ) + strlen( $newText ) > 20000 ) {
155 md5( $oldText ) . md5( $newText ),
156 [
'doWork' => $diff,
'error' => $error ]
158 return $work->execute();
176 $oldText = str_replace(
"\r\n",
"\n", $oldText );
177 $newText = str_replace(
"\r\n",
"\n", $newText );
181 if ( $this->engine === self::ENGINE_WIKIDIFF2 ) {
182 $wikidiff2Version = phpversion(
'wikidiff2' );
184 $wikidiff2Version !==
false &&
185 version_compare( $wikidiff2Version,
'1.5.0',
'>=' ) &&
186 version_compare( $wikidiff2Version,
'1.8.0',
'<' )
188 $text = wikidiff2_do_diff(
196 $text = wikidiff2_do_diff(
204 } elseif ( $this->engine === self::ENGINE_EXTERNAL ) {
207 $tempName1 = tempnam( $tmpDir,
'diff_' );
208 $tempName2 = tempnam( $tmpDir,
'diff_' );
210 $tempFile1 = fopen( $tempName1,
"w" );
214 $tempFile2 = fopen( $tempName2,
"w" );
218 fwrite( $tempFile1, $oldText );
219 fwrite( $tempFile2, $newText );
220 fclose( $tempFile1 );
221 fclose( $tempFile2 );
223 $result = Shell::command( $cmd )
225 $exitCode = $result->getExitCode();
226 if ( $exitCode !== 0 ) {
227 throw new Exception(
"External diff command returned code {$exitCode}. Stderr: "
231 $difftext = $result->getStdout();
232 unlink( $tempName1 );
233 unlink( $tempName2 );
236 } elseif ( $this->engine === self::ENGINE_PHP ) {
237 if ( $this->language ) {
238 $oldText = $this->language->segmentForDiff( $oldText );
239 $newText = $this->language->segmentForDiff( $newText );
241 $ota = explode(
"\n", $oldText );
242 $nta = explode(
"\n", $newText );
243 $diffs =
new Diff( $ota, $nta );
245 $difftext = $formatter->format( $diffs );
246 if ( $this->language ) {
247 $difftext = $this->language->unsegmentForDiff( $difftext );
252 throw new LogicException(
'Invalid engine: ' . $this->engine );