Skip to content

Instantly share code, notes, and snippets.

@svenXY
Last active July 1, 2020 14:56
Show Gist options
  • Save svenXY/b95efa9a1c350f6187ad3139d16d0714 to your computer and use it in GitHub Desktop.
Save svenXY/b95efa9a1c350f6187ad3139d16d0714 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""
Usage: %(scriptName)s --help -> get help
Make a backup of the nethack save file (this is cheating!)
or choose one of the already backed up savegames to restore.
Nethack must not be running while using this script!
Happy slaying,
Sven Hergenhahn https://github.com/svenXY
"""
import argparse
import os
import sys
import shutil
from pathlib import Path
from datetime import datetime
# set your paths here -
# SAVEDIR will be created if it does not yet exist
NH_PLAYGROUND = Path("/usr/local/share/nethack/save")
SAVEDIR = Path("~/nethack/savegames").expanduser()
def parse_args():
parser = argparse.ArgumentParser(description='Backup or restore a nethack savegame')
group = parser.add_mutually_exclusive_group()
group.add_argument('--backup', '-b', dest='action',
help='backup a save game (=default)', action='store_const', const='backup', default='backup')
group.add_argument('--restore', '-r', dest='action',
help='restore a saved game', action='store_const', const='restore')
parser.add_argument('message', nargs='*', default=[])
return parser.parse_args()
def make_menu(files):
for idx, val in enumerate(files):
print(f'{idx:<3} {val.name}')
print()
try:
idx = input('\n'.join(['Gib eine Nummer ein, ',
'<return> für die neueste Datei',
'oder <ctrl-c> um abzubrechen: ']))
except KeyboardInterrupt:
print('\nNever mind.')
sys.exit()
if idx:
return files[int(idx)]
return files[-1]
def restore_file(rest_file):
if rest_file.is_file():
dest_name = rest_file.name.split('_')[1]
dest_path = Path(os.path.join(NH_PLAYGROUND, dest_name))
try:
shutil.copy(rest_file, dest_path)
shutil.chown(dest_path, group='admin')
os.chmod(dest_path, 0o660)
print(f'{rest_file} has been restored')
except OSError as e_msg:
print(f'Failed to restore {rest_file}: {e_msg}')
else:
print(f'Not a file: {rest_file}. Exit')
def backup_file(message):
os.makedirs(SAVEDIR, exist_ok=True)
save_game = sorted(NH_PLAYGROUND.glob('*.Z'), key=os.path.getmtime)[-1]
if save_game.is_file():
date_format = datetime.now().strftime('%Y-%m-%d-%H-%M')
if message:
msg = '_'.join(message)
else:
msg = 'nomsg'
bck_file = '_'.join([date_format, msg, save_game.name])
try:
shutil.copy(save_game, os.path.join(SAVEDIR, bck_file))
print(f'{bck_file} has been backed up')
except OSError as e_msg:
print(f'Failed to backup {bck_file}: {e_msg}')
else:
print(f'Not a file: {save_game}. Exit')
if __name__ == "__main__":
args = parse_args()
if args.action == 'backup':
backup_file(args.message)
elif args.action == 'restore':
all_backups = sorted(SAVEDIR.glob('*.Z'), key=os.path.getmtime)
my_restore = make_menu(all_backups)
restore_file(my_restore)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment