Skip to content

Commit

Permalink
Update feature is added #45 (#54)
Browse files Browse the repository at this point in the history
  • Loading branch information
jasursadikov authored Sep 6, 2024
1 parent 3c2814e commit cd744f0
Show file tree
Hide file tree
Showing 5 changed files with 82 additions and 32 deletions.
8 changes: 7 additions & 1 deletion .github/workflows/main.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -87,4 +87,10 @@ jobs:
- name: Test branch filtering
run: |
./mud.sh -l=label_1 git checkout -b develop
./mud.sh -b=develop echo "Hello world"
./mud.sh -b=develop echo "Hello world"
- name: Test update feature
run: |
./mud.sh update
# git reset --hard HEAD^1
# ./mud.sh update
# git pull --force
3 changes: 3 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#!/usr/bin/env python3
import sys

import utils
import settings
Expand All @@ -8,6 +9,8 @@
try:
utils.settings = settings.Settings(utils.SETTINGS_FILE_NAME)
utils.set_up()
if utils.settings.config['mud'].getboolean('ask_updates') and utils.check_updates():
sys.exit()
mud = Mud()
mud.run()
except KeyboardInterrupt:
Expand Down
34 changes: 11 additions & 23 deletions mud.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
# Commands
COMMANDS = {
'help': ['help', '--help', '-h'],
'update': ['update'],
'configure': ['configure', 'config'],
'version': ['--version', '-v', 'version'],
'set-global': ['--set-global'],
Expand Down Expand Up @@ -46,6 +47,7 @@ def _create_parser() -> ArgumentParser:
subparsers = parser.add_subparsers(dest='command')

subparsers.add_parser(COMMANDS['configure'][0], aliases=COMMANDS['configure'][1:], help='Runs the interactive configuration wizard.')
subparsers.add_parser(COMMANDS['update'][0], aliases=COMMANDS['update'][1:], help='Update mud to the latest version.')
subparsers.add_parser(COMMANDS['init'][0], aliases=COMMANDS['init'][1:], help=f'Initializes the {STYLES["bold"]}.mudconfig{RESET} and adds all repositories in this directory to {STYLES["bold"]}.mudconfig{RESET}.')
subparsers.add_parser(COMMANDS['info'][0], aliases=COMMANDS['info'][1:], help='Displays branch divergence and working directory changes')
subparsers.add_parser(COMMANDS['log'][0], aliases=COMMANDS['log'][1:], help='Displays log of latest commit messages for all repositories in a table view.')
Expand Down Expand Up @@ -92,6 +94,9 @@ def run(self) -> None:
elif sys.argv[1] in COMMANDS['configure']:
self.configure()
return
elif sys.argv[1] in COMMANDS['update']:
utils.check_updates(True)
return

current_directory = os.getcwd()
self.config = config.Config()
Expand Down Expand Up @@ -170,29 +175,12 @@ def init(self, args) -> None:
self.config.save(utils.CONFIG_FILE_NAME)

def configure(self):
def ask(text: str) -> bool:
print(f"{text} [Y/n]", end='', flush=True)
if sys.platform.startswith('win'):
from msvcrt import getch
response = getch().decode().lower()
else:
import tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(fd)
response = sys.stdin.read(1).lower()
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)

print() # Move to new line after key press
return response in ['y', '\r', '\n']

