def launch_askpass(password=None, quiet=False, verbose=False, logfile=os.devnull, *args, **kwargs): # pylint: disable=unused-argument,keyword-arg-before-vararg text = 'Launching MacDaily SSH-AskPass program' print_info(text, logfile, quiet) path = f'Macintosh HD{ROOT.replace(os.path.sep, ":")}:img:askpass.icns' ASKPASS = ['#!/usr/bin/env osascript', '', '-- script based on https://github.com/theseal/ssh-askpass', '', 'on run argv', ' set args to argv as text', ' if args starts with "--help" or args starts with "-h" then', ' return "macdaily-askpass [-h|--help] [prompt]"', ' end if', f' display dialog args with icon file ("{path}") default button "OK" default answer "" with hidden answer', # pylint: disable=line-too-long " return result's text returned", 'end run', ''] askpass = os.path.join(ROOT, 'res', 'askpass.applescript') text = f'Making executable {askpass!r}' print_misc(text, logfile, verbose) user = owner = getpass.getuser() if os.path.isfile(askpass): owner = pwd.getpwuid(os.stat(askpass).st_uid).pw_name if user != owner: run_script(['chown', user, askpass], quiet, verbose, sudo=True, password=password, logfile=logfile) else: try: pathlib.Path(askpass).touch() except PermissionError: owner = 'root' run_script(['touch', askpass], quiet, verbose, sudo=True, password=password, logfile=logfile) run_script(['chown', user, askpass], quiet, verbose, sudo=True, password=password, logfile=logfile) with open(askpass, 'w') as file: file.write(os.linesep.join(ASKPASS)) if user != owner: run_script(['chmod', '+x', askpass], quiet, verbose, sudo=True, password=password, logfile=logfile) run_script(['chown', owner, askpass], quiet, verbose, sudo=True, password=password, logfile=logfile) else: run_script(['chmod', '+x', askpass], quiet, verbose, logfile=logfile) return askpass
def launch_confirm(password=None, quiet=False, verbose=False, logfile=os.devnull, *args, **kwargs): # pylint: disable=unused-argument,keyword-arg-before-vararg text = 'Launching MacDaily Confirmation program' print_info(text, logfile, quiet) path = f'Macintosh HD{ROOT.replace(os.path.sep, ":")}:img:confirm.icns' ASKPASS = ['#!/usr/bin/env osascript', '', 'on run argv', ' set args to argv as text', ' if args starts with "--help" or args starts with "-h" then', ' return "macdaily-confirm [-h|--help] [prompt]"', ' end if', f' display dialog args with icon file ("{path}") default button "Cancel"', " return result's button returned", 'end run', ''] confirm = os.path.join(ROOT, 'res', 'confirm.applescript') text = f'Making executable {confirm!r}' print_misc(text, logfile, verbose) user = owner = getpass.getuser() if os.path.isfile(confirm): owner = pwd.getpwuid(os.stat(confirm).st_uid).pw_name if user != owner: run_script(['chown', user, confirm], quiet, verbose, sudo=True, password=password, logfile=logfile) else: try: pathlib.Path(confirm).touch() except PermissionError: owner = 'root' run_script(['touch', confirm], quiet, verbose, sudo=True, password=password, logfile=logfile) run_script(['chown', user, confirm], quiet, verbose, sudo=True, password=password, logfile=logfile) with open(confirm, 'w') as file: file.write(os.linesep.join(ASKPASS)) if user != owner: run_script(['chmod', '+x', confirm], quiet, verbose, sudo=True, password=password, logfile=logfile) run_script(['chown', owner, confirm], quiet, verbose, sudo=True, password=password, logfile=logfile) else: run_script(['chmod', '+x', confirm], quiet, verbose, logfile=logfile) return confirm
def record(file, args, today, config=None, redirect=False): # record program arguments print_misc(f'{PYTHON} {PROGRAM}', file, redirect) with open(file, 'a') as log: log.writelines([f'TIME: {today!s}\n', f'FILE: {file}\n']) # record parsed arguments print_misc('Parsing command line arguments', file, redirect) with open(file, 'a') as log: for key, value in vars(args).items(): if isinstance(value, dict): for k, v, in value.items(): if v is None: v = 'null' log.write(f'ARG: {key} -> {k} = {v}\n') else: if value is None: value = 'null' log.write(f'ARG: {key} = {value}\n') # record parsed configuration file if config is not None: print_misc( f'Parsing configuration file ' f'{os.path.expanduser("~/.dailyrc")!r}', file, redirect) with open(file, 'a') as log: for key, value in config.items(): for k, v, in value.items(): if v is None: v = 'null' log.write(f'CFG: {key} -> {k} = {v}\n') # record parsed environment variables print_misc('Parsing environment variables', file, redirect) with open(file, 'a') as log: print_environ(log, value_only=True, no_term=True, prefix='ENV: ', suffix=' = %s')
def install(argv=None): # parse args & set context redirection flags args = parse_args(argv) quiet = args.quiet verbose = (args.quiet or not args.verbose) # parse config & change environ config = parse_config(quiet, verbose) os.environ['SUDO_ASKPASS'] = config['Miscellaneous']['askpass'] # fetch current time today = datetime.datetime.today() logdate = datetime.date.strftime(today, r'%y%m%d') logtime = datetime.date.strftime(today, r'%H%M%S') # mkdir for logs logpath = pathlib.Path( os.path.join(config['Path']['logdir'], 'install', logdate)) logpath.mkdir(parents=True, exist_ok=True) # prepare command paras filename = os.path.join(logpath, f'{logtime}-{uuid.uuid4()!s}.log') os.environ['MACDAILY_LOGFILE'] = filename confirm = config['Miscellaneous']['confirm'] askpass = config['Miscellaneous']['askpass'] timeout = config['Miscellaneous']['limit'] disk_dir = config['Path']['arcdir'] brew_renew = None # record program status text = f'{bold}{green}|π¨|{reset} {bold}Running MacDaily version {__version__}{reset}' print_term(text, filename, redirect=quiet) record(filename, args, today, config, redirect=verbose) # ask for password text = f'{bold}{purple}|π|{reset} {bold}Your {under}sudo{reset}{bold} password may be necessary{reset}' print_term(text, filename, redirect=quiet) password = get_pass(askpass) cmd_list = list() for mode in {'apm', 'brew', 'cask', 'gem', 'mas', 'npm', 'pip', 'system'}: # skip disabled commands if not config['Mode'].get(mode, False): text = f'macdaily-install: {yellow}{mode}{reset}: command disabled' print_term(text, filename, redirect=verbose) continue # skip commands with no package spec packages = getattr(args, f'{mode}_pkgs', list()) namespace = getattr(args, mode, None) if not (packages or namespace): text = f'macdaily-install: {yellow}{mode}{reset}: nothing to install' print_term(text, filename, redirect=verbose) continue # update package specifications if namespace is None: namespace = dict(vars(args), packages=list()) namespace['packages'].extend(packages) # check master controlling flags if args.yes: namespace['yes'] = True if args.quiet: namespace['quiet'] = True if args.verbose: namespace['verbose'] = True if args.no_cleanup: namespace['no_cleanup'] = True # run command cmd_cls = globals()[f'{mode.capitalize()}Install'] command = cmd_cls(make_namespace(namespace), filename, timeout, confirm, askpass, password, disk_dir, brew_renew) # record command cmd_list.append(command) brew_renew = command.time archive = None if not args.no_cleanup: archive = make_archive(config, 'install', today, quiet=quiet, verbose=verbose, logfile=filename) text = f'{bold}{green}|π|{reset} {bold}MacDaily report of install command{reset}' print_term(text, filename, redirect=quiet) for command in cmd_list: desc = make_description(command) pkgs = f'{reset}{bold}, {green}'.join(command.packages) fail = f'{reset}{bold}, {red}'.join(command.failed) if pkgs: flag = (len(pkgs) == 1) text = f'Installed following {under}{desc(flag)}{reset}{bold}: {green}{pkgs}{reset}' print_misc(text, filename, redirect=quiet) else: text = f'No {under}{desc(False)}{reset}{bold} installed' print_misc(text, filename, redirect=quiet) if fail: flag = (len(fail) == 1) text = f'Installation of following {under}{desc(flag)}{reset}{bold} failed: {red}{fail}{reset}' print_misc(text, filename, redirect=quiet) else: verb, noun = ('s', '') if len(fail) == 1 else ('', 's') text = f'All {under}{desc(False)}{reset}{bold} installation{noun} succeed{verb}' print_misc(text, filename, redirect=verbose) if archive: formatted_list = f'{reset}{bold}, {under}'.join(archive) text = ( f'Archived following ancient logs: {under}{formatted_list}{reset}') print_misc(text, filename, redirect=quiet) if len(cmd_list) == 0: # pylint: disable=len-as-condition text = f'macdaily: {purple}install{reset}: no packages installed' print_term(text, filename, redirect=quiet) if args.show_log: try: subprocess.check_call([ 'open', '-a', '/Applications/Utilities/Console.app', filename ]) except subprocess.CalledProcessError: print_text(traceback.format_exc(), filename, redirect=verbose) print( f'macdaily: {red}install{reset}: cannot show log file {filename!r}', file=sys.stderr) mode_lst = [command.mode for command in cmd_list] mode_str = ', '.join(mode_lst) if mode_lst else 'none' text = ( f'{bold}{green}|πΊ|{reset} {bold}MacDaily successfully performed install process ' f'for {mode_str} package managers{reset}') print_term(text, filename, redirect=quiet)
def launch_daemons(config, password, quiet=False, verbose=False, logfile=os.devnull): text = 'Launching MacDaily LaunchAgent program' print_info(text, logfile, quiet) def make_daemon(mode, argv): DAEMON = ['#!/usr/bin/env osascript', '', '-- show notification', f'display notification "Running scheduled {mode} scripts..." with title "MacDaily"', '', '-- run script', f'do shell script "{PYTHON} -m macdaily {mode} {argv}"', ''] return os.linesep.join(DAEMON) # Property List osascript = shutil.which('osascript') PLIST_BASE = collections.OrderedDict( Label=str(), UserName=getpass.getuser(), Program=osascript, ProgramArguments=[osascript, ''], # RunAtLoad=True, RootDirectory=str(pathlib.Path.home()), EnvironmentVariables=dict(os.environ), StartCalendarInterval=list(), StandardOutPath=str(), StandardErrorPath=str(), ) library = os.path.expanduser('~/Library/LaunchAgents/') os.makedirs(library, exist_ok=True) root = pathlib.Path(config['Path']['logdir']) for mode, time in config['Daemon'].items(): (root / mode).mkdir(parents=True, exist_ok=True) name = f'com.macdaily.{mode}' path = os.path.join(ROOT, 'res', f'daemon-{mode}.applescript') pout = str(root / mode / 'stdout.log') perr = str(root / mode / 'stderr.log') argv = ' '.join(config['Command'].get(mode, ['--help'])) text = f'Adding {under}{mode}{reset}{bold} command LaunchAgent {name!r}' print_misc(text, logfile, quiet) user = owner = getpass.getuser() if os.path.isfile(path): owner = pwd.getpwuid(os.stat(path).st_uid).pw_name if user != owner: run_script(['chown', user, path], quiet, verbose, sudo=True, password=password, logfile=logfile) else: try: pathlib.Path(path).touch() except PermissionError: owner = 'root' run_script(['touch', path], quiet, verbose, sudo=True, password=password, logfile=logfile) run_script(['chown', user, path], quiet, verbose, sudo=True, password=password, logfile=logfile) with open(path, 'w') as file: file.write(make_daemon(mode, argv)) run_script(['chmod', '+x', path], quiet, verbose, sudo=True, password=password, logfile=logfile) if user != owner: run_script(['chown', owner, path], quiet, verbose, sudo=True, password=password, logfile=logfile) PLIST = copy.copy(PLIST_BASE) PLIST['Label'] = name PLIST['ProgramArguments'][1] = path PLIST['StartCalendarInterval'] = time PLIST['StandardOutPath'] = pout PLIST['StandardErrorPath'] = perr plist = os.path.join(library, f'{name}.plist') text = f'Adding Launch Agent {name!r}' print_misc(text, logfile, verbose) if os.path.exists(plist): run_script(['launchctl', 'unload', '-w', plist], quiet, verbose, logfile=logfile) with open(plist, 'wb') as file: plistlib.dump(PLIST, file, sort_keys=False) run_script(['launchctl', 'load', '-w', plist], quiet, verbose, logfile=logfile) return library
def launch(argv=None): # parse args & set context redirection flags args = parse_args(argv) quiet = args.quiet verbose = (args.quiet or not args.verbose) # parse config & change environ config = parse_config(quiet, verbose) os.environ['SUDO_ASKPASS'] = config['Miscellaneous']['askpass'] # fetch current time today = datetime.datetime.today() logdate = datetime.date.strftime(today, r'%y%m%d') logtime = datetime.date.strftime(today, r'%H%M%S') # mkdir for logs logpath = pathlib.Path(os.path.join(config['Path']['logdir'], 'launch', logdate)) logpath.mkdir(parents=True, exist_ok=True) # prepare command paras filename = os.path.join(logpath, f'{logtime}-{uuid.uuid4()!s}.log') os.environ['MACDAILY_LOGFILE'] = filename askpass = config['Miscellaneous']['askpass'] # record program status text = f'{bold}{green}|π¨|{reset} {bold}Running MacDaily version {__version__}{reset}' print_term(text, filename, redirect=quiet) record(filename, args, today, config, redirect=verbose) # ask for password text = f'{bold}{purple}|π|{reset} {bold}Your {under}sudo{reset}{bold} password may be necessary{reset}' print_term(text, filename, redirect=quiet) password = get_pass(askpass) # update program list if args.all: args.program.extend(('askpass', 'confirm', 'daemons')) prog_dict = dict() for program in set(args.program): if re.match(r'^(askpass|confirm|daemons)$', program, re.IGNORECASE) is None: parser = get_launch_parser() parser.error(f"argument PROG: invalid choice: {program!r} (choose from 'askpass', 'confirm', 'daemons')") # launch program launch_func = globals()[f'launch_{program.lower()}'] path = launch_func(quiet=quiet, verbose=verbose, config=config, password=password, logfile=filename) # record program prog_dict[program] = path archive = None if not args.no_cleanup: archive = make_archive(config, 'launch', today, quiet=quiet, verbose=verbose, logfile=filename) text = f'{bold}{green}|π|{reset} {bold}MacDaily report of launch command{reset}' print_term(text, filename, redirect=quiet) for prog, path in prog_dict.items(): text = f'Launched helper program {under}{prog}{reset}{bold} at {under}{path}{reset}' print_misc(text, filename, redirect=quiet) if archive: formatted_list = f'{reset}{bold}, {under}'.join(archive) text = (f'Archived following ancient logs: {under}{formatted_list}{reset}') print_misc(text, filename, redirect=quiet) if len(prog_dict) == 0: text = f'macdaily: {purple}launch{reset}: no program launched' print_term(text, filename, redirect=quiet) if args.show_log: try: subprocess.check_call(['open', '-a', '/Applications/Utilities/Console.app', filename]) except subprocess.CalledProcessError: print_text(traceback.format_exc(), filename, redirect=verbose) print(f'macdaily: {red}launch{reset}: cannot show log file {filename!r}', file=sys.stderr) mode_str = ', '.join(prog_dict) if prog_dict else 'none' text = (f'{bold}{green}|πΊ|{reset} {bold}MacDaily successfully performed launch process ' f'for {mode_str} helper programs{reset}') print_term(text, filename, redirect=quiet)
def logging(argv=None): # parse args & set context redirection flags args = parse_args(argv) quiet = args.quiet verbose = (args.quiet or not args.verbose) # parse config & change environ config = parse_config(quiet, verbose) os.environ['SUDO_ASKPASS'] = config['Miscellaneous']['askpass'] # fetch current time today = datetime.datetime.today() logdate = datetime.date.strftime(today, r'%y%m%d') logtime = datetime.date.strftime(today, r'%H%M%S') # prepare command paras confirm = config['Miscellaneous']['confirm'] askpass = config['Miscellaneous']['askpass'] timeout = config['Miscellaneous']['limit'] disk_dir = config['Path']['arcdir'] brew_renew = None # record program status text_record = f'{bold}{green}|π¨|{reset} {bold}Running MacDaily version {__version__}{reset}' print_term(text_record, get_logfile(), redirect=quiet) record(get_logfile(), args, today, config, redirect=verbose) # ask for password text_askpass = f'{bold}{purple}|π|{reset} {bold}Your {under}sudo{reset}{bold} password may be necessary{reset}' print_term(text_askpass, get_logfile(), redirect=quiet) password = get_pass(askpass) cmd_list = list() log_list = list() file_list = list() for mode in { 'apm', 'app', 'brew', 'cask', 'gem', 'mas', 'npm', 'pip', 'tap' }: # mkdir for logs logpath = pathlib.Path( os.path.join(config['Path']['logdir'], 'logging', mode, logdate)) logpath.mkdir(parents=True, exist_ok=True) filename = os.path.join(logpath, f'{logtime}-{uuid.uuid4()!s}.log') os.environ['MACDAILY_LOGFILE'] = filename # redo program status records print_term(text_record, filename, redirect=True) record(filename, args, today, config, redirect=True) print_term(text_askpass, filename, redirect=True) # skip disabled commands if (not config['Mode'].get(mode, False)) or getattr( args, f'no_{mode}', False): text = f'macdaily-logging: {yellow}{mode}{reset}: command disabled' print_term(text, filename, redirect=verbose) continue # update logging specifications namespace = getattr(args, mode, vars(args)) # check master controlling flags if args.quiet: namespace['quiet'] = True if args.verbose: namespace['verbose'] = True if args.show_log: namespace['show_log'] = True if args.no_cleanup: namespace['no_cleanup'] = True # run command cmd_cls = globals()[f'{mode.capitalize()}Logging'] command = cmd_cls(make_namespace(namespace), filename, timeout, confirm, askpass, password, disk_dir, brew_renew) # record command cmd_list.append(command) log_list.append(filename) brew_renew = command.time if not namespace['no_cleanup']: archive = make_archive(config, f'logging/{mode}', today, zipfile=False, quiet=quiet, verbose=verbose, logfile=filename) file_list.extend(archive) if namespace.get('show_log', False): try: subprocess.check_call([ 'open', '-a', '/Applications/Utilities/Console.app', filename ]) except subprocess.CalledProcessError: print_text(traceback.format_exc(), filename, redirect=verbose) print( f'macdaily: {red}logging{reset}: cannot show log file {filename!r}', file=sys.stderr) if not args.no_cleanup: storage = make_storage(config, today, quiet=quiet, verbose=verbose, logfile=filename) file_list.extend(storage) text = f'{bold}{green}|π|{reset} {bold}MacDaily report of logging command{reset}' print_term(text, get_logfile(), redirect=quiet) for file in log_list: print_term(text, file, redirect=True) for command in cmd_list: text = f'Recorded existing {under}{command.desc[1]}{reset}{bold} at {under}{command.sample}{reset}' print_misc(text, get_logfile(), redirect=quiet) for file in log_list: print_misc(text, file, redirect=True) if file_list: formatted_list = f'{reset}{bold}, {under}'.join(file_list) text = ( f'Archived following ancient logs: {under}{formatted_list}{reset}') print_misc(text, filename, redirect=quiet) if len(cmd_list) == 0: # pylint: disable=len-as-condition text = f'macdaily: {purple}logging{reset}: no packages recorded' print_term(text, get_logfile(), redirect=quiet) for file in log_list: print_term(text, file, redirect=True) mode_lst = [command.mode for command in cmd_list] mode_str = ', '.join(mode_lst) if mode_lst else 'none' text = ( f'{bold}{green}|πΊ|{reset} {bold}MacDaily successfully performed logging process ' f'for {mode_str} package managers{reset}') print_term(text, get_logfile(), redirect=quiet) for file in log_list: print_term(text, file, redirect=True)
def make_config(quiet=False, verbose=False): if not sys.stdin.isatty(): raise OSError(5, 'Input/output error') print_wrap(f'Entering interactive command line setup procedure...') print_wrap(f'Default settings are shown as in the square brackets.') print_wrap( f'Please directly {bold}{under}ENTER{reset} if you prefer the default settings.' ) rcpath = os.path.expanduser('~/.dailyrc') try: with open(rcpath, 'w') as config_file: config_file.writelines( map(lambda s: f'{s}{os.linesep}', CONFIG[:4])) # pylint: disable=map-builtin-not-iterating print() print_wrap( f'For logging utilities, we recommend you to set up your {bold}hard disk{reset} path.' ) print_wrap( f'You may change other path preferences in configuration `{under}~/.dailyrc{reset}` later.' ) print_wrap( f'Please note that all paths must be valid under all circumstances.' ) dskdir = input('Name of your external hard disk []: ').ljust(41) config_file.write( f'dskdir = /Volumes/{dskdir} ; path where your hard disk lies\n' ) config_file.writelines( map(lambda s: f'{s}{os.linesep}', CONFIG[5:38])) # pylint: disable=map-builtin-not-iterating print() print_wrap( f'In default, we will run {bold}update{reset} and {bold}logging{reset} commands twice a day.' ) print_wrap( f'You may change daily commands preferences in configuration `{under}~/.dailyrc{reset}` later.' ) print_wrap( f'Please enter schedule as {bold}{under}HH:MM[-CMD]{reset} format, ' f'and each separates with {under}comma{reset}.') timing = input( 'Time for daily scripts [10:00-update,22:30-logging,23:00-archive]: ' ) if timing: config_file.writelines([ '\t', '\n\t'.join(map(lambda s: s.strip(), timing.split(','))), '\n' ]) else: config_file.writelines( map(lambda s: f'{s}{os.linesep}', CONFIG[38:41])) # pylint: disable=map-builtin-not-iterating config_file.writelines( map(lambda s: f'{s}{os.linesep}', CONFIG[41:52])) # pylint: disable=map-builtin-not-iterating print() print_wrap( f'For better stability, {bold}MacDaily{reset} depends on several helper programs.' ) print_wrap( 'Your password may be necessary during the launch process.') askpass = launch_askpass(quiet=quiet, verbose=verbose) confirm = launch_confirm(quiet=quiet, verbose=verbose) config_file.write( f'askpass = {askpass.ljust(49)} ; SUDO_ASKPASS utility for Homebrew Casks\n' ) config_file.write( f'confirm = {confirm.ljust(49)} ; confirm utility for MacDaily\n' ) print() print_wrap( f'Also, {bold}MacDaily{reset} supports several different environment setups.' ) print_wrap( 'You may set up these variables here, ' f'or later manually in configuration `{under}~/.dailyrc{reset}`.' ) print_wrap( f'Please enter these specifications as instructed below.') shtout = ( input('Timeout limit for shell scripts in seconds [1,000]: ') or '1000').ljust(49) config_file.write( f'limit = {shtout} ; timeout limit for shell scripts in seconds\n' ) retout = (input('Retry timeout for input prompts in seconds [60]:') or '60').ljust(49) config_file.write( f'retry = {retout} ; retry timeout for input prompts in seconds\n' ) print() print_wrap( f'Configuration for {bold}MacDaily{reset} finished. Now launching...\n' ) except BaseException: os.remove(rcpath) print(reset) raise # parse config config = parse_config(quiet, verbose) askpass = config['Miscellaneous']['askpass'] # ask for password text = f'{bold}{purple}|Γ°ΕΈββ|{reset} {bold}Your {under}sudo{reset}{bold} password may be necessary{reset}' print_term(text, get_logfile(), redirect=quiet) password = get_pass(askpass) # launch daemons path = launch_daemons(config, password, quiet, verbose) text = f'Launched helper program {under}daemons{reset}{bold} at {under}{path}{reset}' print_misc(text, get_logfile(), redirect=quiet)
def archive(argv=None): # parse args & set context redirection flags args = parse_args(argv) quiet = args.quiet verbose = (args.quiet or not args.verbose) # parse config & change environ config = parse_config(quiet, verbose) os.environ['SUDO_ASKPASS'] = config['Miscellaneous']['askpass'] # fetch current time today = datetime.datetime.today() logdate = datetime.date.strftime(today, r'%y%m%d') logtime = datetime.date.strftime(today, r'%H%M%S') # mkdir for logs logpath = pathlib.Path( os.path.join(config['Path']['logdir'], 'archive', logdate)) logpath.mkdir(parents=True, exist_ok=True) # prepare command paras filename = os.path.join(logpath, f'{logtime}-{uuid.uuid4()!s}.log') os.environ['MACDAILY_LOGFILE'] = filename disk_dir = config['Path']['arcdir'] # record program status text = f'{bold}{green}|π¨|{reset} {bold}Running MacDaily version {__version__}{reset}' print_term(text, filename, redirect=quiet) record(filename, args, today, config, redirect=verbose) log_pth = { 'logging/apm', 'logging/app', 'logging/brew', 'logging/cask', 'logging/gem', 'logging/mas', 'logging/npm', 'logging/pip', 'logging/tap' } all_pth = log_pth | { 'archive', 'cleanup', 'dependency', 'postinstall', 'reinstall', 'tarfile', 'uninstall', 'update' } # update path list if args.all: args.path.extend(all_pth) if 'logging' in args.path: args.path.remove('logging') args.path.extend(log_pth) file_dict = dict() for mode in set(args.path): if mode not in all_pth: tmp_pth = all_pth.add('logging') with open(filename, 'a') as file: file.write(f'macdaily: archive: invalid option: {mode!r}') parser = get_archive_parser() parser.error( f"argument CMD: invalid choice: {mode!r} (choose from {', '.join(sorted(tmp_pth))})" ) # make archives file_list = make_archive(config, mode, today, zipfile=False, quiet=quiet, verbose=verbose) # record file list file_dict[mode] = copy.copy(file_list) storage = None if not args.no_storage: storage = make_storage(config, today, quiet=quiet, verbose=verbose) text = f'{bold}{green}|π|{reset} {bold}MacDaily report of archive command{reset}' print_term(text, filename, redirect=quiet) for mode, file_list in file_dict.items(): if file_list: formatted_list = f'{reset}{bold}, {under}'.join(file_list) text = f'Archived following ancient logs of {pink}{mode}{reset}{bold}: {under}{formatted_list}{reset}' else: text = f'No ancient logs of {under}{mode}{reset}{bold} archived' print_misc(text, filename, redirect=quiet) if len(file_dict) == 0: # pylint: disable=len-as-condition text = f'macdaily: {purple}archive{reset}: no logs archived' print_term(text, filename, redirect=quiet) if storage: formatted_list = f'{reset}{bold}, {under}'.join(storage) text = ( f'Stored following ancient archived into {pink}external hard disk{reset} ' f'{bold} at {under}{disk_dir}{reset}{bold}: {under}{formatted_list}{reset}' ) print_misc(text, filename, redirect=quiet) if args.show_log: try: subprocess.check_call([ 'open', '-a', '/Applications/Utilities/Console.app', filename ]) except subprocess.CalledProcessError: print_text(traceback.format_exc(), filename, redirect=verbose) print( f'macdaily: {red}archive{reset}: cannot show log file {filename!r}', file=sys.stderr) mode_str = ', '.join(file_dict) if file_dict else 'none' text = ( f'{bold}{green}|πΊ|{reset} {bold}MacDaily successfully performed archive process ' f'for {mode_str} helper programs{reset}') print_term(text, filename, redirect=quiet)
def postinstall(argv=None): # parse args & set context redirection flags args = parse_args(argv) quiet = args.quiet verbose = (args.quiet or not args.verbose) # parse config & change environ config = parse_config(quiet, verbose) os.environ['SUDO_ASKPASS'] = config['Miscellaneous']['askpass'] # fetch current time today = datetime.datetime.today() logdate = datetime.date.strftime(today, r'%y%m%d') logtime = datetime.date.strftime(today, r'%H%M%S') # mkdir for logs logpath = pathlib.Path( os.path.join(config['Path']['logdir'], 'postinstall', logdate)) logpath.mkdir(parents=True, exist_ok=True) # prepare command paras filename = os.path.join(logpath, f'{logtime}-{uuid.uuid4()!s}.log') os.environ['MACDAILY_LOGFILE'] = filename confirm = config['Miscellaneous']['confirm'] askpass = config['Miscellaneous']['askpass'] timeout = config['Miscellaneous']['limit'] disk_dir = config['Path']['arcdir'] brew_renew = None # record program status text = f'{bold}{green}|π¨|{reset} {bold}Running MacDaily version {__version__}{reset}' print_term(text, filename, redirect=quiet) record(filename, args, today, config, redirect=verbose) # ask for password text = f'{bold}{purple}|π|{reset} {bold}Your {under}sudo{reset}{bold} password may be necessary{reset}' print_term(text, filename, redirect=quiet) password = get_pass(askpass) # check if disabled enabled = (not config['Mode'].get('brew', False)) # run command if enabled: command = PostinstallCommand(make_namespace(args), filename, timeout, confirm, askpass, password, disk_dir, brew_renew) else: text = f'macdaily-postinstall: {yellow}brew{reset}: command disabled' print_term(text, filename, redirect=verbose) archive = None if not args.no_cleanup: archive = make_archive(config, 'postinstall', today, quiet=quiet, verbose=verbose, logfile=filename) text = f'{bold}{green}|π|{reset} {bold}MacDaily report of postinstall command{reset}' print_term(text, filename, redirect=quiet) if enabled: desc = make_description(command) pkgs = f'{reset}{bold}, {green}'.join(command.packages) miss = f'{reset}{bold}, {yellow}'.join(command.notfound) ilst = f'{reset}{bold}, {pink}'.join(command.ignored) fail = f'{reset}{bold}, {red}'.join(command.failed) if pkgs: flag = (len(pkgs) == 1) text = f'Postinstalled following {under}{desc(flag)}{reset}{bold}: {green}{pkgs}{reset}' print_misc(text, filename, redirect=quiet) else: text = f'No {under}{desc(False)}{reset}{bold} postinstalled' print_misc(text, filename, redirect=quiet) if fail: flag = (len(fail) == 1) text = f'Postinstallation of following {under}{desc(flag)}{reset}{bold} failed: {red}{fail}{reset}' print_misc(text, filename, redirect=quiet) else: verb, noun = ('s', '') if len(fail) == 1 else ('', 's') text = f'All {under}{desc(False)}{reset}{bold} postinstallation{noun} succeed{verb}' print_misc(text, filename, redirect=verbose) if ilst: flag = (len(ilst) == 1) text = f'Ignored postinstallation of following {under}{desc(flag)}{reset}{bold}: {pink}{ilst}{reset}' print_misc(text, filename, redirect=quiet) else: text = f'No {under}{desc(False)}{reset}{bold} ignored' print_misc(text, filename, redirect=verbose) if miss: flag = (len(miss) == 1) text = f'Following {under}{desc(flag)}{reset}{bold} not found: {yellow}{miss}{reset}' print_misc(text, filename, redirect=quiet) else: text = f'Hit all {under}{desc(False)}{reset}{bold} specifications' print_misc(text, filename, redirect=verbose) if archive: formatted_list = f'{reset}{bold}, {under}'.join(archive) text = ( f'Archived following ancient logs: {under}{formatted_list}{reset}') print_misc(text, filename, redirect=quiet) if not enabled: text = f'macdaily: {purple}postinstall{reset}: no Homebrew formulae postinstalled' print_term(text, filename, redirect=quiet) if args.show_log: try: subprocess.check_call([ 'open', '-a', '/Applications/Utilities/Console.app', filename ]) except subprocess.CalledProcessError: print_text(traceback.format_exc(), filename, redirect=verbose) print( f'macdaily: {red}postinstall{reset}: cannot show log file {filename!r}', file=sys.stderr) text = ( f'{bold}{green}|πΊ|{reset} {bold}MacDaily successfully performed postinstall process{reset}' ) print_term(text, filename, redirect=quiet)