Skip to content

Commit

Permalink
scripts/_common.py: add a shared Python file to move duplicated code
Browse files Browse the repository at this point in the history
  • Loading branch information
sebastiaanspeck committed May 7, 2024
1 parent b6ac034 commit 839c057
Show file tree
Hide file tree
Showing 4 changed files with 107 additions and 112 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,6 @@ scripts/pdf/tldr-pages.pdf
# Python venv for testing the PDF script
# Create it with: python3 -m venv scripts/pdf/venv/
venv

# Generated pycache
__pycache__
90 changes: 90 additions & 0 deletions scripts/_common.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT

"""
A Python file that makes some commonly used functions available for other scripts to use.
"""

from pathlib import Path
import os
import argparse


def get_tldr_root():
"""
Get the path of local tldr repository for environment variable TLDR_ROOT.
"""

# If this script is running from tldr/scripts, the parent's parent is the root
f = Path(__file__).resolve()
if (
tldr_root := next((path for path in f.parents if path.name == "tldr"), None)
) is not None:
return tldr_root
elif "TLDR_ROOT" in os.environ:
return Path(os.environ["TLDR_ROOT"])
raise SystemExit(
"\x1b[31mPlease set TLDR_ROOT to the location of a clone of https://github.com/tldr-pages/tldr."
)


def get_locale(path):
"""
Get the locale from the path.
"""

# compute locale
pages_dirname = path.parents[1].name
if "." in pages_dirname:
_, locale = pages_dirname.split(".")
else:
locale = "en"

return locale


def create_argument_parser(description):
"""
Create an argument parser that can be extended.
"""

parser = argparse.ArgumentParser(description=description)
parser.add_argument(
"-p",
"--page",
type=str,
required=False,
default="",
help='page name in the format "platform/alias_command.md"',
)
parser.add_argument(
"-l",
"--language",
type=str,
required=False,
default="",
help='language in the format "ll" or "ll_CC" (e.g. "fr" or "pt_BR")',
)
parser.add_argument(
"-s",
"--stage",
action="store_true",
default=False,
help="stage modified pages (requires `git` to be on $PATH and TLDR_ROOT to be a Git repository)",
)
parser.add_argument(
"-S",
"--sync",
action="store_true",
default=False,
help="synchronize each translation's alias page (if exists) with that of English page",
)
parser.add_argument(
"-n",
"--dry-run",
action="store_true",
default=False,
help="show what changes would be made without actually modifying the pages",
)

return parser
72 changes: 10 additions & 62 deletions scripts/set-alias-page.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,32 +37,14 @@
python3 scripts/set-alias-page.py --sync --dry-run
"""

import argparse
import os
import re
import subprocess
from _common import get_tldr_root, get_locale, create_argument_parser

IGNORE_FILES = (".DS_Store", "tldr.md", "aria2.md")


def get_tldr_root():
"""
Get the path of local tldr repository for environment variable TLDR_ROOT.
"""

# If this script is running from tldr/scripts, the parent's parent is the root
f = os.path.normpath(__file__)
if f.endswith("tldr/scripts/set-alias-page.py"):
return os.path.dirname(os.path.dirname(f))

if "TLDR_ROOT" in os.environ:
return os.environ["TLDR_ROOT"]
else:
raise SystemExit(
"\x1b[31mPlease set TLDR_ROOT to the location of a clone of https://github.com/tldr-pages/tldr.\x1b[0m"
)


def get_templates(root):
"""
Get all alias page translation templates from
Expand Down Expand Up @@ -130,12 +112,12 @@ def get_alias_page(file):
return ""


def set_alias_page(file, command, dry_run=False):
def set_alias_page(path, command, dry_run=False):
"""
Write an alias page to disk.
Parameters:
file (string): Path to an alias page
path (string): Path to an alias page
command (string): The command that the alias stands for.
dry_run (bool): Whether to perform a dry-run.
Expand All @@ -146,17 +128,12 @@ def set_alias_page(file, command, dry_run=False):
"\x1b[34mpage updated" if the command updates.
"""

# compute locale
pages_dir = os.path.basename(os.path.dirname(os.path.dirname(file)))
if "." in pages_dir:
_, locale = pages_dir.split(".")
else:
locale = "en"
locale = get_locale(path)
if locale not in templates:
return ""