utils.settings.config['mud']['run_async'] = str(ask('Do you want to run commands simultaneously for multiple repositories?'))
utils.settings.config['mud']['run_table'] = str(ask('Do you want to see command execution progress in table view? This will limit output content.'))
utils.settings.config['mud']['auto_fetch'] = str(ask(f'Do you want to automatically run {STYLES["bold"]}\'git fetch\'{RESET} whenever you run commands such as {STYLES["bold"]}\'mud info\'{RESET}?'))
utils.settings.config['mud']['nerd_fonts'] = str(ask(f'Do you want to use {STYLES["bold"]}nerd-fonts{RESET}?'))
utils.settings.config['mud']['simplify_branches'] = str(ask(f'Do you want to simplify branches? (ex. {STYLES["bold"]}feature/name{RESET} -> {STYLES["bold"]}f/name{RESET}'))
utils.settings.config['mud']['run_async'] = str(utils.ask('Do you want to run commands simultaneously for multiple repositories?'))
utils.settings.config['mud']['run_table'] = str(utils.ask('Do you want to see command execution progress in table view? This will limit output content.'))
utils.settings.config['mud']['auto_fetch'] = str(utils.ask(f'Do you want to automatically run {STYLES["bold"]}\'git fetch\'{RESET} whenever you run commands such as {STYLES["bold"]}\'mud info\'{RESET}?'))
utils.settings.config['mud']['ask_updates'] = str(utils.ask(f'Do you want to get information about latest updates?'))
utils.settings.config['mud']['nerd_fonts'] = str(utils.ask(f'Do you want to use {STYLES["bold"]}nerd-fonts{RESET}?'))
utils.settings.config['mud']['simplify_branches'] = str(utils.ask(f'Do you want to simplify branches? (ex. {STYLES["bold"]}feature/name{RESET} -> {STYLES["bold"]}f/name{RESET}'))
utils.settings.save()
print('Your settings are updated!')
pass
Expand Down
3 changes: 2 additions & 1 deletion settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ def __init__(self, file_name: str) -> None:
'auto_fetch': False,
'run_async': True,
'run_table': True,
'simplify_branches': True
'simplify_branches': True,
'ask_updates': True
},
'alias': {
'to': 'git checkout',
Expand Down
66 changes: 59 additions & 7 deletions utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,18 +109,70 @@
settings: Settings


def remove_colors():
for index in range(len(TEXT)):
TEXT[index] = ''
for index in range(len(BACK)):
BACK[index] = ''


def set_up():
global GLYPHS
GLYPHS = ICON_GLYPHS if settings.mud_settings['nerd_fonts'] else TEXT_GLYPHS


def check_updates(explicit: bool = False) -> bool:
target_directory = os.curdir
os.chdir(os.path.dirname(os.path.abspath(__file__)))

subprocess.run(['git', 'fetch'], check=True)

result = subprocess.run(['git', 'status', '-uno'], capture_output=True, text=True)

if 'Your branch is behind' in result.stdout:
m = random.choice(list(TEXT.values())[3:])
u = random.choice(list(TEXT.values())[3:])
d = random.choice(list(TEXT.values())[3:])
print(fr'''
{m} __ __{u} __ __{d} _____
{m}/\ '-./ \{u}/\ \/\ \{d}/\ __-.{RESET}
{m}\ \ \-./\ \{u} \ \_\ \{d} \ \/\ \{RESET}
{m} \ \_\ \ \_\{u} \_____\{d} \____-{RESET}
{m} \/_/ \/_/{u}\/_____/{d}\/____/{RESET}
''')
print(f'{STYLES["bold"]}New update(s) is available!{RESET}\n')

log = subprocess.run(['git', 'log', 'HEAD..@{u}', '--oneline', '--color=always'], text=True, stdout=subprocess.PIPE).stdout
print(log)

if ask('Do you want to update?'):
update_process = subprocess.run(['git', 'pull', '--force'], text=False, stdout=subprocess.DEVNULL)
if update_process.returncode == 0:
print(f'{TEXT["green"]}{STYLES["BOLD"]}Update successful!{RESET}')
else:
print_error('Update failed', update_process.returncode)
os.chdir(target_directory)
return True

if explicit:
print('No updates available')

os.chdir(target_directory)
return False


def ask(text: str) -> bool:
print(f"{text} [Y/n] ", end='', flush=True)
if sys.platform.startswith('win'):
from msvcrt import getch
response = getch().decode().lower()
else:
import tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(fd)
response = sys.stdin.read(1).lower()
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)

print()
return response in ['y', '\r', '\n']


def print_error(text: str, code: int = 255) -> None:
print(f'{TEXT["red"]}Error:{RESET} {text}')
sys.exit(code)
Expand Down

0 comments on commit cd744f0

Please sign in to comment.