dte.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #!/bin/python3
  2. """
  3. Arguments:
  4. name
  5. exec location
  6. [icon path]
  7. """
  8. import os
  9. from sys import stderr
  10. import argparse
  11. class Args(argparse.Namespace):
  12. NAME_OF_ENTRY: str = ""
  13. EXEC_PATH: str = ""
  14. icon_path: str | None = None
  15. argsparser: argparse.ArgumentParser
  16. def __init__(self):
  17. super().__init__()
  18. self.argsparser = argparse.ArgumentParser("dte.py")
  19. _ = self.argsparser.add_argument("NAME_OF_ENTRY")
  20. _ = self.argsparser.add_argument("EXEC_PATH")
  21. _ = self.argsparser.add_argument("--icon-path", "-i")
  22. self = self.argsparser.parse_args(namespace=self)
  23. args = Args()
  24. name: str = args.NAME_OF_ENTRY
  25. path: str = args.EXEC_PATH
  26. icon_path: str | None = args.icon_path
  27. entry_path: str = os.path.expanduser(f"~/.local/share/applications/{name}.desktop")
  28. entry_lines = [
  29. "[Desktop Entry]\n",
  30. "Type=Application\n",
  31. f"Name={name}\n",
  32. f"Exec={path}\n"
  33. ]
  34. if icon_path is not None:
  35. entry_lines.append(f"Icon={icon_path}\n")
  36. msg_str: str = f"This will create the following destop entry:\n\n"
  37. for line in entry_lines:
  38. msg_str += line
  39. msg_str += f"\nIn {entry_path}\n"
  40. print(msg_str)
  41. while True:
  42. sure: str = input("Continue? (y/n): ").strip().lower()
  43. if sure == "y" or sure == "yes":
  44. break
  45. elif sure == "n" or sure == "no":
  46. exit(0)
  47. try:
  48. with open(entry_path, "r") as f:
  49. print("Desktop entry already exists");
  50. while True:
  51. choice = input(f"Overwrite entry at {entry_path}? (y/n): ").strip().lower()
  52. if choice == "y":
  53. try:
  54. os.remove(entry_path)
  55. break
  56. except Exception as e:
  57. print(f"Failed to remove entry. Exception: {e}", file=stderr)
  58. exit(1)
  59. elif choice == "n":
  60. exit(0)
  61. except FileNotFoundError:
  62. pass
  63. with open(entry_path, "x") as f:
  64. f.writelines(entry_lines)