unidiff()
is a function designed to generate unified diffs between two files or text inputs. Unified diffs are widely used in version control systems to highlight differences between two versions of a file in a compact and readable format.
unidiff(
old,
new,
create_head = TRUE,
with_context = FALSE,
context_length = 3,
ignore_whitespace = NULL,
algorithm = "minimal",
indent_heuristic = FALSE,
ignore = NULL
)
The original file or text input. This can be a file path, a URL, or a string of text.
The modified file or text input to compare against the original. This can also be a file path, a URL, or a string of text.
A logical flag (default TRUE
) indicating whether to include a header in the diff output. The header contains the filenames or identifiers of the files being compared.
A logical flag (default FALSE
) specifying whether to include the full context in the diff output. Including context helps to provide a more complete view of the changes.
An integer value (default 3
) that determines the number of lines of context to include around each change. This is only relevant if with_context is TRUE
.
A character vector indicating how whitespace differences should be treated. Options include "all"
, "change"
, "at_eol"
, "cr_at_eol"
, and "blank_lines"
, allowing for fine-grained control over which whitespace differences to ignore.
A string specifying the diff algorithm to use. Options are "minimal"
, "patience"
, and "histogram"
, with "minimal"
being the default. Each algorithm has different characteristics suited to various types of text comparisons.
A logical flag (default FALSE
) that, when enabled, applies an additional heuristic to better handle indented lines, improving the accuracy of the diff in some cases.
A single string specifying the regex pattern to use for ignoring lines in the diff process. If this is a non-empty string, it should be a valid regex pattern. Lines in the texts that match this pattern will be ignored in the diff.
A character string containing the unified diff.
The unidiff()
function compares two inputs—whether they are files, URLs, or raw text—and generates a unified diff that highlights the differences between them. It supports advanced features like customizable context, whitespace handling, and different diff algorithms to suit various needs. The function can also handle inputs from URLs, making it flexible for remote file comparisons.
The output is a unified diff string, which can be directly used in version control systems or for manual inspection of changes.
For identical files, no diff is returned, and an empty character string is provided.
If regex support is not available on the current platform and a non-empty pattern is provided, an error will be raised.
cat(unidiff(old = "foo bar", new = "foo baz"))
#> ===================================================================
#> --- old
#> +++ new
#> @@ -1 +1 @@
#> -foo bar
#> \ No newline at end of file
#> +foo baz
#> \ No newline at end of file