Skip to content

Commit

Permalink
subprocess.run() is refactored
Browse files Browse the repository at this point in the history
  • Loading branch information
jasursadikov committed Sep 7, 2024
1 parent 6e7e641 commit 203f045
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 26 deletions.
18 changes: 9 additions & 9 deletions commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def __init__(self, repos):
def info(self, repos: Dict[str, List[str]]) -> None:
table = self._get_table()
for path, labels in repos.items():
output = subprocess.check_output(['git', 'status', '--porcelain'], text=True, cwd=path)
output = subprocess.check_output('git status --porcelain', shell=True, text=True, cwd=path)
files = output.splitlines()

formatted_path = self._get_formatted_path(path)
Expand All @@ -30,7 +30,7 @@ def info(self, repos: Dict[str, List[str]]) -> None:
colored_labels = self._get_formatted_labels(labels, utils.GLYPHS["label"])

# Sync with origin status
ahead_behind_cmd = subprocess.run(['git', 'rev-list', '--left-right', '--count', 'HEAD...@{upstream}'], text=True, cwd=path, capture_output=True)
ahead_behind_cmd = subprocess.run('git rev-list --left-right --count HEAD...@{upstream}', shell=True, text=True, cwd=path, capture_output=True)
stdout = ahead_behind_cmd.stdout.strip().split()
origin_sync = ''
if len(stdout) >= 2:
Expand All @@ -53,7 +53,7 @@ def info(self, repos: Dict[str, List[str]]) -> None:
def status(self, repos: Dict[str, List[str]]):
table = self._get_table()
for path, labels in repos.items():
output = subprocess.check_output(['git', 'status', '--porcelain'], text=True, cwd=path)
output = subprocess.check_output('git status --porcelain', shell=True, text=True, cwd=path)
files = output.splitlines()

formatted_path = self._get_formatted_path(path)
Expand Down Expand Up @@ -107,7 +107,7 @@ def log(self, repos: Dict[str, List[str]]) -> None:
commit = self._get_commit_message(path, 35)

# Commit time
commit_time_cmd = subprocess.run(['git', 'log', '-1', '--pretty=format:%cd', '--date=relative'], text=True, cwd=path, capture_output=True)
commit_time_cmd = subprocess.run('git log -1 --pretty=format:%cd --date=relative', shell=True, text=True, cwd=path, capture_output=True)
commit_time = commit_time_cmd.stdout.strip()

table.add_row([formatted_path, branch, author, commit_time, commit])
Expand All @@ -121,7 +121,7 @@ def branches(self, repos: Dict[str, List[str]]) -> None:

# Preparing branches for sorting to display them in the right order.
for path in repos.keys():
raw_branches = [line.strip() for line in subprocess.check_output(['git', 'branch'], text=True, cwd=path).split('\n') if line.strip()]
raw_branches = [line.strip() for line in subprocess.check_output('git branch', shell=True, text=True, cwd=path).split('\n') if line.strip()]
for branch in raw_branches:
branch = branch.replace(' ', '').replace('*', '')
if branch not in all_branches:
Expand All @@ -131,7 +131,7 @@ def branches(self, repos: Dict[str, List[str]]) -> None:

for path, labels in repos.items():
formatted_path = self._get_formatted_path(path)
branches = subprocess.check_output(['git', 'branch'], text=True, cwd=path).splitlines()
branches = subprocess.check_output('git branch', shell=True, text=True, cwd=path).splitlines()
current_branch = next((branch.lstrip('* ') for branch in branches if branch.startswith('*')), None)
branches = [branch.lstrip('* ') for branch in branches]
sorted_branches = sorted(branches, key=lambda x: branch_counter.get(x, 0), reverse=True)
Expand All @@ -151,7 +151,7 @@ def tags(self, repos: Dict[str, List[str]]):

for path, labels in repos.items():
formatted_path = self._get_formatted_path(path)
tags = [line.strip() for line in subprocess.check_output(['git', 'tag'], text=True, cwd=path).splitlines() if line.strip()]
tags = [line.strip() for line in subprocess.check_output('git tag', shell=True, text=True, cwd=path).splitlines() if line.strip()]
tags = [f"{utils.GLYPHS['tag']} {tag}" for tag in tags]
tags = ' '.join(tags)
table.add_row([formatted_path, tags])
Expand Down Expand Up @@ -301,7 +301,7 @@ def _get_branch_status(path: str) -> str:

@staticmethod
def _get_authors_name(path: str) -> str:
cmd = subprocess.run(['git', 'log', '-1', '--pretty=format:%an'], text=True, cwd=path, capture_output=True)
cmd = subprocess.run('git log -1 --pretty=format:%an', shell=True, text=True, cwd=path, capture_output=True)
git_config_user_cmd = subprocess.run(['git', 'config', 'user.name'], text=True, capture_output=True)
committer_color = '' if cmd.stdout.strip() == git_config_user_cmd.stdout.strip() else DIM
author = cmd.stdout.strip()
Expand All @@ -311,7 +311,7 @@ def _get_authors_name(path: str) -> str:

