Skip to content

Instantly share code, notes, and snippets.

@AjayKrP
Created March 5, 2021 05:10
Show Gist options
  • Save AjayKrP/21f6eb3c6499c1f587f0182dc2850794 to your computer and use it in GitHub Desktop.
Save AjayKrP/21f6eb3c6499c1f587f0182dc2850794 to your computer and use it in GitHub Desktop.
Get diff between two folders and stores diff files in separate directory
import os
import sys
import difflib
from shutil import copyfile
import pathlib
if len(sys.argv) < 3:
print('[ERR]: Not enough arguments passed. Usage: get_diff.py <firstFolder> <secondFolder>')
sys.exit()
# Accept root folders arguments
firstFolderRoot = sys.argv[1]
secondFolderRoot = sys.argv[2]
fileName = 'output.txt'
fileDescriptor = open(fileName, 'w+')
destDir = 'output'
# All dirs in first folder
firstFolderDirs = [x[0] for x in os.walk(firstFolderRoot)]
# Loop through each directory in first folder
for firstFolderDir in firstFolderDirs:
# Loop through all files in the directory
for filename in os.listdir(firstFolderDir):
if filename.endswith(".php") or filename.endswith(".xml") or filename.endswith(".html") or filename.endswith(
".js") or filename.endswith("phtml"):
firstFolderFilePath = os.path.join(firstFolderDir, filename)
secondFolderFilePath = os.path.join(firstFolderDir.replace(firstFolderRoot, secondFolderRoot), filename)
# Check if file exists in secondFolderRoot
if not os.path.isfile(secondFolderFilePath):
print("[INFO]: Could not find matching file in secondFolderRoot for " + firstFolderFilePath)
continue
else:
firstFolderFile = open(firstFolderFilePath)
secondFolderFile = open(secondFolderFilePath)
print("Diff between " + firstFolderFile.name + " and " + secondFolderFile.name + ":")
# Find diff
for line in difflib.unified_diff(firstFolderFile.readlines(), secondFolderFile.readlines()):
# fileDescriptor.write("Diff between "+firstFolderFile.name+" and "+secondFolderFile.name+":\n\n")
destFileName = secondFolderFile.name
filename = os.path.basename(destFileName)
basePath = 'output/' + os.path.dirname(destFileName)
print(basePath)
if not os.path.isdir(basePath):
p = pathlib.Path(basePath)
p.mkdir(parents=True)
copyfile(secondFolderFile.name, os.path.join(basePath, filename))
print(line,)
fileDescriptor.write(line)
continue
else:
continue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment