File size: 1,670 Bytes
f65fe85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
'''
    Copyright (C) 2008--2020 Jan Nieuwenhuizen <[email protected]>

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License as
    published by the Free Software Foundation; either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''

import os
import re
import stat
import sys

dry_run = False


def pytt(from_re, to, file_name):
    s = open(file_name, mode='rb').read()
    name = os.path.basename(file_name)
    base, ext = os.path.splitext(name)
    t = re.sub(from_re.encode('utf-8'), to.encode('utf-8') % locals(), s)
    if s != t:
        if dry_run:
            sys.stdout.write(t)
        else:
            stat_info = os.stat(file_name)
            mode = stat.S_IMODE(stat_info[stat.ST_MODE])
            os.system('mv --backup=t %(file_name)s %(file_name)s~' % locals())
            open(file_name, 'wb').write(t)
            os.chmod(file_name, mode)


def main():
    from_re = re.compile(sys.argv[1], re.MULTILINE)
    to = sys.argv[2]
    if not sys.argv[3:] or sys.argv[3] == '-':
        sys.stdout.write(re.sub(from_re, to, sys.stdin.read()))
    else:
        for f in sys.argv[3:]:
            pytt(from_re, to, f)


if __name__ == '__main__':
    main()