160 def process(fin, fout): |
164 def process(fin, fout): |
161 tokens = tokenize.tokenize(fin.readline) |
165 tokens = tokenize.tokenize(fin.readline) |
162 tokens = replacetokens(list(tokens), fullname='<dummy>') |
166 tokens = replacetokens(list(tokens), fullname='<dummy>') |
163 fout.write(tokenize.untokenize(tokens)) |
167 fout.write(tokenize.untokenize(tokens)) |
164 |
168 |
|
169 def tryunlink(fname): |
|
170 try: |
|
171 os.unlink(fname) |
|
172 except OSError as err: |
|
173 if err.errno != errno.ENOENT: |
|
174 raise |
|
175 |
|
176 @contextlib.contextmanager |
|
177 def editinplace(fname): |
|
178 n = os.path.basename(fname) |
|
179 d = os.path.dirname(fname) |
|
180 fp = tempfile.NamedTemporaryFile(prefix='.%s-' % n, suffix='~', dir=d, |
|
181 delete=False) |
|
182 try: |
|
183 yield fp |
|
184 fp.close() |
|
185 if os.name == 'nt': |
|
186 tryunlink(fname) |
|
187 os.rename(fp.name, fname) |
|
188 finally: |
|
189 fp.close() |
|
190 tryunlink(fp.name) |
|
191 |
165 def main(): |
192 def main(): |
166 ap = argparse.ArgumentParser() |
193 ap = argparse.ArgumentParser() |
|
194 ap.add_argument('-i', '--inplace', action='store_true', default=False, |
|
195 help='edit files in place') |
167 ap.add_argument('files', metavar='FILE', nargs='+', help='source file') |
196 ap.add_argument('files', metavar='FILE', nargs='+', help='source file') |
168 args = ap.parse_args() |
197 args = ap.parse_args() |
169 for fname in args.files: |
198 for fname in args.files: |
170 with open(fname, 'rb') as fin: |
199 if args.inplace: |
171 fout = sys.stdout.buffer |
200 with editinplace(fname) as fout: |
172 process(fin, fout) |
201 with open(fname, 'rb') as fin: |
|
202 process(fin, fout) |
|
203 else: |
|
204 with open(fname, 'rb') as fin: |
|
205 fout = sys.stdout.buffer |
|
206 process(fin, fout) |
173 |
207 |
174 if __name__ == '__main__': |
208 if __name__ == '__main__': |
175 main() |
209 main() |