@@ -18,6 +18,8 @@ parser.add_argument('PATCH', type=argparse.FileType('r'),
18
18
help = 'Patch file (read from stdin if omitted)' )
19
19
parser .add_argument ('--indent' , type = int , default = None ,
20
20
help = 'Indent output by n spaces' )
21
+ parser .add_argument ('-b' , '--backup' , action = 'store_true' ,
22
+ help = 'Back up ORIGINAL if modifying in-place' )
21
23
parser .add_argument ('-i' , '--in-place' , action = 'store_true' ,
22
24
help = 'Modify ORIGINAL in-place instead of to stdout' )
23
25
parser .add_argument ('-v' , '--version' , action = 'version' ,
@@ -37,18 +39,36 @@ def patch_files():
37
39
doc = json .load (args .ORIGINAL )
38
40
patch = json .load (args .PATCH )
39
41
result = jsonpatch .apply_patch (doc , patch )
42
+
40
43
if args .in_place :
41
44
dirname = os .path .abspath (os .path .dirname (args .ORIGINAL .name ))
42
- fd , pathname = tempfile .mkstemp (dir = dirname )
43
- fp = os .fdopen (fd , 'w' )
45
+ try :
46
+ fd , pathname = tempfile .mkstemp (dir = dirname )
47
+ fp = os .fdopen (fd , 'w' )
48
+ atomic = True
49
+ except OSError :
50
+ if args .backup :
51
+ os .rename (args .ORIGINAL .name , args .ORIGINAL .name + '.orig' )
52
+ fp = open (args .ORIGINAL .name , 'w' )
53
+ atomic = False
54
+
44
55
else :
45
56
fp = sys .stdout
57
+
46
58
json .dump (result , fp , indent = args .indent )
59
+ fp .write ('\n ' )
60
+
47
61
if args .in_place :
48
62
fp .close ()
49
- os .link (args .ORIGINAL .name , args .ORIGINAL .name + '.orig' )
50
- os .chmod (pathname , os .stat (args .ORIGINAL .name ).st_mode )
51
- os .rename (pathname , args .ORIGINAL .name )
63
+ if atomic :
64
+ try :
65
+ if args .backup :
66
+ os .link (args .ORIGINAL .name , args .ORIGINAL .name + '.orig' )
67
+ os .chmod (pathname , os .stat (args .ORIGINAL .name ).st_mode )
68
+ os .rename (pathname , args .ORIGINAL .name )
69
+ except OSError :
70
+ os .unlink (args .ORIGINAL .name )
71
+ os .rename (pathname , args .ORIGINAL .name )
52
72
53
73
54
74
if __name__ == "__main__" :
0 commit comments