Kity Cartman
Kity Cartman

Reputation: 896

How I can merge "changes" from two text files in one file, programmatically?

Use case

The requirement is to merge CHANGES from two different files in one file. This is not about JOINING two files end-to-end.

Consider files FILE_A, FILE_B & FILE_C, respectively:

FILE_A

FUNCTION FUNCTION1
STATEMENT STATEMENT11
STATEMENT STATEMENT12
;

FUNCTION FUNCTION2
STATEMENT STATEMENT21
STATEMENT STATEMENT22
;

FILE_B

FUNCTION FUNCTION1
    STATEMENT STATEMENT11   #this is comment1
    STATEMENT STATEMENT12
;

FUNCTION FUNCTION2
    STATEMENT STATEMENT21   #this is comment2
    STATEMENT STATEMENT22
;

FILE_C

FUNCTION FUNCTION1
STATEMENT STATEMENT11
STATEMENT STATEMENT12
;

FUNCTION FUNCTION2
STATEMENT STATEMENT21
STATEMENT STATEMENT22
STATEMENT STATEMENT23
;

The important thing to notice here is that FILE_A & FILE_C are system-generated while FILE_B includes indentation corrections and comments made by the user.

The problem is that every time this file is system generated, we are losing the indentations and comments made by the user.

Solution I propose:

After generating FILE_C, system should merge changes from FILE_B & FILE_C into a new file, FILE_D which I call as superimposing files.

FILE_D

FUNCTION FUNCTION1
    STATEMENT STATEMENT11   #this is comment1
    STATEMENT STATEMENT12
;

FUNCTION FUNCTION2
    STATEMENT STATEMENT21   #this is comment2
    STATEMENT STATEMENT22
    STATEMENT STATEMENT23
;

But I am not sure how to achieve this programmitically!

Any suggestion on how to solve this problem is appreciated. I am trying to solve this problem in Scala though.


Edited 1

What alternative approach could I employ to preserve indentations and comments?

The system takes care of preserving other changes besides indentations and comments, made by the user, such as, functions and statements but not indentations and comments. How to achieve the same? Please suggest?

Please let me know if this is the right place for this question or this question needs to be expressed in a better way.

Upvotes: 0

Views: 205

Answers (1)

janssen-dev
janssen-dev

Reputation: 2771

This is a known problem for generated configuration files. Trying to merge these files somehow is in my opinion the wrong approach, as it is also very error-prone. Even big applications like git do not merge multiple changes in one file (instead, you have to do it manually. It is called a merge conflict). Most approach this by adding the information #DO NOT EDIT THIS FILE - ANY CHANGES WILL BE OVERRIDEN to the generated configuration file. The user is then instead meant to copy the file to another directory and make changes there.

Directory Structure

config
|
` - generated
|   |
|   `application.conf # Generate your config to this file
|
|
` - changes
    |
    `application.conf # Read your config from this file. If it doesn't exist, read config/generated/application.conf instead

Upvotes: 2

Related Questions