Browse Source

led.py: chmod the control files automatically if possible

The MMGen Project 6 months ago
parent
commit
2b4ecd8455
2 changed files with 22 additions and 12 deletions
  1. 17 9
      mmgen/led.py
  2. 5 3
      test/cmdtest_py_d/ct_autosign.py

+ 17 - 9
mmgen/led.py

@@ -22,8 +22,10 @@ led: Control the LED on a single-board computer
 
 import os,threading
 from collections import namedtuple
+from subprocess import run
 
-from .util import msg,msg_r,fmt,die
+from .util import msg, msg_r, fmt, die, have_sudo
+from .color import orange
 
 class LEDControl:
 
@@ -81,20 +83,26 @@ class LEDControl:
 			msg(f'\n  Status file:  {board.status}\n  Trigger file: {board.trigger}')
 
 		def check_access(fn,desc,init_val=None):
-			try:
+
+			def write_init_val(init_val):
 				if not init_val:
 					with open(fn) as fp:
 						init_val = fp.read().strip()
 				with open(fn,'w') as fp:
 					fp.write(f'{init_val}\n')
-				return True
-			except PermissionError:
-				die(2,'\n'+fmt(f"""
-					You do not have access to the {desc} file
-					To allow access, run the following command:
 
-					    sudo chmod 0666 {fn}
-				""",indent='  ',strip_char='\t'))
+			try:
+				write_init_val(init_val)
+			except PermissionError:
+				cmd = f'sudo chmod 0666 {fn}'
+				if have_sudo():
+					msg(orange(f'Running ‘{cmd}’'))
+					run(cmd.split(), check=True)
+					write_init_val(init_val)
+				else:
+					die(2,
+						f'\nYou do not have access to the {desc} file\n'
+						f'To allow access, run the following command:\n\n    {cmd}')
 
 		check_access(board.status,desc='status LED control')
 

+ 5 - 3
test/cmdtest_py_d/ct_autosign.py

@@ -595,6 +595,11 @@ class CmdTestAutosign(CmdTestAutosignBase):
 
 		if self.simulate_led:
 			LEDControl.create_dummy_control_files()
+			db = LEDControl.boards['dummy']
+			usrgrp = {'linux': 'root:root', 'darwin': 'root:wheel'}[sys.platform]
+			for fn in (db.status, db.trigger): # trigger the auto-chmod feature
+				run(f'sudo chmod 644 {fn}'.split(), check=True)
+				run(f'sudo chown {usrgrp} {fn}'.split(), check=True)
 			self.have_dummy_control_files = True
 			self.spawn_env['MMGEN_TEST_SUITE_AUTOSIGN_LED_SIMULATE'] = '1'
 
@@ -922,9 +927,6 @@ class CmdTestAutosignLive(CmdTestAutosignBTC):
 		except Exception as e:
 			msg(str(e))
 			die(2,'LEDControl initialization failed')
-		for path in (cf.board.status,cf.board.trigger):
-			if path:
-				run(['sudo','chmod','0666',path],check=True)
 
 	def run_setup_mmgen(self):
 		return self.run_setup(mn_type='mmgen',use_dfl_wallet=None)