windows本地使用tiddlywiki的一种方案

tiddlywiki是一款优秀轻便的个人wiki。

一种使用方法

  • 单独使用一个浏览器主要用于书写wiki,设置默认下载路径为wiki的存放路径。

  • 将wiki直接保存为一个浏览器书签。

  • 解决保存后,将最新内容版更新为原始wiki名称(书签保存的wiki名称),并备份

    浏览器下载后,最新的文件会被重命名为xxx(1).html, xxx(2).html,..., xxx(n).html

    • 通过一个python脚本实现,创建windows后台任务,每隔数分钟执行一次
    • 创建windows执行python的定时任务
    • 自动将最新文件(最新一次浏览器重命名的文件)重命名为原始文件名,并进行备份的脚本
import os
import re
import time
import shutil
import logging
from operator import itemgetter
from pathlib import Path

class Logger:
    def __init__(self, file, dir, level=logging.DEBUG):
        self.logger = logging.getLogger()
        self.logger.setLevel(logging.INFO)
        fmt = logging.Formatter('[%(asctime)s][%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S')
        # 设置CMD日志
        sh = logging.StreamHandler()
        sh.setFormatter(fmt)
        sh.setLevel(level)
        # 设置文件日志
        log_path = os.path.join(dir,'log')
        if os.path.exists(log_path):
            shutil.rmtree(log_path)
        os.mkdir(log_path)
        fh = logging.FileHandler(os.path.join(log_path, file))
        fh.setFormatter(fmt)
        fh.setLevel(level)

        self.logger.addHandler(sh)
        self.logger.addHandler(fh)

    def info(self, message):
        self.logger.info(message)

    def warn(self, message):
        self.logger.warn(message)

    def error(self, message):
        self.logger.error(message)

class CurDirFileOp:
    def __init__(self, rootDir, suffix):
        self.allFile = self.listAllFiles(rootDir)
        self.suffixFile = self.getSuffixFile(self.allFile, suffix)

    def listAllFiles(self, rootDir):
        _files = []
        list = os.listdir(rootDir)  # 列出文件夹下所有的目录与文件
        for i in range(0, len(list)):
            path = os.path.join(rootDir, list[i])
            if os.path.isdir(path):
                _files.extend(self.listAllFiles(path))
            if os.path.isfile(path):
                _files.append(path)
        return _files

    def getSuffixFile(self, allFile, suffix):
        _files = []
        lenth = len(suffix)
        if lenth is 0:
            return _files
        for file in allFile:
            if file[-lenth:] != suffix or os.path.isdir(file):
                continue  # 过滤非目标文件
            _files.append(file)
        return _files

    def getSonDir(self, rootDir, sonDirName):
        path = os.path.join(rootDir, sonDirName)
        if os.path.exists(path) is False:
            os.makedirs(path)
        return path

    def genNewFileName(self, fileNameIn, addStr):
        '''
        在后缀前添加字符串为新文件名
        '''
        nameList = re.split(r'([.])', fileNameIn)
        newName = nameList[0] + '-' + str(addStr) + str(nameList[1]) + str(nameList[2])
        return newName

class WikiOp:
    def __init__(self):
        self.wikiDir = os.path.abspath('.')
        self.fo = CurDirFileOp(self.wikiDir, 'html')
        self.htmlFile = self.fo.suffixFile
        self.backDir = self.fo.getSonDir(self.wikiDir, 'back')
        self.locTime = time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())

    def getWikiFile(self):
        '''
        'D:\\working\\tools\\cornfield\\tiddlywiki\\123': 
            [
                {'index': 0, 'fileName': 'D:\\working\\tools\\cornfield\\tiddlywiki\\123.html'}
            ],
        'D:\\working\\tools\\cornfield\\tiddlywiki\\mywiki': 
            [
                {'index': 10, 'fileName': 'D:\\working\\tools\\cornfield\\tiddlywiki\\mywiki(10).html'}, 
                {'index': 2, 'fileName': 'D:\\working\\tools\\cornfield\\tiddlywiki\\mywiki(2).html'}, 
                {'index': 3, 'fileName': 'D:\\working\\tools\\cornfield\\tiddlywiki\\mywiki(3).html'}, 
                {'index': 4, 'fileName': 'D:\\working\\tools\\cornfield\\tiddlywiki\\mywiki(4).html'}, 
                {'index': 5, 'fileName': 'D:\\working\\tools\\cornfield\\tiddlywiki\\mywiki(5).html'}, 
                {'index': 6, 'fileName': 'D:\\working\\tools\\cornfield\\tiddlywiki\\mywiki(6).html'}, 
                {'index': 7, 'fileName': 'D:\\working\\tools\\cornfield\\tiddlywiki\\mywiki(7).html'}, 
                {'index': 8, 'fileName': 'D:\\working\\tools\\cornfield\\tiddlywiki\\mywiki(8).html'}, 
                {'index': 9, 'fileName': 'D:\\working\\tools\\cornfield\\tiddlywiki\\mywiki(9).html'}, 
                {'index': 0, 'fileName': 'D:\\working\\tools\\cornfield\\tiddlywiki\\mywiki.html'}
            ]
        }
        '''
        allWikiDic = {}
        for file in self.htmlFile:
            if self.backDir in file:
                continue
            fileName = re.split(r'([().])', file)
            if len(fileName) is 7:
                index = int(fileName[2])
            elif len(fileName) is 3:
                index = 0
            else:
                continue
            itemKey = fileName[0]
            singleDict = {}
            singleDict["index"] = index
            singleDict['fileName'] = file
            if itemKey not in allWikiDic:
                allWikiDic[itemKey] = []

            allWikiDic[itemKey].append(singleDict)

        return allWikiDic

    def delBracketsOfBrowserRename(self, fileNameIn):
        nameList = re.split(r'[()]', fileNameIn)
        newName = nameList[0] + nameList[-1]
        return newName

    def backOldAndRnameNewWiki(self):
        wikiDic = self.getWikiFile()
        for item in wikiDic:
            allFile = self.fo.listAllFiles(self.wikiDir)
            wikiList = wikiDic[item]
            wikiList = sorted(wikiList,key = itemgetter('index'),reverse = True)
            if len(wikiList) is 1:
                if  wikiList[0]['fileName'].find("(") is -1:  # 跳过 不需要修改的
                    continue

            for idx in range(1, len(wikiList)): # backUp
                fileName = wikiList[idx]['fileName']
                newName = self.fo.genNewFileName(fileName, self.locTime)
                log.info("%s rename to: %s" %(fileName, newName))
                os.rename(fileName, newName)
                log.info("%s move to: %s" %(newName, self.backDir))
                shutil.move(newName, self.backDir)
            if len(wikiList) is not 0:
                fileName = wikiList[0]['fileName']
                newName = self.delBracketsOfBrowserRename(fileName)
                log.info("%s rename to: %s" %(fileName, newName))
                os.rename(fileName, newName)

if __name__ == "__main__":
    global dirHome, log
    dirHome = os.path.split(os.path.realpath(__file__))[0]
    os.chdir(dirHome)
    log = Logger('wikiback.log', dirHome, logging.INFO)
    wiki = WikiOp()
    wiki.backOldAndRnameNewWiki()
    log.info("-------------------------------back and rename ok!--------------------------------")

你可能感兴趣的:(windows本地使用tiddlywiki的一种方案)