Created
July 19, 2016 06:02
-
-
Save mikamikem/ba54330033c88c883bc083782042fcab to your computer and use it in GitHub Desktop.
Sorts a Unity scene or prefab file so it's consistent and can be diffed in a text diff tool.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/python | |
import sys; | |
import os; | |
import argparse; | |
import shutil; | |
parser = argparse.ArgumentParser(description='Sort Unity Files - Sorts Unity files so they can be diffed in text diff tools.', add_help=False) | |
parser.add_argument('input', help='Input scene file') | |
parser.add_argument('output', nargs='?', default='', help='Output sorted scene file') | |
sortArgs, remaining = parser.parse_known_args() | |
if sortArgs.input == None or sortArgs.input == "": | |
print("Input file must be specified!") | |
sys.exit(1) | |
output = str(sortArgs.input).replace(".unity", ".sorted.unity"); | |
if sortArgs.output != None and sortArgs.output != "": | |
output = sortArgs.output; | |
if os.path.exists(sortArgs.input): | |
OriginalHandle = None | |
IDAndOffset = {} | |
IDAndLength = {} | |
LastID = "" | |
with open(sortArgs.input, 'r') as OriginalHandle: | |
OriginalPos = OriginalHandle.tell() | |
OriginalLine = OriginalHandle.readline() | |
Preamble = "" | |
while OriginalLine: | |
if OriginalLine.startswith('--- !u!'): | |
if LastID != "": | |
NewLength = OriginalPos - IDAndOffset[LastID] | |
# print("Cleaning up last tag " + LastID + " with total length " + str(NewLength) + "\n") | |
IDAndLength[LastID] = NewLength | |
NewID = OriginalLine.replace('--- !u!', '').replace(' &', '+') | |
NewID = NewID[0:NewID.find(' ')] | |
# print("Found line \"" + OriginalLine + "\" with ID " + NewID + " at offset " + str(OriginalPos) + "\n"); | |
IDAndOffset[NewID] = OriginalPos | |
LastID = NewID | |
elif len(IDAndOffset) == 0: | |
Preamble += OriginalLine | |
OriginalPos = OriginalHandle.tell() | |
OriginalLine = OriginalHandle.readline() | |
if LastID != "": | |
NewLength = OriginalPos - IDAndOffset[LastID] | |
IDAndLength[LastID] = NewLength | |
with open(output, 'w') as NewHandle: | |
NewHandle.write(Preamble) | |
for currentKey in sorted(IDAndOffset): | |
ToReadOffset = IDAndOffset[currentKey] | |
ToReadLength = IDAndLength[currentKey] | |
OriginalHandle.seek(ToReadOffset) | |
ToWriteString = OriginalHandle.read(ToReadLength) | |
NewHandle.write(ToWriteString) | |
# print("Attempting to write " + str(ToReadLength) + " from offset " + str(ToReadOffset) + ": \n" + ToWriteString) | |
else: | |
print("Input file (" + sortArgs.input + ") does not exist.") | |
sys.exit(1) | |
sys.exit(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment