comparison mercurial/posix.py @ 45717:755214a84b9d

posix: use context managers in a couple of places Differential Revision: https://phab.mercurial-scm.org/D9205
author Matt Harbison <matt_harbison@yahoo.com>
date Tue, 13 Oct 2020 16:41:01 -0400
parents 8e8fd938ca07
children 87c35b5a14eb
comparison
equal deleted inserted replaced
45716:9628d3cd9d13 45717:755214a84b9d
142 st = os.lstat(f) 142 st = os.lstat(f)
143 s = st.st_mode 143 s = st.st_mode
144 if l: 144 if l:
145 if not stat.S_ISLNK(s): 145 if not stat.S_ISLNK(s):
146 # switch file to link 146 # switch file to link
147 fp = open(f, b'rb') 147 with open(f, b'rb') as fp:
148 data = fp.read() 148 data = fp.read()
149 fp.close()
150 unlink(f) 149 unlink(f)
151 try: 150 try:
152 os.symlink(data, f) 151 os.symlink(data, f)
153 except OSError: 152 except OSError:
154 # failed to make a link, rewrite file 153 # failed to make a link, rewrite file
155 fp = open(f, b"wb") 154 with open(f, b"wb") as fp:
156 fp.write(data) 155 fp.write(data)
157 fp.close() 156
158 # no chmod needed at this point 157 # no chmod needed at this point
159 return 158 return
160 if stat.S_ISLNK(s): 159 if stat.S_ISLNK(s):
161 # switch link to file 160 # switch link to file
162 data = os.readlink(f) 161 data = os.readlink(f)
163 unlink(f) 162 unlink(f)
164 fp = open(f, b"wb") 163 with open(f, b"wb") as fp:
165 fp.write(data) 164 fp.write(data)
166 fp.close()
167 s = 0o666 & ~umask # avoid restatting for chmod 165 s = 0o666 & ~umask # avoid restatting for chmod
168 166
169 sx = s & 0o100 167 sx = s & 0o100
170 if st.st_nlink > 1 and bool(x) != bool(sx): 168 if st.st_nlink > 1 and bool(x) != bool(sx):
171 # the file is a hardlink, break it 169 # the file is a hardlink, break it