- 帖子
- 52
- 精华
- 0
- 积分
- 207
- 阅读权限
- 30
- 注册时间
- 2016-1-15
- 最后登录
- 2016-12-17
|
本帖最后由 manhong2112 于 2016-10-21 17:32 编辑
原本想弄個筆記本, 然後架個站自用...然後寫着寫着寫成了vcs(算嗎?算吧)......
話說混亂到自己都看不太下去了XDDD
EDIT: 換成if-else...感覺不想再看到python的lambda了....
EDIT: 大改了一下, 和把index的rollback功能刪了- import hashlib
- import os
- import json
- import datetime
- import time
- dataLoc = "data"
- class Enitiy(object):
- def __init__(self, name, dtype, hashcode, history):
- self.name = name
- self.dtype = dtype
- self.hashcode = hashcode
- self.history = history
- class Index(Enitiy):
- def __init__(self, name, jsons=None, hashcode=None):
- self.name = name
- self.index = dict()
- if jsons is not None:
- for i in jsons["index"]:
- if i["type"] == "Index":
- self.index[i["name"]] = Index(
- i["name"],
- json.loads(read(i["hashcode"])),
- i["hashcode"])
- else:
- self.index[i["name"]] = Enitiy(
- i["name"],
- i["type"],
- i["hashcode"],
- i["history"] if "history" in i else dict())
- super().__init__(name, "Index", hashcode, None)
- def __str__(self):
- return str(self.index)
- def __getitem__(self, k):
- return self.index[k]
- def __setitem__(self, k, v):
- self.index[k] = v
- def __contains__(self, item):
- return item in self.index
- def __len__(self):
- return len(self.index)
- def items(self):
- return self.index.items()
- def dumpJsons(self):
- result = dict()
- result["index"] = []
- result["name"] = self.name
- for k, v in self.index.items():
- obj = dict()
- obj["name"], obj["type"], obj["hashcode"], obj["history"] = v.name, v.dtype, v.hashcode, v.history
- result["index"].append(obj)
- return json.dumps(result)
- _open = open
- def open(hashcode, type="w+"):
- path = getPath(hashcode)
- os.makedirs(os.path.dirname(path), exist_ok=True)
- if os.path.isfile(path):
- type = "r+"
- else:
- type = "w"
- return _open(path, type, encoding="UTF-8")
- def getPath(hashcode):
- return os.path.join(dataLoc, hashcode[:2], hashcode)
- def hash(str):
- return hashlib.sha1(str).hexdigest()
- def hashStr(str):
- return hash(str.encode("utf-8"))
- def hashFile(name, content):
- return hash((name + "|" + content).encode("utf-8"))
- def read(hashcode):
- with open(hashcode) as f:
- return f.read()
- def init():
- root = None
- path = getPath("root")
- name = "/"
- if not os.path.isfile(path):
- root = Index(name)
- root_json = root.dumpJsons()
- hashcode = hashFile(name, root_json)
- with open(hashcode) as f:
- f.write(root_json)
- with open("root") as f:
- f.write(json.dumps({"hashcode": hashcode, "name": name, "type": "Index"}))
- else:
- with open("root") as f:
- accessPt = json.loads(f.read())
- hashcode = accessPt["hashcode"]
- with open(hashcode) as f:
- root = Index(name, json.loads(f.read()), hashcode)
- return [root]
- def end(indexStack):
- root = indexStack[0]
- date = datetime.datetime.now().strftime("%Y/%m/%d-%H:%M:%S")
- name = "/"
- content = root.dumpJsons()
- hashcode = hashFile(name, content)
- with open(hashcode) as f:
- f.write(content)
- with open("root") as f:
- accessPt = json.loads(f.read())
- f.seek(0)
- accessPt["hashcode"] = hashcode
- f.write(json.dumps(accessPt))
- f.truncate()
- helpCmd = {
- "update": ["Usage>> update <name> <type> <content>",
- "Usage>> Update or create a file"],
- "rollback": ["Usage>> rollback <name> <id>",
- "Usage>> Rollback to the specified id"],
- "ls": ["Usage>> ls [name]",
- "Usage>> list all file in current dir or specified dir"],
- "cd": ["Usage>> cd <dir|'..'>",
- "Usage>> cd to specified dir"],
- "mkdir": ["Usage>> mkdir <dir>",
- "Usage>> create a new dir at current dir"],
- "read": ["Usage>> read <name>",
- "Usage>> read the content of specified file"],
- "history": ["Usage>> history <name>",
- "Usage>> List modifiy history of specified file"],
- "help": ["Usage>> <cmd>", "Usage>> Print the usage of cmd",
- "Usage>> all cmd[update, rollback, ls, cd, mkdir, read, history, help]"]
- }
- mainCmd = {"update", "rollback", "ls", "cd",
- "mkdir", "read", "history", "help", }
- def update(indexStack, name, dtype, content):
- index = indexStack[-1]
- date = datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S")
- dateid = hashStr(date)[:6]
- entity_hashcode = hashFile(name, content)
- with open(entity_hashcode) as f:
- f.write(content)
- if name not in index:
- if dtype == "Index":
- index[name] = Index(name, hashcode=entity_hashcode)
- else:
- index[name] = Enitiy(name, dtype, entity_hashcode, dict())
- else:
- entity = index[name]
- entity.history[dateid] = (date, entity.hashcode)
- entity.hashcode = entity_hashcode
- def rollback(indexStack, name, datetimeid):
- """
- indexStack
- name = file/dir name
- datetimeid = date
- """
- index = indexStack[-1]
- assert type(index[name]) is not Index
- history = index[name].history
- assert datetimeid in history
- with open(history[datetimeid][1]) as f:
- update(indexStack, name, index[name].dtype, f.read())
- def ls(indexStack, name=None):
- if name is not None:
- index = Index(name, json.loads(read(indexStack[-1][name].hashcode)))
- else:
- index = indexStack[-1]
- assert type(index) is Index
- return index.name, sorted([(e.name, e.dtype) for _, e in index.items()])
-
- def cd(indexStack, name):
- """
- indexStack
- name = file/dir name
- """
- assert type(indexStack) is list
- assert type(name) is str
- if name == "..":
- indexStack.pop()
- else:
- index = indexStack[-1]
- assert type(index[name]) is Index
- indexStack.append(index[name])
- def getHistory(indexStack, name):
- """
- indexStack
- name = file name
- """
- assert type(indexStack) is list
- assert type(name) is str
- index = indexStack[-1]
- assert type(index[name]) is not Index
- return index[name].history
- def mkdir(indexStack, name):
- assert name not in indexStack[-1]
- update(indexStack, name, "Index", Index(name).dumpJsons())
- if __name__ == '__main__':
- indexStack = init()
- try:
- while True:
- cmd = input("/".join([i.name for i in indexStack]) + ">> ").split(" ")
- args = cmd[1:] if len(cmd) > 1 else []
- if cmd[0] in mainCmd:
- if cmd[0] == "update":
- update(indexStack, *args)
- elif cmd[0] == "rollback":
- rollback(indexStack, args[0], args[1])
- elif cmd[0] == "ls":
- if len(args) == 1:
- i = ls(indexStack, *args)
- else:
- i = ls(indexStack)
- print(i[0] + " :"),
- print("\n".join(["\t" + n + " | " + t for n, t in i[1]]))
- elif cmd[0] == "cd":
- cd(indexStack, *args)
- elif cmd[0] == "mkdir":
- if len(args) != 1:
- print("E>")
- else:
- mkdir(indexStack, args[0])
- elif cmd[0] == "read":
- if len(args) != 1:
- print("E>")
- else:
- print(read(indexStack[-1][args[0]].hashcode)),
- elif cmd[0] == "history":
- if len(args) == 1:
- history = getHistory(indexStack, args[0])
- print(args[0] + " :")
- print("id\t|date")
- print("\n".join(
- ["{}\t|{}".format(x[0], x[1]) for x in
- sorted([(dateid, v[0]) for dateid, v in history.items()], key=lambda x: x[1])]))
- else:
- print("E>")
- elif cmd[0] == "help":
- exit = False
- while not exit:
- cmd = input("Help>> ")
- if cmd == "exit" or cmd == "quit":
- exit = True
- elif cmd in helpCmd:
- list(map(lambda x: print(x), helpCmd[cmd]))
- else:
- print("E> Invalid command")
- elif cmd[0] == "exit" or cmd[0] == "quit":
- break
- else:
- print("E> Invalid command")
- except Exception:
- raise
- finally:
- end(indexStack)
复制代码 |
|