Skip to content

Instantly share code, notes, and snippets.

@KOLANICH
Created April 4, 2018 12:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KOLANICH/39e758930307d74f618ed70378342d08 to your computer and use it in GitHub Desktop.
Save KOLANICH/39e758930307d74f618ed70378342d08 to your computer and use it in GitHub Desktop.
This scriot will help you recover Notepad++ session from backup folder
__author__="KOLANICH"
__license__="Unlicense"
__copyright__=r"""
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <https://unlicense.org/>
"""
from pathlib import Path
from bs4 import BeautifulSoup, Tag
import typing
def parseFile(fn:Path):
try:
with fn.open("rb") as f:
t=f.read()
return BeautifulSoup(t, "xml")
except:
None
def langsToId_(items:typing.Container[BeautifulSoup]):
extLangMap={}
for lng in items:
if lng.has_attr("ext") and lng.has_attr("name") and lng["ext"] and lng["name"]:
for ext in lng["ext"].split(" "):
extLangMap[ext.lower()]=lng["name"]
return extLangMap
def extToLanguageIDMapping(langsXML:typing.Container[BeautifulSoup]):
return langsToId_(langsXML.select_one("Languages").select("Language"))
def extToUDLNameMapping(userDefineLang:BeautifulSoup):
return langsToId_(userDefineLang.select("UserLang"))
def languageIDToNameMapping(stylersXML:BeautifulSoup):
langNameMap={}
extLangMap={}
for lt in stylersXML.select_one("LexerStyles").select("LexerType"):
if lt.has_attr("name"):
if lt.has_attr("desc"):
langNameMap[lt["name"]]=lt["desc"]
if lt.has_attr("ext") and lt["ext"]:
for ext in lt["ext"].split(" "):
extLangMap[ext.lower()]=lt["name"]
return langNameMap, extLangMap
def getTypeToNameMap(nppDir:Path):
langsFile=nppDir/"langs.xml"
stylersFile=nppDir/"stylers.xml"
udlFile=nppDir/"userDefineLang.xml"
extLangMap=extToLanguageIDMapping(parseFile(langsFile))
langNameMap, extLangMap1=languageIDToNameMapping(parseFile(stylersFile))
extLangMap.update(extLangMap1)
extNameMap={k:langNameMap[v] for k, v in extLangMap.items() if v in langNameMap}
extNameMap.update(extToUDLNameMapping(parseFile(udlFile)))
return extNameMap
def recoverSession(mainView:BeautifulSoup, backupFiles:typing.Container[Path], extNameMap:typing.Mapping[str, str]):
present=set()
for f in mainView.select("File"):
present.add(Path(f["backupFilePath"]).absolute())
for f in (backupFiles - present):
#ft=mainView.new_tag("File")
ft=Tag(None, None, "File")
fn=f.name.split("@")[0]
ft["backupFilePath"]=str(f)
ft["filename"]=fn
ext=Path(fn).suffix[1:].lower()
#print(ext)
if ext in extNameMap:
ft["lang"]=extNameMap[ext]
mainView.append(ft)
def subtag(par, subName):
sub=par.select_one(subName)
if not sub:
sub=Tag(None, None, subName)
par.append(sub)
#print(subName, sub)
return sub
def doRecovery(nppDir:Path):
nppDir=Path(".")
sessFile=nppDir/"session.xml"
backupDir=nppDir/"backup"
rootElName="NotepadPlus"
if sessFile.exists():
sess=parseFile(sessFile)
else:
sess=BeautifulSoup("<"+rootElName+"/>", "xml")
sess=sess.select_one(rootElName)
mainView=subtag(subtag(sess, "Session"), "mainView")
backupFiles={p.absolute() for p in backupDir.glob("*")}
extNameMap=getTypeToNameMap(nppDir)
recoverSession(mainView, backupFiles, extNameMap)
with sessFile.open("wt", encoding="utf-8") as f:
f=f.write(str(sess))
if __name__=="__main__":
from plumbum import cli
class SessionRestorerCLI(cli.Application):
"""Restores session from files in Backup folder"""
def main(self, nppDir:cli.ExistingDirectory="."):
doRecovery(Path(nppDir))
SessionRestorerCLI.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment