spitzip/module/main.py

125 lines
2.9 KiB
Python

import sys
import os
prochelper = mfp.require("prochelper")
prochelper.setLanguage("C")
eprint = mfp.require("printhelper").eprint
def getFlag(flags,flag):
if not flag in flags: return None
return flags[flag]
def getArchiveTool(archiveFile):
tool = "7z"
while True:
# Method 1: file command
try:
mimetype = prochelper.pcallStr(["file","-b","--mime-type","--uncompress",archiveFile])
if mimetype == "application/x-tar":
tool = "tar"
break
except subprocess.CalledProcessError as e:
eprint("Warning: 'file' exited with error " +str(e.returncode))
# Method 2: file extension
archiveFileSplit = archiveFile.rsplit(".",2)
if len(archiveFileSplit) < 2:
eprint("Warning: No file extension.")
break
if archiveFileSplit[-1].lower() == "tar":
tool = "tar"
break
if len(archiveFileSplit) > 2 and archiveFileSplit[-2].lower() == "tar":
tool = "tar"
break
break
return tool
def printHelp(exitCode):
eprint('''\
Syntax: "''' +sys.argv[0]+ '''" <action> <flags> <archive>
Available actions:
* help - Prints this help
* list - Outputs each file of archive as a json table
* extract - Copy a file/folder from the archive into another folder. -if= sets
the path to copy from the archive (DO NOT use wildcards!), -of= sets the output
folder. The output folder has to exist. Files are replaced without asking.
Universal flags:
* -tool= - Which tool to use for the archive. By default, the program guesses
the best tool for the job. Available: 7z, tar\
''')
sys.exit(exitCode)
def main():
args = sys.argv[1:]
if len(args) > 0:
action = args.pop(0)
else:
eprint("ERROR: No action given.\n")
printHelp(1)
flags = {}
index = 0
length = len(args)
while index < length:
arg = args[index]
if arg.startswith("-") and "=" in arg:
arg = arg[1:].split("=",1)
flags[arg[0]] = arg[1]
del args[index]
length -= 1
continue
index += 1
if length > 1:
eprint("ERROR: Too many, or malformed arguments.\n")
printHelp(1)
if length < 1:
eprint("ERROR: No archive file in arguments.\n")
printHelp(1)
archiveFile = args[0]
if not os.path.isfile(archiveFile):
eprint("ERROR: " +archiveFile+ " not found.")
printHelp(1)
if action == "help": printHelp(0)
tool = getFlag(flags,"tool")
if tool == None:
tool = getArchiveTool(archiveFile)
toolApi = mfp.require("tools/" +tool)
if action == "list":
import json
for apiFile in toolApi.action_list(archiveFile,flags):
print(json.dumps(apiFile))
return
if action == "extract":
if not "if" in flags:
eprint("ERROR: -if flag is not set.\n")
printHelp(1)
if not "of" in flags:
eprint("ERROR: -of flag is not set.\n")
printHelp(1)
if not os.path.isdir(flags["of"]):
eprint("ERROR: -of '" + str(flags["of"]) + "' is not a directory.")
sys.exit(1)
toolApi.action_extract(archiveFile,flags)
return
eprint("ERROR: Invalid action.\n")
printHelp()
sys.exit(1)