Search code examples
pythonpython-2.7tortoisesvnline-endingscornerstone

Replacing line endings conditionally in python 2.7.15


I have some svn patches that unfortunately have mixed line endings. My Windows svn client (tortoise) saves its metadata with CRLF line endings. However, my colleagues use Cornerstone on MacOS to apply patches which needs the metadata to have LF line endings. I can't bulk change all the line endings in the file (working on that with management). I need to change the line endings of only the metadata.

I am able to detect CRLF line endings in my patch file just fine but trying to replace them with LF is not working out. Can anyone help out? If there's a more efficient way to do this please let me know.

I'm using python 2.7.15

import sys
import os

CRLF = '\r\n'
LF = '\n'

filePath = sys.argv[1] 
newFilePath = filePath.replace('.patch', '-converted.patch')

newFile = open(newFilePath,'wb')
oldFile = open(filePath, 'r+b')

for idx,line in enumerate(oldFile.readlines()):
        line = str(line)
        if line.startswith("=====") or line.startswith("@@") or line.startswith("+++") or line.startswith("---") or line.startswith("Index:"):
                if line.endswith(CRLF):
                        print ("detected CRLF at line " + str(idx))
                        line.replace(CRLF, LF)
                        print ("converted line ending to LF at line " + str(idx))
                        if line.endswith(CRLF):
                                print("hmm... line " + str(idx) + " still a crlf line!!!!!!!!")
        newFile.writelines(line)

oldFile.close()
newFile.close()

Solution

  • replace method doesn't update the object it's invoked from, but merely returns the replaced string as a returning value, so you need to assign the returning value back to the variable to get it updated.

    Change this line:

    line.replace(CRLF, LF)
    

    to:

    line = line.replace(CRLF, LF)