Hello community, here is the log from the commit of package setconf for openSUSE:Factory checked in at 2016-05-10 09:27:33 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Comparing /work/SRC/openSUSE:Factory/setconf (Old) and /work/SRC/openSUSE:Factory/.setconf.new (New) ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Package is "setconf" Changes: -------- --- /work/SRC/openSUSE:Factory/setconf/setconf.changes 2015-07-21 13:27:13.000000000 +0200 +++ /work/SRC/openSUSE:Factory/.setconf.new/setconf.changes 2016-05-10 09:27:34.000000000 +0200 @@ -1,0 +2,11 @@ +Sat May 7 07:12:54 UTC 2016 - sor.ale...@meowr.ru + +- Update to version 0.7.2 (changes since 0.6.7): + * Deal mainly with bytes instead of strings. + * Handle ISO-8859-1 (Latin1) better, for Python 3. + * Fix a failing testcase for +=. + * Fix an issue that only happened on Python 3.2. + * Remove a dependency on chardet. + * Several minor changes. + +------------------------------------------------------------------- Old: ---- setconf-0.6.7.tar.xz New: ---- setconf-0.7.2.tar.xz ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Other differences: ------------------ ++++++ setconf.spec ++++++ --- /var/tmp/diff_new_pack.QsuRo9/_old 2016-05-10 09:27:35.000000000 +0200 +++ /var/tmp/diff_new_pack.QsuRo9/_new 2016-05-10 09:27:35.000000000 +0200 @@ -1,7 +1,7 @@ # # spec file for package setconf # -# Copyright (c) 2015 SUSE LINUX GmbH, Nuernberg, Germany. +# Copyright (c) 2016 SUSE LINUX GmbH, Nuernberg, Germany. # # All modifications and additions to the file contributed by third parties # remain the property of their copyright owners, unless otherwise agreed @@ -17,7 +17,7 @@ Name: setconf -Version: 0.6.7 +Version: 0.7.2 Release: 0 Summary: Utility to easily change settings in configuration files License: GPL-2.0+ ++++++ setconf-0.6.7.tar.xz -> setconf-0.7.2.tar.xz ++++++ Files old/setconf-0.6.7/setconf.1.gz and new/setconf-0.7.2/setconf.1.gz differ diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/setconf-0.6.7/setconf.py new/setconf-0.7.2/setconf.py --- old/setconf-0.6.7/setconf.py 2015-06-25 21:50:37.000000000 +0200 +++ new/setconf-0.7.2/setconf.py 2016-03-28 15:07:26.000000000 +0200 @@ -1,4 +1,4 @@ -#!/usr/bin/python2 +#!/usr/bin/env python # -*- coding: utf-8 -*- # # setconf @@ -22,30 +22,31 @@ # Dec 2014 # Mar 2015 # Jun 2015 +# Mar 2016 # from sys import argv from sys import exit as sysexit -from os import linesep +from os import linesep as linesep_str from os.path import exists from tempfile import mkstemp -from subprocess import check_output from decimal import Decimal +from base64 import b64decode -# TODO: Use optparse or argparse if shedskin is no longer a target. +VERSION = "0.7.2" -VERSION = "0.6.7" -ASSIGNMENTS = ['==', '=>', '+=', '-=', '=', ':=', '::', ':'] +# TODO: Use optparse or argparse if shedskin is no longer a target. -def get_encoding(filename): - """Use the output from the file command to guess the encoding. - Returns (True, encoding) or (False, None)""" - s = check_output(["/usr/bin/file", filename]).strip().decode('utf-8') - if s.endswith("text"): - return (True, s.split(" ")[1]) - else: - return (False, None) +def bs(x): + """Convert from string to UTF-8 encoded bytes, if needed""" + if type(x) != type(b""): + return x.encode("utf-8") + return x + +NL = bs(linesep_str) +ASSIGNMENTS = [b'==', b'=>', b'+=', b'-=', b'?=', + b'=', b':=', b'::', b':'] def parts(line, including_assignment=True): @@ -55,14 +56,16 @@ if not stripline: return None, None # Skip lines that start with #, // or /* - if (stripline[0] == "#") or (stripline[:2] in ["//", "/*"]): - return None, None + for commentsymbol in [b"#", b"//", b"/*"]: + if stripline.startswith(commentsymbol): + # Skip this line + return None, None # These assignments are supported, in this order - assignment = "" + assignment = b"" found = [] for ass in ASSIGNMENTS: # Skip the += and -= operators when finding keys and values - if ass in ['+=', '-=']: + if ass in [b'+=', b'-=']: continue # Collect the rest if ass in line: @@ -73,7 +76,7 @@ elif found: # > 1 # If several assignments are found, use the first one firstpos = len(line) - firstassignment = "" + firstassignment = b"" for ass in found: pos = line.index(ass) if pos < firstpos: @@ -100,12 +103,15 @@ def changeline(line, newvalue): + line = bs(line) + newvalue = bs(newvalue) + first = firstpart(line) if first: - if "= " in line or ": " in line or "> " in line: - return first + " " + newvalue - elif "=\t" in line or ":\t" in line or ">\t" in line: - return first + "\t" + newvalue + if b"= " in line or b": " in line or b"> " in line: + return first + b" " + newvalue + elif b"=\t" in line or b":\t" in line or b">\t" in line: + return first + b"\t" + newvalue else: return first + newvalue else: @@ -114,29 +120,35 @@ def test_changeline(): passes = True - passes = passes and changeline("rabbits = DUMB", "cool") == "rabbits = cool" + passes = passes and changeline(" // ost = 2", "3") == b" // ost = 2" + passes = passes and changeline("rabbits = DUMB", "cool") == b"rabbits = cool" passes = passes and changeline( "for ever and ever : never", - "and ever") == "for ever and ever : and ever" + "and ever") == b"for ever and ever : and ever" passes = passes and changeline( " for ever and Ever := beaver", - "TURTLE") == " for ever and Ever := TURTLE" - passes = passes and changeline("CC=g++", "baffled") == "CC=baffled" - passes = passes and changeline("CC =\t\tg++", "baffled") == "CC =\tbaffled" - passes = passes and changeline("cabal ==1.2.3", "1.2.4") == "cabal ==1.2.4" + "TURTLE") == b" for ever and Ever := TURTLE" + passes = passes and changeline("CC=g++", "baffled") == b"CC=baffled" + passes = passes and changeline("CC =\t\tg++", "baffled") == b"CC =\tbaffled" + passes = passes and changeline("cabal ==1.2.3", "1.2.4") == b"cabal ==1.2.4" passes = passes and changeline( "TMPROOT=${TMPDIR:=/tmp}", - "/nice/pants") == "TMPROOT=/nice/pants" - passes = passes and changeline(" # ost = 2", "3") == " # ost = 2" - passes = passes and changeline(" // ost = 2", "3") == " // ost = 2" - passes = passes and changeline(" ost = 2", "3") == " ost = 3" - passes = passes and changeline(" /* ost = 2 */", "3") == " /* ost = 2 */" - passes = passes and changeline("æøå =>\t123", "256") == "æøå =>\t256" + "/nice/pants") == b"TMPROOT=/nice/pants" + passes = passes and changeline(" # ost = 2", "3") == b" # ost = 2" + + # The above passes, except for the first one + + passes = passes and changeline(" ost = 2", "3") == b" ost = 3" + passes = passes and changeline(" /* ost = 2 */", "3") == b" /* ost = 2 */" + passes = passes and changeline("æøå =>\t123", "256") == bs("æøå =>\t256") print("Changeline passes: %s" % (passes)) return passes def change(lines, key, value): + key = bs(key) + value = bs(value) + newlines = [] for line in lines: if not line.strip(): @@ -154,21 +166,23 @@ def test_change(): - testcontent = """LIGHTS = ON + testcontent = b"""LIGHTS = ON bananas= not present tea := yes randombob :ok """ - testcontent_changed = """LIGHTS = off + testcontent_changed = b"""LIGHTS = off bananas= not present tea := yes randombob :ok """ passes = True - a = "".join(change(testcontent.split(linesep), "LIGHTS", "off")) - b = "".join(testcontent_changed.split(linesep)) + splitted = testcontent.split(NL) + elements = change(splitted, "LIGHTS", "off") + a = bytes.join(b"", elements) + b = bytes.join(b"", testcontent_changed.split(NL)) passes = passes and a == b print("Change passes: %s" % (passes)) return passes @@ -176,91 +190,99 @@ def changefile(filename, key, value, dummyrun=False): """if dummyrun==True, don't write but return True if changes would have been made""" + + key = bs(key) + value = bs(value) + # Read the file try: - file = open(filename) - data = file.read() - lines = data.split(linesep)[:-1] - file.close() + with open(filename, 'rb') as f: + data = f.read() + lines = data.split(NL)[:-1] except IOError: print("Can't read %s" % (filename)) sysexit(2) final_nl = True - if linesep not in data: + if NL not in data: lines = [data] final_nl = False - elif not data.endswith(linesep): + elif not data.endswith(NL): final_nl = False # Change and write the file - changed_contents = linesep.join(change(lines, key, value)) + changed_contents = NL.join(change(lines, key, value)) # Only add a final newline if the original contents had one at the end if final_nl: - changed_contents += linesep + changed_contents += NL if dummyrun: return data != changed_contents try: - file = open(filename, "w") + with open(filename, 'wb') as f: + f.write(changed_contents) except IOError: print("No write permission: %s" % (filename)) sysexit(2) - file.write(changed_contents) - file.close() + def addtofile(filename, line): """Tries to add a line to a file. UTF-8. No questions asked.""" + + line = bs(line) + # Read the file try: - file = open(filename) - data = file.read() - lines = data.split(linesep)[:-1] - file.close() + with open(filename, 'rb') as f: + data = f.read() + lines = data.split(NL)[:-1] except IOError: print("Can't read %s" % (filename)) sysexit(2) - if data.strip() == "": + if data.strip() == b"": lines = [] - elif linesep not in data: + elif NL not in data: lines = [data] # Change and write the file try: - file = open(filename, "w") + with open(filename, 'wb') as f: + lines.append(line) + added_data = NL.join(lines) + NL + f.write(added_data) except IOError: print("No write permission: %s" % (filename)) sysexit(2) - lines.append(line) - added_data = linesep.join(lines) + linesep - file.write(added_data) - file.close() def test_changefile(): # Test data - testcontent = "keys := missing" + linesep + "døg = found" + linesep * 3 + "æøåÆØÅ" + linesep - testcontent_changed = "keys := found" + linesep + \ - "døg = missing" + linesep * 3 + "æøåÆØÅ" + linesep + testcontent = b"keys := missing" + NL + bs("døg = found") + NL * 3 + bs("æøåÆØÅ") + NL + testcontent_changed = b"keys := found" + NL + \ + bs("døg = missing") + NL * 3 + bs("æøåÆØÅ") + NL filename = mkstemp()[1] # Write the testfile - file = open(filename, "w") - file.write(testcontent) - file.close() + with open(filename, 'wb') as f: + f.write(testcontent) # Change the file with changefile changefile(filename, "keys", "found") changefile(filename, "døg", "missing") # Read the file - file = open(filename) - newcontent = file.read().split(linesep)[:-1] - file.close() + with open(filename, 'rb') as f: + newcontent = f.read().split(NL)[:-1] # Do the tests passes = True - passes = passes and newcontent == testcontent_changed.split(linesep)[:-1] + passes = passes and newcontent == testcontent_changed.split(NL)[:-1] print("Changefile passes: %s" % (passes)) return passes -def change_multiline(data, key, value, endstring=linesep, verbose=True, searchfrom=0): +def change_multiline(data, key, value, endstring=NL, verbose=True, searchfrom=0): + + data = bs(data) + key = bs(key) + value = bs(value) + endstring = bs(endstring) + if key not in data: return data - if (endstring != linesep) and (endstring not in data): + if (endstring != NL) and (endstring not in data): if verbose: print("Multiline end marker not found: " + endstring) return data @@ -272,7 +294,7 @@ before = data[:startpos] between = data[startpos:endpos + 1] - linestartpos = data[:startpos].rfind(linesep) + 1 + linestartpos = data[:startpos].rfind(NL) + 1 line = data[linestartpos:endpos + 1] # If the first part of the line is not a key (could be because it's commented out)... if not firstpart(line): @@ -281,8 +303,8 @@ after = data[endpos + len(endstring):] newbetween = changeline(between, value) - if between.endswith(linesep): - newbetween += linesep + if between.endswith(NL): + newbetween += NL result = before + newbetween + after return result @@ -290,80 +312,80 @@ def test_change_multiline(): passes = True # test 1 - testcontent = "keys := missing" + linesep + "dog = found" + linesep * 3 - testcontent_changed = "keys := found" + linesep + "dog = found" + linesep * 3 + testcontent = b"keys := missing" + NL + b"dog = found" + NL * 3 + testcontent_changed = b"keys := found" + NL + b"dog = found" + NL * 3 a = change_multiline(testcontent, "keys", "found") b = testcontent_changed - extracheck = testcontent.replace("missing", "found") == testcontent_changed + extracheck = testcontent.replace(b"missing", b"found") == testcontent_changed passes = passes and a == b and extracheck if not passes: print("FAIL1") # test 2 - testcontent = 'blabla\nOST=(a\nb)\n\nblabla\nÆØÅ' - testcontent_changed = 'blabla\nOST=(c d)\n\nblabla\nÆØÅ' + testcontent = bs('blabla\nOST=(a\nb)\n\nblabla\nÆØÅ') + testcontent_changed = bs('blabla\nOST=(c d)\n\nblabla\nÆØÅ') a = change_multiline(testcontent, "OST", "(c d)", ")") b = testcontent_changed passes = passes and a == b if not passes: print("FAIL2") # test 3 - testcontent = 'bläblä=1' - testcontent_changed = 'bläblä=2' + testcontent = bs('bläblä=1') + testcontent_changed = bs('bläblä=2') a = change_multiline(testcontent, "bläblä", "2") b = testcontent_changed passes = passes and a == b if not passes: print("FAIL3") # test 4 - testcontent = "\n" - testcontent_changed = "\n" + testcontent = b"\n" + testcontent_changed = b"\n" a = change_multiline(testcontent, "blablañ", "ost") b = testcontent_changed passes = passes and a == b if not passes: print("FAIL4") # test 5 - testcontent = "" - testcontent_changed = "" + testcontent = b"" + testcontent_changed = b"" a = change_multiline(testcontent, "blabla", "ost") b = testcontent_changed passes = passes and a == b if not passes: print("FAIL5") # test 6 - testcontent = "a=(1, 2, 3" - testcontent_changed = "a=(1, 2, 3" + testcontent = b"a=(1, 2, 3" + testcontent_changed = b"a=(1, 2, 3" a = change_multiline(testcontent, "a", "(4, 5, 6)", ")", verbose=False) b = testcontent_changed passes = passes and a == b if not passes: print("FAIL6") # test 7 - testcontent = "a=(1, 2, 3\nb=(7, 8, 9)" - testcontent_changed = "a=(4, 5, 6)" + testcontent = b"a=(1, 2, 3\nb=(7, 8, 9)" + testcontent_changed = b"a=(4, 5, 6)" a = change_multiline(testcontent, "a", "(4, 5, 6)", ")") b = testcontent_changed passes = passes and a == b if not passes: print("FAIL7") # test 8 - testcontent = "a=(0, 0, 0)\nb=(1\n2\n3\n)\nc=(7, 8, 9)" - testcontent_changed = "a=(0, 0, 0)\nb=(4, 5, 6)\nc=(7, 8, 9)" + testcontent = b"a=(0, 0, 0)\nb=(1\n2\n3\n)\nc=(7, 8, 9)" + testcontent_changed = b"a=(0, 0, 0)\nb=(4, 5, 6)\nc=(7, 8, 9)" a = change_multiline(testcontent, "b", "(4, 5, 6)", ")") b = testcontent_changed passes = passes and a == b if not passes: print("FAIL8") # test 9 - testcontent = "a=(0, 0, 0)\nb=(1\n2\n3\n)\nc=(7, 8, 9)\n\n" - testcontent_changed = "a=(0, 0, 0)\nb=(1\n2\n3\n)\nc=(7, 8, 9)\n\n" + testcontent = b"a=(0, 0, 0)\nb=(1\n2\n3\n)\nc=(7, 8, 9)\n\n" + testcontent_changed = b"a=(0, 0, 0)\nb=(1\n2\n3\n)\nc=(7, 8, 9)\n\n" a = change_multiline(testcontent, "b", "(4, 5, 6)", "]", verbose=False) b = testcontent_changed passes = passes and a == b if not passes: print("FAIL9") # test 10 - testcontent = """ + testcontent = bs(""" source=("http://prdownloads.sourceforge.net/maniadrive/ManiaDrive-$pkgver-linux-i386.tar.gz" "maniadrive.desktop" "ñlicense.txt" @@ -375,8 +397,8 @@ build() { cd "$srcdir/ManiaDrive-$pkgver-linux-i386" -""" - testcontent_changed = """ +""") + testcontent_changed = bs(""" source=("http://prdownloads.sourceforge.net/maniadrive/ManiaDrive-$pkgver-linux-i386.tar.gz" "maniadrive.desktop" "ñlicense.txt" @@ -385,23 +407,23 @@ build() { cd "$srcdir/ManiaDrive-$pkgver-linux-i386" -""" +""") a = change_multiline(testcontent, "md5sums", "('123abc' 'abc123')", ")", verbose=False) b = testcontent_changed passes = passes and a == b if not passes: print("FAIL10") # test 11 - testcontent = "x=(0, 0, 0)\nCHEESE\nz=2\n" - testcontent_changed = "x=(4, 5, 6)\nz=2\n" + testcontent = b"x=(0, 0, 0)\nCHEESE\nz=2\n" + testcontent_changed = b"x=(4, 5, 6)\nz=2\n" a = change_multiline(testcontent, "x", "(4, 5, 6)", "CHEESE", verbose=False) b = testcontent_changed passes = passes and a == b if not passes: print("FAIL11") # test 12 - testcontent = "# md5sum=('abc123')\nmd5sum=('def456')\nmd5sum=('ghi789')\n" - testcontent_changed = "# md5sum=('abc123')\nmd5sum=('OST')\nmd5sum=('ghi789')\n" + testcontent = b"# md5sum=('abc123')\nmd5sum=('def456')\nmd5sum=('ghi789')\n" + testcontent_changed = b"# md5sum=('abc123')\nmd5sum=('OST')\nmd5sum=('ghi789')\n" a = change_multiline(testcontent, "md5sum", "('OST')", "\n", verbose=False) b = testcontent_changed passes = passes and a == b @@ -412,44 +434,43 @@ return passes -def changefile_multiline(filename, key, value, endstring="\n"): +def changefile_multiline(filename, key, value, endstring=b"\n"): + + key = bs(key) + value = bs(value) + # Read the file try: - file = open(filename) - data = file.read() - file.close() + with open(filename, 'rb') as f: + data = f.read() except IOError: print("Can't read %s" % (filename)) sysexit(2) # Change and write the file new_contents = change_multiline(data, key, value, endstring) try: - file = open(filename, "w") - file.write(new_contents) + with open(filename, 'wb') as f: + f.write(new_contents) except: # UnicodeEncodeError: not supported by shedskin #print("codeEncodeError: Can't change value for %s" % (filename)) print("Can't change value for %s" % (filename)) sysexit(2) - # finally is not supported by shedskin - file.close() def test_changefile_multiline(): # Test data - testcontent = "keys := missing" + linesep + "dog = found" + linesep * 3 + "æøåÆØÅ" - testcontent_changed = "keys := found" + linesep + "dog = missing" + linesep * 3 + "æøåÆØÅ" + testcontent = b"keys := missing" + NL + b"dog = found" + NL * 3 + bs("æøåÆØÅ") + testcontent_changed = b"keys := found" + NL + b"dog = missing" + NL * 3 + bs("æøåÆØÅ") filename = mkstemp()[1] # Write the testfile - file = open(filename, "w") - file.write(testcontent) - file.close() + with open(filename, 'wb') as f: + f.write(testcontent) # Change the file with changefile changefile_multiline(filename, "keys", "found") changefile_multiline(filename, "dog", "missing") # Read the file - file = open(filename, "r") - newcontent = file.read() - file.close() + with open(filename, 'rb') as f: + newcontent = f.read() # Do the tests passes = True passes = passes and newcontent == testcontent_changed @@ -462,16 +483,15 @@ def test_addline(): # --- TEST 1 --- - testcontent = "# cache-ttl=65000" + linesep + "MOO=yes" + linesep - testcontent_changed = "# cache-ttl=65000" + linesep + "MOO=no" + linesep + \ - "X=123" + linesep + "Y=345" + linesep + "Z:=567" + linesep + \ - "FJORD => 999" + linesep + 'vm.swappiness=1' + \ - linesep + "cache-ttl=6" + linesep + testcontent = b"# cache-ttl=65000" + NL + b"MOO=yes" + NL + testcontent_changed = b"# cache-ttl=65000" + NL + b"MOO=no" + NL + \ + b"X=123" + NL + b"Y=345" + NL + b"Z:=567" + NL + \ + b"FJORD => 999" + NL + b'vm.swappiness=1' + \ + NL + b"cache-ttl=6" + NL filename = mkstemp()[1] # Write the testfile - file = open(filename, "w") - file.write(testcontent) - file.close() + with open(filename, 'wb') as f: + f.write(testcontent) # Change the file by adding keys and values main(["-a", filename, "X", "123"]) main(["--add", filename, "Y=345"]) @@ -482,22 +502,19 @@ main(["-a", filename, "vm.swappiness=1"]) main(["-a", filename, "cache-ttl=6"]) # Read the file - file = open(filename, "r") - newcontent = file.read() - file.close() + with open(filename, 'rb') as f: + newcontent = f.read() # --- TEST 2 --- - testcontent_changed2 = "x=2" + linesep + testcontent_changed2 = b"x=2" + NL filename = mkstemp()[1] # Write an empty testfile - file = open(filename, "w+") - file.close() + open(filename, 'wb+').close() # Change the file by adding keys and values main(["-a", filename, "x=2"]) # Read the file - file2 = open(filename, "r") - newcontent2 = file2.read() - file2.close() + with open(filename, 'rb') as f: + newcontent2 = f.read() # Do the tests passes = True @@ -508,6 +525,29 @@ return passes +def test_latin1(): + # Test data + testcontent = b64decode( + b"SGVsbG8sIHRoaXMgaXMgYW4gSVNPLTg4NTktMSBlbmNvZGVkIHRleHQgZmlsZS4gQmzlYuZyIG9n\nIHL4ZHZpbi4KCkFsc28sCng9Nwo=") + testcontent_changed = b64decode( + b"SGVsbG8sIHRoaXMgaXMgYW4gSVNPLTg4NTktMSBlbmNvZGVkIHRleHQgZmlsZS4gQmzlYuZyIG9n\nIHL4ZHZpbi4KCkFsc28sCng9NDIK") + + filename = mkstemp()[1] + # Write the testfile + with open(filename, 'wb') as f: + f.write(testcontent) # already bytes, no need to encode + # Change the file with changefile + changefile(filename, "x", "42") + # Read the file + with open(filename, 'rb') as f: + newcontent = f.read().split(NL)[:-1] + # Do the tests + passes = True + passes = passes and newcontent == testcontent_changed.split(NL)[:-1] + print("ISO-8859-1 passes: %s" % (passes)) + return passes + + def tests(): # If one test fails, the rest will not be run passes = True @@ -517,6 +557,7 @@ passes = passes and test_change_multiline() passes = passes and test_changefile_multiline() passes = passes and test_addline() + passes = passes and test_latin1() if passes: print("All tests pass!") else: @@ -526,16 +567,15 @@ def create_if_missing(filename): if not exists(filename): try: - f = open(filename, "w") + open(filename, 'wb').close() except IOError: print("No write permission: %s" % (filename)) sysexit(2) - f.close() def has_key(data, key): """Check if the given key exists in the given data.""" - lines = data.split(linesep)[:-1] + lines = data.split(NL)[:-1] for line in lines: if not line.strip(): # Skip blank lines @@ -545,39 +585,54 @@ return True return False + def get_value(data, key): """Return the first value for a given key.""" - lines = data.split(linesep)[:-1] + lines = data.split(NL)[:-1] for line in lines: if not line.strip(): # Skip blank lines continue first, second = parts(line, False) + if first: + first = first.strip() + if second: + second = second.strip() if key == first: return second - return "" + return b"" + def strip_trailing_zeros(s): - return s.rstrip('0').rstrip('.') if '.' in s else s + return s.rstrip(b'0').rstrip(b'.') if b'.' in s else s + + +def byte2decimal(b): + return Decimal(b.decode("utf-8", "ignore")) + def inc(startvalue, s): - """Increase the number in the string with the given string, or return the same string.""" + """Increase the number in the byte string with the given byte string, + or return the same string.""" try: - result = str(Decimal(startvalue)+Decimal(s)) + result = bs(str(byte2decimal(startvalue) + byte2decimal(s))) except ArithmeticError: return s return strip_trailing_zeros(result) + def dec(startvalue, s): - """Decrease the number in the string with the given string, or return the same string.""" + """Decrease the number in the string with the given string, + or return the same string.""" try: - result = str(Decimal(startvalue)-Decimal(s)) + result = bs(str(byte2decimal(startvalue) - byte2decimal(s))) except ArithmeticError: return s return strip_trailing_zeros(result) + def main(args=argv[1:], exitok=True): if len(args) == 1: if args[0] in ["-t", "--test"]: @@ -612,31 +667,29 @@ elif len(args) == 2: # Single line replace: "x=123" or "x+=2" filename = args[0] - keyvalue = args[1] - if "+=" in keyvalue: - key, value = keyvalue.split("+=", 1) + keyvalue = bs(args[1]) + if b"+=" in keyvalue: + key, value = keyvalue.split(b"+=", 1) try: - f = open(filename) + with open(filename, 'rb') as f: + data = f.read() except IOError: print("Can't read %s" % (filename)) sysexit(2) - data = f.read() - f.close() datavalue = get_value(data, key) changefile(filename, key, inc(datavalue, value)) - elif "-=" in keyvalue: - key, value = keyvalue.split("-=", 1) + elif b"-=" in keyvalue: + key, value = keyvalue.split(b"-=", 1) try: - f = open(filename) + with open(filename, 'rb') as f: + data = f.read() except IOError: print("Can't read %s" % (filename)) sysexit(2) - data = f.read() - f.close() datavalue = get_value(data, key) changefile(filename, key, dec(datavalue, value)) - elif "=" in keyvalue: - key, value = keyvalue.split("=", 1) + elif b"=" in keyvalue: + key, value = keyvalue.split(b"=", 1) changefile(filename, key, value) else: sysexit(2) @@ -644,7 +697,7 @@ if args[0] in ["-a", "--add"]: # Single line replace/add ("x 123") filename = args[1] - keyvalue = args[2] + keyvalue = bs(args[2]) create_if_missing(filename) @@ -663,22 +716,21 @@ if changefile(filename, key, value, dummyrun=True): changefile(filename, key, value) else: - f = open(filename) - data = f.read() - f.close() + with open(filename, 'rb') as f: + data = f.read() if not has_key(data, key): addtofile(filename, keyvalue) else: # Single line replace ("x 123") filename = args[0] - key = args[1] - value = args[2] + key = bs(args[1]) + value = bs(args[2]) changefile(filename, key, value) elif len(args) == 4: if args[0] in ["-a", "--add"]: filename = args[1] - key = args[2] - value = args[3] + key = bs(args[2]) + value = bs(args[3]) create_if_missing(filename) @@ -686,18 +738,17 @@ if changefile(filename, key, value, dummyrun=True): changefile(filename, key, value) else: - keyvalue = key + "=" + value - f = open(filename) - data = f.read() - f.close() + keyvalue = key + b"=" + value + with open(filename, 'rb') as f: + data = f.read() if not has_key(data, key): addtofile(filename, keyvalue) else: # Multiline replace filename = args[0] - key = args[1] - value = args[2] - endstring = args[3] + key = bs(args[1]) + value = bs(args[2]) + endstring = bs(args[3]) changefile_multiline(filename, key, value, endstring) else: sysexit(1)