Browse Source

util.py: minor cleanups, function renames

The MMGen Project 3 years ago
parent
commit
af710a9c82
4 changed files with 25 additions and 36 deletions
  1. 1 1
      mmgen/cfg.py
  2. 1 1
      mmgen/rpc.py
  3. 22 33
      mmgen/util.py
  4. 1 1
      test/test_py_d/ts_input.py

+ 1 - 1
mmgen/cfg.py

@@ -83,7 +83,7 @@ class CfgFile(object):
 	def get_lines(self):
 	def get_lines(self):
 		def gen_lines():
 		def gen_lines():
 			for lineno,line in enumerate(self.data,1):
 			for lineno,line in enumerate(self.data,1):
-				line = strip_comments(line)
+				line = strip_comment(line)
 				if line == '':
 				if line == '':
 					continue
 					continue
 				m = re.fullmatch(r'(\w+)(\s+)(.*)',line)
 				m = re.fullmatch(r'(\w+)(\s+)(.*)',line)

+ 1 - 1
mmgen/rpc.py

@@ -505,7 +505,7 @@ class BitcoinRPCClient(RPCClient,metaclass=AsyncInit):
 
 
 	def get_daemon_auth_cookie(self):
 	def get_daemon_auth_cookie(self):
 		fn = self.get_daemon_auth_cookie_fn()
 		fn = self.get_daemon_auth_cookie_fn()
-		return get_lines_from_file(fn,'')[0] if file_is_readable(fn) else ''
+		return get_lines_from_file(fn,'')[0] if os.access(fn,os.R_OK) else ''
 
 
 	@staticmethod
 	@staticmethod
 	def make_host_path(wallet):
 	def make_host_path(wallet):

+ 22 - 33
mmgen/util.py

@@ -394,28 +394,12 @@ def check_int_between(n,lo,hi,desc='value'):
 def match_ext(addr,ext):
 def match_ext(addr,ext):
 	return addr.split('.')[-1] == ext
 	return addr.split('.')[-1] == ext
 
 
-def file_exists(f):
-	try:
-		os.stat(f)
-		return True
-	except:
-		return False
-
-def file_is_readable(f):
-	from stat import S_IREAD
-	try:
-		assert os.stat(f).st_mode & S_IREAD
-	except:
-		return False
-	else:
-		return True
-
 def get_from_brain_opt_params():
 def get_from_brain_opt_params():
 	l,p = opt.from_brain.split(',')
 	l,p = opt.from_brain.split(',')
 	return(int(l),p)
 	return(int(l),p)
 
 
-def remove_whitespace(s):
-	return s.translate(dict((ord(ws),None) for ws in '\t\r\n '))
+def remove_whitespace(s,ws='\t\r\n '):
+	return s.translate(dict((ord(e),None) for e in ws))
 
 
 def pretty_format(s,width=80,pfx=''):
 def pretty_format(s,width=80,pfx=''):
 	out = []
 	out = []
@@ -455,11 +439,11 @@ def decode_pretty_hexdump(data):
 		msg('Data not in hexdump format')
 		msg('Data not in hexdump format')
 		return False
 		return False
 
 
-def strip_comments(line):
-	return re.sub(r'\s+$','',re.sub(r'#.*','',line,1))
+def strip_comment(line):
+	return re.sub(r'\s+$','',re.sub(r'#.*','',line))
 
 
-def remove_comments(lines):
-	return [m for m in [strip_comments(l) for l in lines] if m != '']
+def strip_comments(lines):
+	return [m for m in [strip_comment(l) for l in lines] if m != '']
 
 
 def get_hash_params(hash_preset):
 def get_hash_params(hash_preset):
 	if hash_preset in g.hash_presets:
 	if hash_preset in g.hash_presets:
@@ -510,15 +494,19 @@ def open_file_or_exit(filename,mode,silent=False):
 
 
 def check_file_type_and_access(fname,ftype,blkdev_ok=False):
 def check_file_type_and_access(fname,ftype,blkdev_ok=False):
 
 
