bpo-25522: IDLE "Save As" warnings

Give a warning when attempting to save a file that shadows a module
in the standard library.
This commit is contained in:
Zackery Spytz 2019-11-04 17:36:32 -07:00
parent 1726909094
commit 6cafdc8ff8
2 changed files with 46 additions and 2 deletions

View File

@ -104,6 +104,21 @@ def coding_spec(data):
return name return name
def libmodules():
libdir = os.path.dirname(os.path.dirname(__file__))
for entry in os.listdir(libdir):
if entry.endswith(".py"):
yield entry[:-3]
fullpath = os.path.join(libdir, entry)
if (os.path.isdir(fullpath) and
os.path.exists(os.path.join(fullpath, "__init__.py"))):
yield entry
islibmodule = frozenset(libmodules()).__contains__
isbinmodule = frozenset(sys.builtin_module_names).__contains__
class IOBinding: class IOBinding:
# One instance per editor Window so methods know which to save, close. # One instance per editor Window so methods know which to save, close.
# Open returns focus to self.editwin if aborted. # Open returns focus to self.editwin if aborted.
@ -512,6 +527,11 @@ class IOBinding:
pwd = "" pwd = ""
return pwd, "" return pwd, ""
def warnbadfilename(self, msg):
return tkMessageBox.askokcancel(
title="Bad File Name", message=msg,
default=tkMessageBox.CANCEL, parent=self.text)
def asksavefile(self): def asksavefile(self):
dir, base = self.defaultfilename("save") dir, base = self.defaultfilename("save")
if not self.savedialog: if not self.savedialog:
@ -519,8 +539,30 @@ class IOBinding:
parent=self.text, parent=self.text,
filetypes=self.filetypes, filetypes=self.filetypes,
defaultextension=self.defaultextension) defaultextension=self.defaultextension)
filename = self.savedialog.show(initialdir=dir, initialfile=base) go = False
return filename while not go:
filename = self.savedialog.show(initialdir=dir, initialfile=base)
if not filename:
return ''
name = os.path.splitext(os.path.basename(filename))[0]
stdlibmsg = ("Neither you nor python will be able to import the "
"stdlib module.")
if islibmodule(name):
go = self.warnbadfilename(
f"This name matches a stdlib name in the Lib "
f"directory.\n{stdlibmsg}")
elif isbinmodule(name):
go = self.warnbadfilename(
f"This name matches a builtin stdlib name.\n"
f"{stdlibmsg}")
elif not name.isidentifier():
go = self.warnbadfilename(
"This name is not a valid identifier.\n"
"You will not be able to import this file.")
else:
go = True
if go:
return filename
def updaterecentfileslist(self,filename): def updaterecentfileslist(self,filename):
"Update recent file list on all editor windows" "Update recent file list on all editor windows"

View File

@ -0,0 +1,2 @@
IDLE now warns when a user attempts to save a file that shadows a module in
the standard library.