How to Merge Source Code Files

GroupDocs.Comparison can merge source code files by exposing each detected change as a ChangeInfo and letting you set comparison_action to ComparisonAction.ACCEPT (apply without highlighting) or ComparisonAction.REJECT (discard from the result).

Steps to apply or reject changes

  1. Instantiate Comparer with the source document path or stream.
  2. Call add() with the target document.
  3. Call compare() to run the comparison.
  4. Call get_changes() to retrieve the change collection.
  5. Set comparison_action on each change to ComparisonAction.ACCEPT or ComparisonAction.REJECT.
  6. Call apply_changes() with ApplyChangeOptions(changes=...) to produce the merged file.

Example scenario

You need to compare several versions of source code files and selectively accept or discard changes made by different authors.

Before comparison:

Source file Target file

The differences show two methods in source.cs: AddNumbers and Sum. Without using comparison_action, all changes are auto-applied to the output and both methods are removed. With comparison_action you can choose which method survives.

Example: Merge two source code files

from groupdocs.comparison import Comparer
from groupdocs.comparison.options import ApplyChangeOptions
from groupdocs.comparison.result import ComparisonAction

def merge_source_code_files():
    with Comparer("./source.cs") as comparer:
        comparer.add("./target.cs")
        comparer.compare("./result.cs")
        changes = comparer.get_changes()

        # Accept the first 10 changes; reject the rest
        for i, change in enumerate(changes):
            change.comparison_action = ComparisonAction.ACCEPT if i < 10 else ComparisonAction.REJECT

        with open("./result.cs", "wb") as result_file:
            comparer.apply_changes(result_file, ApplyChangeOptions(changes=changes))

if __name__ == "__main__":
    merge_source_code_files()

source.cs is the source file used in this example. Click here to download it.

target.cs is the target file used in this example. Click here to download it.

Binary file (CS, 121 bytes)

Download full output

Result

The merged file marks deleted elements in red, added elements in blue, and modified elements in green. An accompanying HTML file highlights every changed code region.

Result source code fileResult HTML file

As shown, only one of the two methods was removed.

Close
Loading

Analyzing your prompt, please hold on...

An error occurred while retrieving the results. Please refresh the page and try again.