-	a = ((os.R_OK,'read'),(os.W_OK,'writ'))
-	access,m = a[ftype in ('output file','output directory')]
+	access,op_desc = (
+		(os.W_OK,'writ') if ftype in ('output file','output directory') else
+		(os.R_OK,'read') )
 
 
-	ok_types = [
-		(stat.S_ISREG,'regular file'),
-		(stat.S_ISLNK,'symbolic link')
-	]
-	if blkdev_ok: ok_types.append((stat.S_ISBLK,'block device'))
-	if ftype == 'output directory': ok_types = [(stat.S_ISDIR, 'output directory')]
+	if ftype == 'output directory':
+		ok_types = [(stat.S_ISDIR, 'output directory')]
+	else:
+		ok_types = [
+			(stat.S_ISREG,'regular file'),
+			(stat.S_ISLNK,'symbolic link')
+		]
+		if blkdev_ok:
+			ok_types.append((stat.S_ISBLK,'block device'))
 
 
 	try:
 	try:
 		mode = os.stat(fname).st_mode
 		mode = os.stat(fname).st_mode
@@ -533,7 +521,7 @@ def check_file_type_and_access(fname,ftype,blkdev_ok=False):
 		die(1,f'Requested {ftype} {fname!r} is not a {ok_list}')
 		die(1,f'Requested {ftype} {fname!r} is not a {ok_list}')
 
 
 	if not os.access(fname,access):
 	if not os.access(fname,access):
-		die(1,f'Requested {ftype} {fname!r} is not {m}able by you')
+		die(1,f'Requested {ftype} {fname!r} is not {op_desc}able by you')
 
 
 	return True
 	return True
 
 
@@ -645,7 +633,7 @@ def write_data_to_file( outfile,data,desc='data',
 				die(1,f'{capfirst(desc)} not saved')
 				die(1,f'{capfirst(desc)} not saved')
 
 
 		hush = False
 		hush = False
-		if file_exists(outfile) and ask_overwrite:
+		if os.path.lexists(outfile) and ask_overwrite:
 			confirm_or_raise('',f'File {outfile!r} already exists\nOverwrite?')
 			confirm_or_raise('',f'File {outfile!r} already exists\nOverwrite?')
 			msg(f'Overwriting file {outfile!r}')
 			msg(f'Overwriting file {outfile!r}')
 			hush = True
 			hush = True
@@ -719,7 +707,8 @@ def mmgen_decrypt_file_maybe(fn,desc='',quiet=False,silent=False):
 def get_lines_from_file(fn,desc='',trim_comments=False,quiet=False,silent=False):
 def get_lines_from_file(fn,desc='',trim_comments=False,quiet=False,silent=False):
 	dec = mmgen_decrypt_file_maybe(fn,desc,quiet=quiet,silent=silent)
 	dec = mmgen_decrypt_file_maybe(fn,desc,quiet=quiet,silent=silent)
 	ret = dec.decode().splitlines()
 	ret = dec.decode().splitlines()
-	if trim_comments: ret = remove_comments(ret)
+	if trim_comments:
+		ret = strip_comments(ret)
 	dmsg(f'Got {len(ret)} lines from file {fn!r}')
 	dmsg(f'Got {len(ret)} lines from file {fn!r}')
 	return ret
 	return ret
 
 

+ 1 - 1
test/test_py_d/ts_input.py

@@ -202,7 +202,7 @@ class TestSuiteInput(TestSuiteBase):
 		if wcls.wclass == 'mnemonic':
 		if wcls.wclass == 'mnemonic':
 			mn = mn or read_from_file(wf).strip().split()
 			mn = mn or read_from_file(wf).strip().split()
 		elif wcls.wclass == 'dieroll':
 		elif wcls.wclass == 'dieroll':
-			mn = mn or list(read_from_file(wf).strip().translate(dict((ord(ws),None) for ws in '\t\n ')))
+			mn = mn or list(remove_whitespace(read_from_file(wf)))
 			for idx,val in ((5,'x'),(18,'0'),(30,'7'),(44,'9')):
 			for idx,val in ((5,'x'),(18,'0'),(30,'7'),(44,'9')):
 				mn.insert(idx,val)
 				mn.insert(idx,val)
 		t = self.spawn('mmgen-walletconv',['-r10','-S','-i',fmt,'-o',out_fmt or fmt])
 		t = self.spawn('mmgen-walletconv',['-r10','-S','-i',fmt,'-o',out_fmt or fmt])