##// END OF EJS Templates
prevent transient leaks of file handle by using new helper functions...
Dan Villiom Podlaski Christiansen -
r14168:135e2447 default
parent child Browse files
Show More
@@ -191,7 +191,7 b' class darcs_source(converter_source, com'
191 if rev != self.lastrev:
191 if rev != self.lastrev:
192 raise util.Abort(_('internal calling inconsistency'))
192 raise util.Abort(_('internal calling inconsistency'))
193 path = os.path.join(self.tmppath, name)
193 path = os.path.join(self.tmppath, name)
194 data = open(path, 'rb').read()
194 data = util.readfile(path)
195 mode = os.lstat(path).st_mode
195 mode = os.lstat(path).st_mode
196 mode = (mode & 0111) and 'x' or ''
196 mode = (mode & 0111) and 'x' or ''
197 return data, mode
197 return data, mode
@@ -1028,7 +1028,7 b' class svn_sink(converter_sink, commandli'
1028 os.unlink(filename)
1028 os.unlink(filename)
1029 except OSError:
1029 except OSError:
1030 pass
1030 pass
1031 self.wopener(filename, 'w').write(data)
1031 self.wopener.write(filename, data)
1032
1032
1033 if self.is_exec:
1033 if self.is_exec:
1034 was_exec = self.is_exec(self.wjoin(filename))
1034 was_exec = self.is_exec(self.wjoin(filename))
@@ -97,7 +97,7 b' def snapshot(ui, repo, files, node, tmpr'
97 if 'l' in fctx.flags():
97 if 'l' in fctx.flags():
98 wopener.symlink(data, wfn)
98 wopener.symlink(data, wfn)
99 else:
99 else:
100 wopener(wfn, 'w').write(data)
100 wopener.write(wfn, data)
101 if 'x' in fctx.flags():
101 if 'x' in fctx.flags():
102 util.set_flags(dest, False, True)
102 util.set_flags(dest, False, True)
103 if node is None:
103 if node is None:
@@ -234,7 +234,7 b' def sign(ui, repo, *revs, **opts):'
234
234
235 # write it
235 # write it
236 if opts['local']:
236 if opts['local']:
237 repo.opener("localsigs", "ab").write(sigmessage)
237 repo.opener.append("localsigs", sigmessage)
238 return
238 return
239
239
240 msigs = match.exact(repo.root, '', ['.hgsigs'])
240 msigs = match.exact(repo.root, '', ['.hgsigs'])
@@ -413,7 +413,7 b' def demo(ui, repo, *args, **opts):'
413 demoitems('keywordset', ui.configitems('keywordset'))
413 demoitems('keywordset', ui.configitems('keywordset'))
414 demoitems('keywordmaps', kwmaps.iteritems())
414 demoitems('keywordmaps', kwmaps.iteritems())
415 keywords = '$' + '$\n$'.join(sorted(kwmaps.keys())) + '$\n'
415 keywords = '$' + '$\n$'.join(sorted(kwmaps.keys())) + '$\n'
416 repo.wopener(fn, 'w').write(keywords)
416 repo.wopener.write(fn, keywords)
417 repo[None].add([fn])
417 repo[None].add([fn])
418 ui.note(_('\nkeywords written to %s:\n') % fn)
418 ui.note(_('\nkeywords written to %s:\n') % fn)
419 ui.note(keywords)
419 ui.note(keywords)
@@ -291,14 +291,14 b' class queue(object):'
291 elif l.strip():
291 elif l.strip():
292 self.ui.warn(_('malformated mq status line: %s\n') % entry)
292 self.ui.warn(_('malformated mq status line: %s\n') % entry)
293 # else we ignore empty lines
293 # else we ignore empty lines
294 lines = self.opener(self.status_path).read().splitlines()
294 lines = self.opener.read(self.status_path).splitlines()
295 return list(parselines(lines))
295 return list(parselines(lines))
296 return []
296 return []
297
297
298 @util.propertycache
298 @util.propertycache
299 def full_series(self):
299 def full_series(self):
300 if os.path.exists(self.join(self.series_path)):
300 if os.path.exists(self.join(self.series_path)):
301 return self.opener(self.series_path).read().splitlines()
301 return self.opener.read(self.series_path).splitlines()
302 return []
302 return []
303
303
304 @util.propertycache
304 @util.propertycache
@@ -412,7 +412,7 b' class queue(object):'
412 if self.active_guards is None:
412 if self.active_guards is None:
413 self.active_guards = []
413 self.active_guards = []
414 try:
414 try:
415 guards = self.opener(self.guards_path).read().split()
415 guards = self.opener.read(self.guards_path).split()
416 except IOError, err:
416 except IOError, err:
417 if err.errno != errno.ENOENT:
417 if err.errno != errno.ENOENT:
418 raise
418 raise
@@ -39,7 +39,7 b' class transplants(object):'
39 def read(self):
39 def read(self):
40 abspath = os.path.join(self.path, self.transplantfile)
40 abspath = os.path.join(self.path, self.transplantfile)
41 if self.transplantfile and os.path.exists(abspath):
41 if self.transplantfile and os.path.exists(abspath):
42 for line in self.opener(self.transplantfile).read().splitlines():
42 for line in self.opener.read(self.transplantfile).splitlines():
43 lnode, rnode = map(revlog.bin, line.split(':'))
43 lnode, rnode = map(revlog.bin, line.split(':'))
44 list = self.transplants.setdefault(rnode, [])
44 list = self.transplants.setdefault(rnode, [])
45 list.append(transplantentry(lnode, rnode))
45 list.append(transplantentry(lnode, rnode))
@@ -318,7 +318,7 b' class transplanter(object):'
318 nodes = []
318 nodes = []
319 merges = []
319 merges = []
320 cur = nodes
320 cur = nodes
321 for line in self.opener('series').read().splitlines():
321 for line in self.opener.read('series').splitlines():
322 if line.startswith('# Merges'):
322 if line.startswith('# Merges'):
323 cur = merges
323 cur = merges
324 continue
324 continue
@@ -72,12 +72,12 b' def write(repo):'
72 refs = repo._bookmarks
72 refs = repo._bookmarks
73
73
74 try:
74 try:
75 bms = repo.opener('bookmarks').read()
75 bms = repo.opener.read('bookmarks')
76 except IOError, inst:
76 except IOError, inst:
77 if inst.errno != errno.ENOENT:
77 if inst.errno != errno.ENOENT:
78 raise
78 raise
79 bms = ''
79 bms = ''
80 repo.opener('undo.bookmarks', 'w').write(bms)
80 repo.opener.write('undo.bookmarks', bms)
81
81
82 if repo._bookmarkcurrent not in refs:
82 if repo._bookmarkcurrent not in refs:
83 setcurrent(repo, None)
83 setcurrent(repo, None)
@@ -91,7 +91,7 b' def logmessage(opts):'
91 if logfile == '-':
91 if logfile == '-':
92 message = sys.stdin.read()
92 message = sys.stdin.read()
93 else:
93 else:
94 message = open(logfile).read()
94 message = util.readfile(logfile)
95 except IOError, inst:
95 except IOError, inst:
96 raise util.Abort(_("can't read commit message '%s': %s") %
96 raise util.Abort(_("can't read commit message '%s': %s") %
97 (logfile, inst.strerror))
97 (logfile, inst.strerror))
@@ -1129,7 +1129,7 b" def debugcomplete(ui, cmd='', **opts):"
1129
1129
1130 def debugfsinfo(ui, path = "."):
1130 def debugfsinfo(ui, path = "."):
1131 """show information detected about current filesystem"""
1131 """show information detected about current filesystem"""
1132 open('.debugfsinfo', 'w').write('')
1132 util.writefile('.debugfsinfo', '')
1133 ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
1133 ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
1134 ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
1134 ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
1135 ui.write('case-sensitive: %s\n' % (util.checkcase('.debugfsinfo')
1135 ui.write('case-sensitive: %s\n' % (util.checkcase('.debugfsinfo')
@@ -2669,7 +2669,7 b' def import_(ui, repo, patch1, *patches, '
2669 raise util.Abort(_('no diffs found'))
2669 raise util.Abort(_('no diffs found'))
2670
2670
2671 if msgs:
2671 if msgs:
2672 repo.opener('last-message.txt', 'wb').write('\n* * *\n'.join(msgs))
2672 repo.opener.write('last-message.txt', '\n* * *\n'.join(msgs))
2673 finally:
2673 finally:
2674 release(lock, wlock)
2674 release(lock, wlock)
2675
2675
@@ -74,7 +74,7 b' class dirstate(object):'
74 @propertycache
74 @propertycache
75 def _branch(self):
75 def _branch(self):
76 try:
76 try:
77 return self._opener("branch").read().strip() or "default"
77 return self._opener.read("branch").strip() or "default"
78 except IOError:
78 except IOError:
79 return "default"
79 return "default"
80
80
@@ -220,13 +220,13 b' class dirstate(object):'
220 if branch in ['tip', '.', 'null']:
220 if branch in ['tip', '.', 'null']:
221 raise util.Abort(_('the name \'%s\' is reserved') % branch)
221 raise util.Abort(_('the name \'%s\' is reserved') % branch)
222 self._branch = encoding.fromlocal(branch)
222 self._branch = encoding.fromlocal(branch)
223 self._opener("branch", "w").write(self._branch + '\n')
223 self._opener.write("branch", self._branch + '\n')
224
224
225 def _read(self):
225 def _read(self):
226 self._map = {}
226 self._map = {}
227 self._copymap = {}
227 self._copymap = {}
228 try:
228 try:
229 st = self._opener("dirstate").read()
229 st = self._opener.read("dirstate")
230 except IOError, err:
230 except IOError, err:
231 if err.errno != errno.ENOENT:
231 if err.errno != errno.ENOENT:
232 raise
232 raise
@@ -113,14 +113,14 b' def _eoltype(data):'
113
113
114 def _matcheol(file, origfile):
114 def _matcheol(file, origfile):
115 "Convert EOL markers in a file to match origfile"
115 "Convert EOL markers in a file to match origfile"
116 tostyle = _eoltype(open(origfile, "rb").read())
116 tostyle = _eoltype(util.readfile(origfile))
117 if tostyle:
117 if tostyle:
118 data = open(file, "rb").read()
118 data = util.readfile(file)
119 style = _eoltype(data)
119 style = _eoltype(data)
120 if style:
120 if style:
121 newdata = data.replace(style, tostyle)
121 newdata = data.replace(style, tostyle)
122 if newdata != data:
122 if newdata != data:
123 open(file, "wb").write(newdata)
123 util.writefile(file, newdata)
124
124
125 def filemerge(repo, mynode, orig, fcd, fco, fca):
125 def filemerge(repo, mynode, orig, fcd, fco, fca):
126 """perform a 3-way merge in the working directory
126 """perform a 3-way merge in the working directory
@@ -8,6 +8,7 b''
8 from i18n import gettext, _
8 from i18n import gettext, _
9 import sys, os
9 import sys, os
10 import extensions
10 import extensions
11 import util
11
12
12
13
13 def moduledoc(file):
14 def moduledoc(file):
@@ -79,7 +80,7 b' def loaddoc(topic):'
79 break
80 break
80
81
81 path = os.path.join(docdir, topic + ".txt")
82 path = os.path.join(docdir, topic + ".txt")
82 doc = gettext(open(path).read())
83 doc = gettext(util.readfile(path))
83 for rewriter in helphooks.get(topic, []):
84 for rewriter in helphooks.get(topic, []):
84 doc = rewriter(topic, doc)
85 doc = rewriter(topic, doc)
85 return doc
86 return doc
@@ -137,14 +137,14 b' def share(ui, source, dest=None, update='
137
137
138 requirements = ''
138 requirements = ''
139 try:
139 try:
140 requirements = srcrepo.opener('requires').read()
140 requirements = srcrepo.opener.read('requires')
141 except IOError, inst:
141 except IOError, inst:
142 if inst.errno != errno.ENOENT:
142 if inst.errno != errno.ENOENT:
143 raise
143 raise
144
144
145 requirements += 'shared\n'
145 requirements += 'shared\n'
146 file(os.path.join(roothg, 'requires'), 'w').write(requirements)
146 util.writefile(os.path.join(roothg, 'requires'), requirements)
147 file(os.path.join(roothg, 'sharedpath'), 'w').write(sharedpath)
147 util.writefile(os.path.join(roothg, 'sharedpath'), sharedpath)
148
148
149 r = repository(ui, root)
149 r = repository(ui, root)
150
150
@@ -56,7 +56,8 b' class localrepository(repo.repository):'
56 if self.ui.configbool('format', 'dotencode', True):
56 if self.ui.configbool('format', 'dotencode', True):
57 requirements.append('dotencode')
57 requirements.append('dotencode')
58 # create an invalid changelog
58 # create an invalid changelog
59 self.opener("00changelog.i", "a").write(
59 self.opener.append(
60 "00changelog.i",
60 '\0\0\0\2' # represents revlogv2
61 '\0\0\0\2' # represents revlogv2
61 ' dummy changelog to prevent using the old repo layout'
62 ' dummy changelog to prevent using the old repo layout'
62 )
63 )
@@ -70,7 +71,7 b' class localrepository(repo.repository):'
70 # find requirements
71 # find requirements
71 requirements = set()
72 requirements = set()
72 try:
73 try:
73 requirements = set(self.opener("requires").read().splitlines())
74 requirements = set(self.opener.read("requires").splitlines())
74 except IOError, inst:
75 except IOError, inst:
75 if inst.errno != errno.ENOENT:
76 if inst.errno != errno.ENOENT:
76 raise
77 raise
@@ -80,7 +81,7 b' class localrepository(repo.repository):'
80
81
81 self.sharedpath = self.path
82 self.sharedpath = self.path
82 try:
83 try:
83 s = os.path.realpath(self.opener("sharedpath").read())
84 s = os.path.realpath(self.opener.read("sharedpath"))
84 if not os.path.exists(s):
85 if not os.path.exists(s):
85 raise error.RepoError(
86 raise error.RepoError(
86 _('.hg/sharedpath points to nonexistent directory %s') % s)
87 _('.hg/sharedpath points to nonexistent directory %s') % s)
@@ -652,7 +653,7 b' class localrepository(repo.repository):'
652 if self._link(filename):
653 if self._link(filename):
653 data = os.readlink(self.wjoin(filename))
654 data = os.readlink(self.wjoin(filename))
654 else:
655 else:
655 data = self.wopener(filename, 'r').read()
656 data = self.wopener.read(filename)
656 return self._filter(self._encodefilterpats, filename, data)
657 return self._filter(self._encodefilterpats, filename, data)
657
658
658 def wwrite(self, filename, data, flags):
659 def wwrite(self, filename, data, flags):
@@ -660,7 +661,7 b' class localrepository(repo.repository):'
660 if 'l' in flags:
661 if 'l' in flags:
661 self.wopener.symlink(data, filename)
662 self.wopener.symlink(data, filename)
662 else:
663 else:
663 self.wopener(filename, 'w').write(data)
664 fp = self.wopener.write(filename, data)
664 if 'x' in flags:
665 if 'x' in flags:
665 util.set_flags(self.wjoin(filename), False, True)
666 util.set_flags(self.wjoin(filename), False, True)
666
667
@@ -679,13 +680,14 b' class localrepository(repo.repository):'
679
680
680 # save dirstate for rollback
681 # save dirstate for rollback
681 try:
682 try:
682 ds = self.opener("dirstate").read()
683 ds = self.opener.read("dirstate")
683 except IOError:
684 except IOError:
684 ds = ""
685 ds = ""
685 self.opener("journal.dirstate", "w").write(ds)
686 self.opener.write("journal.dirstate", ds)
686 self.opener("journal.branch", "w").write(
687 self.opener.write("journal.branch",
687 encoding.fromlocal(self.dirstate.branch()))
688 encoding.fromlocal(self.dirstate.branch()))
688 self.opener("journal.desc", "w").write("%d\n%s\n" % (len(self), desc))
689 self.opener.write("journal.desc",
690 "%d\n%s\n" % (len(self), desc))
689
691
690 renames = [(self.sjoin("journal"), self.sjoin("undo")),
692 renames = [(self.sjoin("journal"), self.sjoin("undo")),
691 (self.join("journal.dirstate"), self.join("undo.dirstate")),
693 (self.join("journal.dirstate"), self.join("undo.dirstate")),
@@ -720,7 +722,7 b' class localrepository(repo.repository):'
720 lock = self.lock()
722 lock = self.lock()
721 if os.path.exists(self.sjoin("undo")):
723 if os.path.exists(self.sjoin("undo")):
722 try:
724 try:
723 args = self.opener("undo.desc", "r").read().splitlines()
725 args = self.opener.read("undo.desc").splitlines()
724 if len(args) >= 3 and self.ui.verbose:
726 if len(args) >= 3 and self.ui.verbose:
725 desc = _("repository tip rolled back to revision %s"
727 desc = _("repository tip rolled back to revision %s"
726 " (undo %s: %s)\n") % (
728 " (undo %s: %s)\n") % (
@@ -741,7 +743,7 b' class localrepository(repo.repository):'
741 util.rename(self.join('undo.bookmarks'),
743 util.rename(self.join('undo.bookmarks'),
742 self.join('bookmarks'))
744 self.join('bookmarks'))
743 try:
745 try:
744 branch = self.opener("undo.branch").read()
746 branch = self.opener.read("undo.branch")
745 self.dirstate.setbranch(branch)
747 self.dirstate.setbranch(branch)
746 except IOError:
748 except IOError:
747 self.ui.warn(_("named branch could not be reset, "
749 self.ui.warn(_("named branch could not be reset, "
@@ -275,7 +275,7 b' def _normalize(names, default, root, cwd'
275 elif kind in ('listfile', 'listfile0'):
275 elif kind in ('listfile', 'listfile0'):
276 delimiter = kind == 'listfile0' and '\0' or '\n'
276 delimiter = kind == 'listfile0' and '\0' or '\n'
277 try:
277 try:
278 files = open(name, 'r').read().split(delimiter)
278 files = util.readfile(name).split(delimiter)
279 files = [f for f in files if f]
279 files = [f for f in files if f]
280 except EnvironmentError:
280 except EnvironmentError:
281 raise util.Abort(_("unable to read file list (%s)") % name)
281 raise util.Abort(_("unable to read file list (%s)") % name)
@@ -47,7 +47,7 b' class mergestate(object):'
47 self._dirty = False
47 self._dirty = False
48 def add(self, fcl, fco, fca, fd, flags):
48 def add(self, fcl, fco, fca, fd, flags):
49 hash = util.sha1(fcl.path()).hexdigest()
49 hash = util.sha1(fcl.path()).hexdigest()
50 self._repo.opener("merge/" + hash, "w").write(fcl.data())
50 self._repo.opener.write("merge/" + hash, fcl.data())
51 self._state[fd] = ['u', hash, fcl.path(), fca.path(),
51 self._state[fd] = ['u', hash, fcl.path(), fca.path(),
52 hex(fca.filenode()), fco.path(), flags]
52 hex(fca.filenode()), fco.path(), flags]
53 self._dirty = True
53 self._dirty = True
@@ -467,7 +467,7 b' if __name__ == "__main__":'
467 print
467 print
468 return blocks
468 return blocks
469
469
470 text = open(sys.argv[1]).read()
470 text = util.readfile(sys.argv[1])
471 blocks = debug(findblocks, text)
471 blocks = debug(findblocks, text)
472 blocks = debug(findliteralblocks, blocks)
472 blocks = debug(findliteralblocks, blocks)
473 blocks, pruned = debug(prunecontainers, blocks, sys.argv[2:])
473 blocks, pruned = debug(prunecontainers, blocks, sys.argv[2:])
@@ -93,7 +93,7 b' class statichttprepository(localrepo.loc'
93
93
94 # find requirements
94 # find requirements
95 try:
95 try:
96 requirements = self.opener("requires").read().splitlines()
96 requirements = self.opener.read("requires").splitlines()
97 except IOError, inst:
97 except IOError, inst:
98 if inst.errno != errno.ENOENT:
98 if inst.errno != errno.ENOENT:
99 raise
99 raise
@@ -60,7 +60,7 b' def findglobaltags(ui, repo, alltags, ta'
60 def readlocaltags(ui, repo, alltags, tagtypes):
60 def readlocaltags(ui, repo, alltags, tagtypes):
61 '''Read local tags in repo. Update alltags and tagtypes.'''
61 '''Read local tags in repo. Update alltags and tagtypes.'''
62 try:
62 try:
63 data = repo.opener("localtags").read()
63 data = repo.opener.read("localtags")
64 except IOError, inst:
64 except IOError, inst:
65 if inst.errno != errno.ENOENT:
65 if inst.errno != errno.ENOENT:
66 raise
66 raise
@@ -311,7 +311,7 b' class templater(object):'
311 '''Get the template for the given template name. Use a local cache.'''
311 '''Get the template for the given template name. Use a local cache.'''
312 if not t in self.cache:
312 if not t in self.cache:
313 try:
313 try:
314 self.cache[t] = open(self.map[t][1]).read()
314 self.cache[t] = util.readfile(self.map[t][1])
315 except KeyError, inst:
315 except KeyError, inst:
316 raise util.Abort(_('"%s" not in template map') % inst.args[0])
316 raise util.Abort(_('"%s" not in template map') % inst.args[0])
317 except IOError, inst:
317 except IOError, inst:
General Comments 0
You need to be logged in to leave comments. Login now