Formatted python code using flake8 w/ default configuration

This commit is contained in:
coder 2020-04-26 00:11:36 +10:00
parent 41d674e6b1
commit 0d2d6c216e
5 changed files with 155 additions and 125 deletions

View File

@ -8,6 +8,7 @@ else:
PathSlash = '/'
FileProtocol = "file:" + 2*PathSlash
def ConvertToStandardPathFormat(Path):
""" Example,
Input: '"file:///some/path/somefile.extension"
@ -18,6 +19,7 @@ def ConvertToStandardPathFormat(Path):
Path = Path[len(FileProtocol):]
return Path
def GetTextAfter(Text, ReadlinesTextFile):
for Lines in range(len(ReadlinesTextFile)):
Line = ReadlinesTextFile[Lines].strip('\n')
@ -25,18 +27,21 @@ def GetTextAfter(Text, ReadlinesTextFile):
return Line[len(Text):]
return ''
def SingleQuoteString(String):
if len(String) > 0:
if String[0] != '\'' or String[-1] != '\'':
String = '\'' + String + '\''
return String
def DoubleQuoteString(String):
if len(String) > 0:
if String[0] != '"' or String[-1] != '"':
String = '"' + String + '"'
return String
def ListIntoString(List, QuoteItems=0, Seprator=' '):
if QuoteItems == 2:
for i in range(len(List)):
@ -49,36 +54,42 @@ def ListIntoString(List, QuoteItems=0, Seprator=' '):
Stringoflist = (Seprator).join(List)
return Stringoflist
# strip=0 => remove both ' & ", 1 => remove ', 2 => remove "
def UnquoteString(String, strip=0):
while True:
if (
strip != 2
and String.startswith('"')
and String.endswith('"')):
strip != 2 and
String.startswith('"') and
String.endswith('"')
):
String = String.strip('"')
elif (
strip != 1
and String.startswith("'")
and String.endswith("'")):
and String.endswith("'")
):
String = String.strip("'")
else:
break
return String
def StandardVariableName(Variable):
Variable = Variable.casefold()
Variable = Variable.replace('_', '').replace(' ', '')
return Variable
#def DictionaryToJsonStr(Dict, BaseIndentation=0):
#BI = '\t'*BaseIndentation
#JsonStr = BI+'{\n'
#for k, v in Dict.items():
#JsonStr += BI+'\t"'+k+'" : "'+v+'",\n'
#JsonStr = JsonStr[:-2]
#JsonStr += '\n'+BI+'}'
#return JsonStr
"""
def DictionaryToJsonStr(Dict, BaseIndentation=0):
BI = '\t'*BaseIndentation
JsonStr = BI+'{\n'
for k, v in Dict.items():
JsonStr += BI+'\t"'+k+'" : "'+v+'",\n'
JsonStr = JsonStr[:-2]
JsonStr += '\n'+BI+'}'
return JsonStr
"""
def StringToKeyValuePair(String, Seprator):
SepratorAt = String.find(Seprator)
@ -89,14 +100,17 @@ def StringToKeyValuePair(String, Seprator):
else:
return "", String
def FormatStrForDictinary(String):
String = String.strip(" \n\r")
return UnquoteString(String)
def StrListToDictionary(
List,
Seprator = '=',
FormatFunction = FormatStrForDictinary):
Seprator='=',
FormatFunction=FormatStrForDictinary
):
Dictionary = {}
for i in List:
k, v = StringToKeyValuePair(i, Seprator)

View File

@ -2,6 +2,7 @@ from os.path import isfile as DoesFileExist
from .DataStructureManupulations import ConvertToStandardPathFormat
def ReadTextFile(FilePath):
FilePath = ConvertToStandardPathFormat(FilePath)
if DoesFileExist(FilePath) is True:
@ -12,10 +13,12 @@ def ReadTextFile(FilePath):
else:
return ''
def ReadlinesTextFile(FilePath):
String = ReadTextFile(FilePath)
return String.split('\n')
def WriteTextFiles(FilePath, Text):
if type(Text) != str:
Text = '\n'.join(Text)
@ -23,7 +26,8 @@ def WriteTextFiles(FilePath, Text):
File.write(Text)
File.close()
def WriteBinaryToFile(Filepath, Data):
File=open(Filepath, 'wb')
File = open(Filepath, 'wb')
File.write(Data)
File.close()

View File

@ -3,6 +3,6 @@ from urllib.request import urlopen
HttpsContext = ssl.create_default_context()
def Download(Url):
return urlopen(Url, context=HttpsContext).read()

View File

@ -1,11 +1,13 @@
import os
def CallFuncInDir(Directory, Function, *args, **kwArgs):
CurrentDir = os.getcwd()
os.chdir(Directory)
Function(*args, **kwArgs)
os.chdir(CurrentDir)
# return True if operation succesful and False if failed
def CreateDir(Directory):
if not os.path.isfile(Directory):

View File

@ -6,10 +6,6 @@ All sub-directories of bundles directory will be scanned for activity
bundles i.e. .xo files.
"""
""" FIXME: paths hard coded unix style & most likely will not work on winodws.
Use code written for IMM to handle it.
"""
import glob
import json
import os
@ -19,8 +15,6 @@ from urllib.parse import quote as strToHtmlFmt
import zipfile
from GeneralFunctions.DataStructureManupulations import (
GetTextAfter,
UnquoteString,
StrListToDictionary
)
from GeneralFunctions.InputOutput import (
@ -32,6 +26,12 @@ from GeneralFunctions.OS import (
CreateDir
)
""" FIXME: paths hard coded unix style & most likely will not work on winodws.
Use code written for IMM to handle it.
"""
class extractData:
def findInfoFiles(self, bundle):
@ -56,7 +56,7 @@ class extractData:
assert(CreateDir("js"))
def extractActivityInfo(self, infoFilePath, zipFile):
infoList, infoDict = [], {}
infoList = []
infoList = zipFile.read(
infoFilePath).decode("utf-8").split('\n')
return StrListToDictionary(infoList)
@ -85,9 +85,9 @@ class extractData:
if iconAbsolutePath in bundle.namelist():
icon = bundle.read(iconAbsolutePath)
iconPath = (
"icons/"+
"icons/" +
activityName
+".svg"
+ ".svg"
)
CallFuncInDir(
self.websiteDir,
@ -112,40 +112,43 @@ class extractData:
pathName = strToHtmlFmt(appInfo["name"], safe='')
html = (
'<!DOCTYPE html>\n<html>\n<head>\n<title>'+appInfo["name"]+
'<!DOCTYPE html>\n<html>\n<head>\n<title>' + appInfo["name"] +
'</title>\n<meta charset="utf-8"/>\n<link rel="stylesheet" '
'type="text/css" href="../css/main.css"/>\n</head>\n<body>\n'
'</body>\n<h1>'+appInfo["name"]+'</h1>\n<p><img src="'+
str(iconsDir+pathName+'.svg')+'"></img></p>\n<div id=summary>'
'<h2>Summary</h2>\n<p>'+appInfo["summary"]+
'</p>\n</div>\n<div id=description><h2>Description</h2>\n<p>'+
appInfo["description"]+'</p>\n</div>\n<div id=tags><h2>Tags'
'</body>\n<h1>' + appInfo["name"] + '</h1>\n<p><img src="' +
str(iconsDir + pathName + '.svg') + '"></img></p>\n'
'<div id=summary><h2>Summary</h2>\n<p>' + appInfo["summary"] +
'</p>\n</div>\n<div id=description><h2>Description</h2>\n<p>' +
appInfo["description"] + '</p>\n</div>\n<div id=tags><h2>Tags'
'</h2>\n<ul>\n'
)
for tag in appInfo["tags"]:
html += '<li>'+tag+'</li>\n'
html += '<li>' + tag + '</li>\n'
html += (
'</ul>\n</div>\n<a href="'+str(bundlesDir+pathName+'.xo')+
'</ul>\n</div>\n<a href="' +
str(bundlesDir + pathName + '.xo') +
'"><h2>Download<h2></a>\n</body>\n</html>'
)
WriteTextFiles("./app/"+appInfo["name"]+".html", html)
WriteTextFiles("./app/" + appInfo["name"] + ".html", html)
""" Only those which are specified in map will be added to index.
If an entry or value does not exist in infoJSON than emprty entry will
be created for it.
appends keys rather than replacing where mutiple map to same
"""
def generateIndex(self,
infoToIndexMap = {
"name" : ("name", str),
"summary" : ("summary", str),
"description" : ("description", str),
"tag" : ("tags", list),
"tags" : ("tags", list),
"categories" : ("tags", list),
"category" : ("tags", list)
}):
def generateIndex(
self,
infoToIndexMap={
"name": ("name", str),
"summary": ("summary", str),
"description": ("description", str),
"tag": ("tags", list),
"tags": ("tags", list),
"categories": ("tags", list),
"category": ("tags", list)
}
):
unexpectedInputError = (
"main.py generateIndex() : expect only str, list or tuple as "
"kwargs -> value[1] but found "
@ -186,7 +189,7 @@ class extractData:
# Create entry/key with empty value for keys not present
# in activty.info
for k ,v in i2IMap.items():
for k, v in i2IMap.items():
if v[0] not in indexDict:
if v[1] == str:
indexDict[v[0]] = ""
@ -197,7 +200,11 @@ class extractData:
sys.exit(1)
self.indexDictList.append(indexDict)
self.indexJs = "search.assignIndex("+json.dumps(self.indexDictList, indent=4)+")"
self.indexJs = (
"search.assignIndex(" +
json.dumps(self.indexDictList, indent=4) +
")"
)
def generateInfoJson(self):
self.infoJson = json.dumps(self.bundlesInfoList, indent=4)
@ -256,7 +263,7 @@ class extractData:
Eg. Html, icon and bundles are written while processing each bundle
"""
WriteTextFiles("info.json", self.infoJson)
WriteTextFiles("./js/index.js",self.indexJs)
WriteTextFiles("./js/index.js", self.indexJs)
WriteTextFiles(
"bundlesNotExactlyOneInfoFile.txt",
self.bundlesNotExactlyOneInfoFile
@ -265,6 +272,7 @@ class extractData:
WriteTextFiles("erroredBundles.txt", self.erroredBundles)
WriteTextFiles("iconErroredBundles.txt", self.iconErroredBundles)
def processArguments():
variables = {}
if len(sys.argv) == 3:
@ -282,9 +290,11 @@ def processArguments():
sys.exit(1)
return variables
def main():
variables = processArguments()
extractData(variables["bundlesDir"], variables["websiteDir"])
if __name__ == "__main__":
main();
main()