@staticmethod
def _get_commit_message(path: str, max_chars: int) -> str:
cmd = subprocess.run(['git', 'log', '-1', '--pretty=format:%s'], text=True, cwd=path, capture_output=True)
cmd = subprocess.run('git log -1 --pretty=format:%s', shell=True, text=True, cwd=path, capture_output=True)
log = cmd.stdout.strip()
log = log[:max_chars] + '...' if len(log) > max_chars else log
return log
Expand Down
10 changes: 5 additions & 5 deletions config.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,26 +13,26 @@ def __init__(self):
self.data = {}

def save(self, file_path: str) -> None:
root = ElementTree.Element("mud")
root = ElementTree.Element('mud')

def _filter_labels(label: str):
return bool(re.match(r'^\w+$', label))

for path, labels in self.data.items():
dir_element = ElementTree.SubElement(root, "dir")
dir_element.set("path", path)
dir_element = ElementTree.SubElement(root, 'dir')
dir_element.set('path', path)

valid_labels = [label for label in labels if _filter_labels(label)]
if valid_labels:
if len(valid_labels) == 1:
formatted_labels = valid_labels[0]
else:
formatted_labels = ', '.join(valid_labels)
dir_element.set("label", formatted_labels)
dir_element.set('label', formatted_labels)

rough_string = ElementTree.tostring(root)
parsed = minidom.parseString(rough_string)
pretty_xml = parsed.toprettyxml(indent="\t")
pretty_xml = parsed.toprettyxml(indent='\t')

with open(file_path, 'w') as file:
file.write(pretty_xml)
Expand Down
11 changes: 5 additions & 6 deletions mud.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,6 @@ def run(self) -> None:
else:
self.cmd_runner.run_ordered(self.repos.keys(), sys.argv)


def init(self, args) -> None:
self.config.data = {}
index = 0
Expand Down Expand Up @@ -223,9 +222,9 @@ def _filter_repos(self) -> None:
to_delete = []
for repo in self.repos:
os.chdir(os.path.join(directory, repo))
has_modifications = subprocess.check_output(['git', 'status', '--porcelain'])
branch_filter = (branch is not None and branch.strip() and subprocess.check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], text=True).splitlines()[0] != branch)
is_diverged = not any('ahead' in line or 'behind' in line for line in subprocess.check_output(['git', 'status', '--branch', '--porcelain'], text=True).splitlines() if line.startswith('##'))
has_modifications = subprocess.check_output('git status --porcelain', shell=True)
branch_filter = (branch is not None and branch.strip() and subprocess.check_output('git rev-parse --abbrev-ref HEAD', shell=True, text=True).splitlines()[0] != branch)
is_diverged = not any('ahead' in line or 'behind' in line for line in subprocess.check_output('git status --branch --porcelain', shell=True, text=True).splitlines() if line.startswith('##'))
if (modified and not has_modifications) or (branch and branch_filter) or (diverged and is_diverged):
to_delete.append(repo)

Expand All @@ -238,15 +237,15 @@ def _fetch_all(self) -> None:
asyncio.run(self._fetch_all_async())
else:
for repo in self.repos:
subprocess.run(['git', 'fetch'], cwd=repo, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
subprocess.run('git fetch', shell=True, cwd=repo, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

async def _fetch_all_async(self) -> None:
tasks = [self._fetch_repo_async(repo) for repo in self.repos]
await asyncio.gather(*tasks)

@staticmethod
async def _fetch_repo_async(repo: str) -> None:
await asyncio.create_subprocess_exec(['git', 'fetch'], cwd=repo, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
await asyncio.create_subprocess_exec('git fetch', shell=True, cwd=repo, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

@staticmethod
def _parse_aliases():
Expand Down
12 changes: 6 additions & 6 deletions utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def set_up():

def version() -> None:
os.chdir(os.path.dirname(os.path.abspath(__file__)))
hash = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'], text=True).splitlines()[0]
hash = subprocess.check_output('git rev-parse --short HEAD', shell=True, text=True).splitlines()[0]
m = random.choice(TEXT[3:])
u = random.choice(TEXT[3:])
d = random.choice(TEXT[3:])
Expand All @@ -87,8 +87,8 @@ def check_updates(explicit: bool = False) -> bool:
target_directory = os.getcwd()
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)
subprocess.run('git fetch', shell=True, check=True)
result = subprocess.run('git status -uno', shell=True, capture_output=True, text=True)

if 'Your branch is behind' in result.stdout:
m = random.choice(TEXT[3:])
Expand All @@ -103,11 +103,11 @@ def check_updates(explicit: bool = False) -> bool:
''')
print(f'{BOLD}New update(s) is available!{RESET}\n')

log = subprocess.run(['git', 'log', 'HEAD..@{u}', '--oneline', '--color=always'], text=True, stdout=subprocess.PIPE).stdout
log = subprocess.run('git log HEAD..@{u} --oneline --color=always', shell=True, 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)
update_process = subprocess.run('git pull --force', shell=True, text=False, stdout=subprocess.DEVNULL)
if update_process.returncode == 0:
print(f'{GREEN}{BOLD}Update successful!{RESET}')
else:
Expand Down Expand Up @@ -135,7 +135,7 @@ def configure():


def ask(text: str) -> bool:
print(f"{text} [Y/n] ", end='', flush=True)
print(f'{text} [Y/n] ', end='', flush=True)
if sys.platform.startswith('win'):
from msvcrt import getch
response = getch().decode().lower()
Expand Down

0 comments on commit 203f045

Please sign in to comment.