# Test if the alias page already exists
orig_command = get_alias_page(file)
orig_command = get_alias_page(path)
if orig_command == command:
return ""

Expand All @@ -175,14 +152,14 @@ def set_alias_page(file, command, dry_run=False):
status = f"{status_prefix}{status}\x1b[0m"

if not dry_run: # Only write to the file during a non-dry-run
alias_name, _ = os.path.splitext(os.path.basename(file))
alias_name, _ = os.path.splitext(os.path.basename(path))
text = (
templates[locale]
.replace("example", alias_name, 1)
.replace("example", command)
)
os.makedirs(os.path.dirname(file), exist_ok=True)
with open(file, "w") as f:
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w") as f:
f.write(text)

return status
Expand Down Expand Up @@ -214,37 +191,8 @@ def sync(root, pages_dirs, alias_name, orig_command, dry_run=False):


def main():
parser = argparse.ArgumentParser(
description="Sets the alias page for all translations of a page"
)
parser.add_argument(
"-p",
"--page",
type=str,
required=False,
default="",
help='page name in the format "platform/alias_command.md"',
)
parser.add_argument(
"-s",
"--stage",
action="store_true",
default=False,
help="stage modified pages (requires `git` to be on $PATH and TLDR_ROOT to be a Git repository)",
)
parser.add_argument(
"-S",
"--sync",
action="store_true",
default=False,
help="synchronize each translation's alias page (if exists) with that of English page",
)
parser.add_argument(
"-n",
"--dry-run",
action="store_true",
default=False,
help="show what changes would be made without actually modifying the pages",
parser = create_argument_parser(
"Sets the alias page for all translations of a page"
)
parser.add_argument("command", type=str, nargs="?", default="")
args = parser.parse_args()
Expand Down
54 changes: 4 additions & 50 deletions scripts/set-more-info-link.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,10 @@
python3 scripts/set-more-info-link.py --sync --dry-run
"""

import argparse
import os
import re
import subprocess
from pathlib import Path
from _common import get_tldr_root, get_locale, create_argument_parser

labels = {
"en": "More information:",
Expand Down Expand Up @@ -90,17 +89,6 @@
IGNORE_FILES = (".DS_Store",)


def get_tldr_root() -> Path:
f = Path(__file__).resolve()
return next(path for path in f.parents if path.name == "tldr")

if "TLDR_ROOT" in os.environ:
return Path(os.environ["TLDR_ROOT"])
raise SystemError(
"\x1b[31mPlease set TLDR_ROOT to the location of a clone of https://github.com/tldr-pages/tldr."
)


def set_link(path: Path, link: str, dry_run=False) -> str:
with path.open(encoding="utf-8") as f:
lines = f.readlines()
Expand All @@ -116,12 +104,7 @@ def set_link(path: Path, link: str, dry_run=False) -> str:
desc_end = i
break

# compute locale
pages_dirname = path.parents[1].name
if "." in pages_dirname:
_, locale = pages_dirname.split(".")
else:
locale = "en"
locale = get_locale(path)

# build new line
if locale in ["bn", "hi", "ne"]:
Expand Down Expand Up @@ -202,37 +185,8 @@ def sync(


def main():
parser = argparse.ArgumentParser(
description='Sets the "More information" link for all translations of a page'
)
parser.add_argument(
"-p",
"--page",
type=str,
required=False,
default="",
help='page name in the format "platform/command.md"',
)
parser.add_argument(
"-s",
"--stage",
action="store_true",
default=False,
help="stage modified pages (requires `git` to be on $PATH and TLDR_ROOT to be a Git repository)",
)
parser.add_argument(
"-S",
"--sync",
action="store_true",
default=False,
help="synchronize each translation's more information link (if exists) with that of English page",
)
parser.add_argument(
"-n",
"--dry-run",
action="store_true",
default=False,
help="show what changes would be made without actually modifying the pages",
parser = create_argument_parser(
'Sets the "More information" link for all translations of a page'
)
parser.add_argument("link", type=str, nargs="?", default="")
args = parser.parse_args()
Expand Down

0 comments on commit 839c057

Please sign in to comment.