Advertisement
Guest User

c3mm.py

a guest
Oct 1st, 2016
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.78 KB | None | 0 0
  1. # coding: utf8
  2. # Cossacks Mod manager version 1.2.1
  3. # Require python 3.5 to work: https://python.org/dowloads
  4. import sys, os
  5.  
  6. MOD_PATH = "mod/"
  7. CONFIG_PATH = "c3mm/"
  8. COPY_PATH = CONFIG_PATH + "copy/"
  9. BCKUP_PATH = CONFIG_PATH + "bckup/"
  10.  
  11. INI_PATH = CONFIG_PATH + "c3mm.ini"
  12. FILE_PATH = CONFIG_PATH + "file.ini"
  13.  
  14. ldir = [MOD_PATH, CONFIG_PATH, COPY_PATH, BCKUP_PATH]
  15.  
  16. for dir in ldir:
  17.     try:
  18.         os.mkdir(dir)
  19.     except:
  20.         pass
  21.  
  22. def olderversionthan(a, b):
  23.     a = a.split('.')
  24.     b = b.split('.')
  25.     while len(a) > len(b):
  26.         b.append('0')
  27.     while len(a) < len(b):
  28.         a.append('0')
  29.     for _a, _b in zip(a, b):
  30.         if _a < _b:
  31.             return True
  32.         elif _a > _b:
  33.             return False
  34.     return False
  35.  
  36. def loadmodlist():
  37.     try:
  38.         open(INI_PATH, "r")
  39.     except:
  40.         open(INI_PATH, "w").close()
  41.     data = {}
  42.     for name, version in [line.split(" version ") for line in open(INI_PATH, "r").read().split("\n") if line != ""]:
  43.         data[name] = version
  44.     return data
  45.  
  46. def savemodlist(modlist):
  47.     data = ""
  48.     for key in modlist:
  49.         data += key + " version " + modlist[key] + "\n"
  50.  
  51.     open(INI_PATH, "w").write(data)
  52.  
  53. def loadfilelist():
  54.     try:
  55.         open(FILE_PATH, "r")
  56.     except:
  57.         open(FILE_PATH, "w").close()
  58.  
  59.     data = {}
  60.     for line in open(FILE_PATH).read().split('\n'):
  61.         info = line.split(',')
  62.         data[info[0]] = info[1:]
  63.     return data
  64.  
  65. def savefilelist(filelist):
  66.     data = ""
  67.     for file in filelist:
  68.         if file == '' or filelist[file] == []:
  69.             continue
  70.         data += file
  71.         for mod in filelist[file]:
  72.             data += "," + mod
  73.         data += '\n'
  74.     open(FILE_PATH, "w").write(data)
  75.  
  76. def main(argv):
  77.  
  78.     modlist = loadmodlist()
  79.     filelist = loadfilelist()
  80.  
  81.     bad = checkMod(filelist)
  82.     for mod in bad:
  83.         print("Uninstall", mod, "version", modlist[mod])
  84.         uninstall({'name':mod}, modlist[mod], filelist, modlist)
  85.  
  86.     if len (argv) == 1:
  87.         printhelp()
  88.         return
  89.  
  90.     if argv[1] == "install":
  91.         if len(argv) < 2:
  92.             mod = input("Please type name of mod file: ")
  93.         else:
  94.             mod = argv[2]
  95.  
  96.         mod = MOD_PATH + mod
  97.         mod = loadmoddata(mod)
  98.  
  99.         print("Install", mod["name"], "version", mod["version"])
  100.         install(mod, filelist, modlist)
  101.  
  102.         mkuninstall(mod)
  103.  
  104.     elif argv[1] == "uninstall":
  105.         if len(argv) < 2:
  106.             mod = input("Please type name of mod file: ")
  107.         else:
  108.             mod = argv[2]
  109.  
  110.         mod = MOD_PATH + mod
  111.         mod = loadmoddata(mod)
  112.  
  113.         if not mod["name"] in modlist or modlist[mod["name"]] != mod["version"]:
  114.             print(mod["name"], "version", mod["version"], "doesn't exist, impossible to uninstall it.")
  115.             exit()
  116.  
  117.         print("Unistall", mod["name"], "version", modlist[mod["name"]])
  118.         uninstall(mod, modlist[mod["name"]], filelist, modlist)
  119.  
  120.     elif argv[1] == "help":
  121.         printhelp ()
  122.  
  123.     else:
  124.         print("Unknow command", argv[1])
  125.         printhelp()
  126.  
  127.     savemodlist(modlist)
  128.     savefilelist(filelist)
  129.  
  130. def checkMod(fileData):#dic of (file:list of mod)
  131.     bad = []
  132.     for file in fileData:
  133.         if file == '':
  134.             continue
  135.         if open(file, 'r').read() != open(COPY_PATH + file, 'r').read():
  136.             print("File", file, "has been modify.")
  137.             for mod in fileData[file]:
  138.                 if not mod in bad:
  139.                     print(mod, "will be uninstall")
  140.                     bad.append(mod)
  141.     return bad
  142.  
  143. def install(mod, filelist, modlist, uninstall=False):
  144.     for file in mod["files"]:
  145.         if not apply(mod["files"][file], file):
  146.             print("Fatal error")
  147.             return
  148.         else:
  149.             if not uninstall:
  150.  
  151.                 if not mod["name"] in modlist:
  152.                     modlist[mod["name"]] = mod["version"]
  153.                 elif modlist[mod["name"]] == mod["version"]:
  154.                     print(mod["name"], "version", mod["version"], "already installed!")
  155.                     exit()
  156.                 elif olderversionthan(modlist[mod["name"]], mod["version"]):
  157.                     print("Unistall", mod["name"], "version", modlist[mod["name"]])
  158.                     uninstall(mod, modlist[mod["name"]], filelist) 
  159.                     modlist[mod["name"]] = mod["version"]
  160.                 elif olderversionthan(mod["version"], modlist[mod["name"]]) :
  161.                     print(mod["name"], "version", modlist[mod["name"]], " is already installed. Are you sure to install an older version?", "(" + mod["version"] + ")")
  162.                     choice = input("yes/no:")
  163.                     if choice == "yes":
  164.                         print("Unistall", mod["name"], "version", modlist[mod["name"]])
  165.                         uninstall(mod, modlist[mod["name"]], filelist) 
  166.                         modlist[mod["name"]] = mod["version"]
  167.  
  168.                 if not file in filelist:
  169.                     filelist[file] = []
  170.                 if not mod['name'] in filelist[file]:
  171.                     filelist[file].append(mod['name'])
  172.  
  173.         print("Patching of", file,  "succed!")
  174.         copy(file)
  175.  
  176. def uninstall(mod, oldversion, filelist, modlist):
  177.     _uninstall = loadmoddata(CONFIG_PATH + mod["name"] + " " + oldversion + " uninstall")
  178.     for file in filelist:
  179.         if mod["name"]in filelist[file]:
  180.             filelist[file].remove(mod["name"])
  181.     install(_uninstall, filelist, modlist, True)
  182.     del modlist[mod["name"]]
  183.  
  184. def copy(path):
  185.     mkpath(COPY_PATH + path)
  186.     open(COPY_PATH + path, "w").write(open(path, "r").read())
  187.  
  188. def backup(path):
  189.     mkpath(BCKUP_PATH + path)
  190.     try:
  191.         try:
  192.             open(BCKUP_PATH + path, "r")
  193.             print("A backup of", path, "already exist")
  194.         except:
  195.             open(BCKUP_PATH + path, "w").write(open(path, "r").read())
  196.             print("Backup of", path, "suceed!")
  197.         return True
  198.     except:
  199.         print("Impossible to write in", path)
  200.         return False
  201.  
  202. def apply(instruction, path):
  203.  
  204.     if not backup (path):
  205.         return False
  206.     try:
  207.         txt = open(path, "r").read()
  208.     except:
  209.         print("File", path, "don't exist or you havn't access to it.")
  210.         return
  211.  
  212.     for old, new in instruction:
  213.         if not old in txt:
  214.             print("Warning! No match with'", old, "' in", path)
  215.         txt = txt.replace(old, new)
  216.  
  217.     try:
  218.         open(path, "w").write(txt)
  219.     except:
  220.         print("Impossible to write in", path)
  221.         return False
  222.  
  223.     return True
  224.  
  225. def printhelp():
  226.     print("Cossacks 3 (text)Mod manager version 1.2.0\npython c3mm.py [instruction] [options]\n\tInstruction:\n\tinstall + path : install a cossacks3 mod file.\n\tuninstall + path : uninstall a cossacks3 mod file")
  227.  
  228. def loadmoddata(path):
  229.     info, mod = open(path, "r").read().split('\n', 1)
  230.     name, version = info.split(" version ")
  231.  
  232.     data = {}
  233.     data["name"] = name
  234.     data["version"] = version
  235.  
  236.     data["files"] = {}
  237.     for file in mod.split("*PATH*"):
  238.         if file == "":
  239.             continue
  240.         path, instruction = file.split("\n", 1)
  241.         instruction = [(old, new) for old, new in [line.split("*REPLACE*") for line in instruction.split("*END*") if line != ""]]
  242.         data["files"][path] = instruction
  243.  
  244.     return data
  245.  
  246. def mkuninstall(mod):
  247.     data = ""
  248.     data += mod["name"] + " version " + mod["version"] + " cleaner\n"
  249.     for file in mod["files"]:
  250.         data += "*PATH*" + file + "\n"
  251.         for old, new in mod["files"][file]:
  252.             data += new + "*REPLACE*" + old + "*END*"
  253.     open(CONFIG_PATH + mod["name"] + " " + mod["version"] + " uninstall", "w").write(data)
  254.  
  255. def mkpath(path):
  256.     rpath = ""
  257.     for dir in path.split("/")[:-1]:
  258.         rpath += dir + '/'
  259.         try:
  260.             os.mkdir(rpath)
  261.         except:
  262.             pass
  263. if __name__ == "__main__":
  264.     main(sys.argv)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement