2424
2525def edit_file (key , value , file , fmt , must_exist = False ):
2626 data = DottedDict (read_file (file , fmt ))
27- if must_exist :
28- try :
29- # this is the way I found it works for array vals too
30- # e.g. fruits.0.name
31- data [key ]
32- except KeyError :
27+ try :
28+ # this is the way I found it works for array vals too
29+ # e.g. fruits.0.name
30+ if data [key ] == value and type (data [key ]) == type (value ):
31+ # prevents writing to the file is value is matching already
32+ return False
33+ except KeyError :
34+ if must_exist :
3335 raise ValueError ('{} is not present in {}' .format (key , file ))
3436 data [key ] = value
35- write_file (file , fmt , data )
37+ return write_file (file , fmt , data )
3638
3739
3840def read_file (file , fmt ):
@@ -60,6 +62,7 @@ def write_file(file, fmt, data):
6062 fd .write (to ())
6163 fd .close ()
6264 os .rename (tmp , file )
65+ return True
6366 except Exception :
6467 # We can assume we can remove it, because we successfully created
6568 # it with O_EXCL above.
@@ -103,11 +106,13 @@ def main():
103106 parser .add_argument ('file' , metavar = '<filename>' , help = 'Filename to edit' )
104107 parser .add_argument ('-e' , '--must-exist' , dest = 'must_exist' , action = 'store_true' ,
105108 help = 'Throw error and exit if the key does not already exist' )
109+ parser .add_argument ('-m' , '--must-change' , dest = 'must_change' , action = 'store_true' ,
110+ help = 'Exit with status code 2 if the values already match and file unchanged' )
106111 parser .add_argument ('-s' , '--string' , dest = 'is_string' , action = 'store_true' ,
107112 help = 'Always treat value as a string by quoting it' )
108113 parser .add_argument ('--version' , action = 'version' ,
109114 version = '%(prog)s {version}' .format (version = __version__ ))
110- parser .set_defaults (is_string = False , must_exist = False )
115+ parser .set_defaults (is_string = False , must_exist = False , must_change = False )
111116 args = parser .parse_args ()
112117
113118 if args .is_string :
@@ -123,7 +128,9 @@ def main():
123128 sys .exit (1 )
124129
125130 try :
126- edit_file (args .key , val , args .file , fmt , must_exist = args .must_exist )
131+ res = edit_file (args .key , val , args .file , fmt , must_exist = args .must_exist )
132+ if args .must_change and res is False :
133+ sys .exit (2 )
127134 except ValueError as e :
128135 print ("\033 [91mError: \033 [0m" + str (e ), file = sys .stderr )
129136 sys .exit (1 )
0 commit comments