hexss 0.26.2__tar.gz → 0.26.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. {hexss-0.26.2 → hexss-0.26.3}/HexSS.egg-info/PKG-INFO +1 -1
  2. {hexss-0.26.2 → hexss-0.26.3}/HexSS.egg-info/SOURCES.txt +1 -0
  3. {hexss-0.26.2 → hexss-0.26.3}/PKG-INFO +1 -1
  4. {hexss-0.26.2 → hexss-0.26.3}/hexss/__init__.py +1 -1
  5. {hexss-0.26.2 → hexss-0.26.3}/hexss/download/download.py +11 -1
  6. hexss-0.26.3/hexss/git/__init__.py +258 -0
  7. hexss-0.26.3/hexss/git/__init__2.py +268 -0
  8. hexss-0.26.2/hexss/git/__init__.py +0 -213
  9. {hexss-0.26.2 → hexss-0.26.3}/HexSS.egg-info/dependency_links.txt +0 -0
  10. {hexss-0.26.2 → hexss-0.26.3}/HexSS.egg-info/entry_points.txt +0 -0
  11. {hexss-0.26.2 → hexss-0.26.3}/HexSS.egg-info/top_level.txt +0 -0
  12. {hexss-0.26.2 → hexss-0.26.3}/LICENSE +0 -0
  13. {hexss-0.26.2 → hexss-0.26.3}/MANIFEST.in +0 -0
  14. {hexss-0.26.2 → hexss-0.26.3}/README.md +0 -0
  15. {hexss-0.26.2 → hexss-0.26.3}/hexss/__main__.py +0 -0
  16. {hexss-0.26.2 → hexss-0.26.3}/hexss/box/__init__.py +0 -0
  17. {hexss-0.26.2 → hexss-0.26.3}/hexss/box/box.py +0 -0
  18. {hexss-0.26.2 → hexss-0.26.3}/hexss/box/box_only.py +0 -0
  19. {hexss-0.26.2 → hexss-0.26.3}/hexss/config.py +0 -0
  20. {hexss-0.26.2 → hexss-0.26.3}/hexss/constants/__init__.py +0 -0
  21. {hexss-0.26.2 → hexss-0.26.3}/hexss/constants/terminal_color.py +0 -0
  22. {hexss-0.26.2 → hexss-0.26.3}/hexss/control_robot/__init__.py +0 -0
  23. {hexss-0.26.2 → hexss-0.26.3}/hexss/control_robot/app.py +0 -0
  24. {hexss-0.26.2 → hexss-0.26.3}/hexss/control_robot/pretty_dataframe.py +0 -0
  25. {hexss-0.26.2 → hexss-0.26.3}/hexss/control_robot/robot.py +0 -0
  26. {hexss-0.26.2 → hexss-0.26.3}/hexss/control_robot/server.py +0 -0
  27. {hexss-0.26.2 → hexss-0.26.3}/hexss/control_robot/static/css/dashboard.css +0 -0
  28. {hexss-0.26.2 → hexss-0.26.3}/hexss/control_robot/static/css/global.css +0 -0
  29. {hexss-0.26.2 → hexss-0.26.3}/hexss/control_robot/static/css/light.css +0 -0
  30. {hexss-0.26.2 → hexss-0.26.3}/hexss/control_robot/static/css/primer-primitives.css +0 -0
  31. {hexss-0.26.2 → hexss-0.26.3}/hexss/control_robot/static/css/primer.css +0 -0
  32. {hexss-0.26.2 → hexss-0.26.3}/hexss/control_robot/static/handsontable.full.min.css +0 -0
  33. {hexss-0.26.2 → hexss-0.26.3}/hexss/control_robot/static/handsontable.full.min.js +0 -0
  34. {hexss-0.26.2 → hexss-0.26.3}/hexss/control_robot/static/header.css +0 -0
  35. {hexss-0.26.2 → hexss-0.26.3}/hexss/control_robot/static/jquery-3.6.0.min.js +0 -0
  36. {hexss-0.26.2 → hexss-0.26.3}/hexss/control_robot/static/styles.css +0 -0
  37. {hexss-0.26.2 → hexss-0.26.3}/hexss/control_robot/templates/head_import.html +0 -0
  38. {hexss-0.26.2 → hexss-0.26.3}/hexss/control_robot/templates/header.html +0 -0
  39. {hexss-0.26.2 → hexss-0.26.3}/hexss/control_robot/templates/index.html +0 -0
  40. {hexss-0.26.2 → hexss-0.26.3}/hexss/control_robot/templates/register.html +0 -0
  41. {hexss-0.26.2 → hexss-0.26.3}/hexss/control_robot/templates/table_editor.html +0 -0
  42. {hexss-0.26.2 → hexss-0.26.3}/hexss/detector/__init__.py +0 -0
  43. {hexss-0.26.2 → hexss-0.26.3}/hexss/detector/object_detector.py +0 -0
  44. {hexss-0.26.2 → hexss-0.26.3}/hexss/download/__init__.py +0 -0
  45. {hexss-0.26.2 → hexss-0.26.3}/hexss/draw_app/__init__.py +0 -0
  46. {hexss-0.26.2 → hexss-0.26.3}/hexss/draw_app/app.py +0 -0
  47. {hexss-0.26.2 → hexss-0.26.3}/hexss/draw_app/convert_data.py +0 -0
  48. {hexss-0.26.2 → hexss-0.26.3}/hexss/draw_app/media_sequence.py +0 -0
  49. {hexss-0.26.2 → hexss-0.26.3}/hexss/draw_app/server.py +0 -0
  50. {hexss-0.26.2 → hexss-0.26.3}/hexss/draw_app/static/canvas.js +0 -0
  51. {hexss-0.26.2 → hexss-0.26.3}/hexss/draw_app/static/media_control.js +0 -0
  52. {hexss-0.26.2 → hexss-0.26.3}/hexss/draw_app/static/script.js +0 -0
  53. {hexss-0.26.2 → hexss-0.26.3}/hexss/draw_app/templates/index.html +0 -0
  54. {hexss-0.26.2 → hexss-0.26.3}/hexss/env.py +0 -0
  55. {hexss-0.26.2 → hexss-0.26.3}/hexss/example/__init__.py +0 -0
  56. {hexss-0.26.2 → hexss-0.26.3}/hexss/example/camera_server.py +0 -0
  57. {hexss-0.26.2 → hexss-0.26.3}/hexss/example/detector.py +0 -0
  58. {hexss-0.26.2 → hexss-0.26.3}/hexss/example/image.py +0 -0
  59. {hexss-0.26.2 → hexss-0.26.3}/hexss/example/templates/index.html +0 -0
  60. {hexss-0.26.2 → hexss-0.26.3}/hexss/example/threading1.py +0 -0
  61. {hexss-0.26.2 → hexss-0.26.3}/hexss/example/threading2.py +0 -0
  62. {hexss-0.26.2 → hexss-0.26.3}/hexss/example/threading_app.py +0 -0
  63. {hexss-0.26.2 → hexss-0.26.3}/hexss/frame_publisher/__init__.py +0 -0
  64. {hexss-0.26.2 → hexss-0.26.3}/hexss/frame_publisher/publisher.py +0 -0
  65. {hexss-0.26.2 → hexss-0.26.3}/hexss/frame_publisher/server.py +0 -0
  66. {hexss-0.26.2 → hexss-0.26.3}/hexss/git/test.py +0 -0
  67. {hexss-0.26.2 → hexss-0.26.3}/hexss/github/__init__.py +0 -0
  68. {hexss-0.26.2 → hexss-0.26.3}/hexss/github/download.py +0 -0
  69. {hexss-0.26.2 → hexss-0.26.3}/hexss/image/__init__.py +0 -0
  70. {hexss-0.26.2 → hexss-0.26.3}/hexss/image/capture.py +0 -0
  71. {hexss-0.26.2 → hexss-0.26.3}/hexss/image/classifier.py +0 -0
  72. {hexss-0.26.2 → hexss-0.26.3}/hexss/image/detector.py +0 -0
  73. {hexss-0.26.2 → hexss-0.26.3}/hexss/image/func.py +0 -0
  74. {hexss-0.26.2 → hexss-0.26.3}/hexss/image/im.py +0 -0
  75. {hexss-0.26.2 → hexss-0.26.3}/hexss/image/im_box.py +0 -0
  76. {hexss-0.26.2 → hexss-0.26.3}/hexss/image/pygame.py +0 -0
  77. {hexss-0.26.2 → hexss-0.26.3}/hexss/image2/__init__.py +0 -0
  78. {hexss-0.26.2 → hexss-0.26.3}/hexss/image2/capture.py +0 -0
  79. {hexss-0.26.2 → hexss-0.26.3}/hexss/image2/classifier.py +0 -0
  80. {hexss-0.26.2 → hexss-0.26.3}/hexss/image2/detector.py +0 -0
  81. {hexss-0.26.2 → hexss-0.26.3}/hexss/image2/im.py +0 -0
  82. {hexss-0.26.2 → hexss-0.26.3}/hexss/json/__init__.py +0 -0
  83. {hexss-0.26.2 → hexss-0.26.3}/hexss/kill.py +0 -0
  84. {hexss-0.26.2 → hexss-0.26.3}/hexss/latex.py +0 -0
  85. {hexss-0.26.2 → hexss-0.26.3}/hexss/modbus/__init__.py +0 -0
  86. {hexss-0.26.2 → hexss-0.26.3}/hexss/modbus/serial/__init__.py +0 -0
  87. {hexss-0.26.2 → hexss-0.26.3}/hexss/modbus/serial/app.py +0 -0
  88. {hexss-0.26.2 → hexss-0.26.3}/hexss/modbus/serial/robot.py +0 -0
  89. {hexss-0.26.2 → hexss-0.26.3}/hexss/modbus/serial/run.py +0 -0
  90. {hexss-0.26.2 → hexss-0.26.3}/hexss/modbus/serial/templates/header.html +0 -0
  91. {hexss-0.26.2 → hexss-0.26.3}/hexss/modbus/serial/templates/index.html +0 -0
  92. {hexss-0.26.2 → hexss-0.26.3}/hexss/modbus/serial/templates/register.html +0 -0
  93. {hexss-0.26.2 → hexss-0.26.3}/hexss/multiprocessing/__init__.py +0 -0
  94. {hexss-0.26.2 → hexss-0.26.3}/hexss/multiprocessing/func.py +0 -0
  95. {hexss-0.26.2 → hexss-0.26.3}/hexss/multiprocessing/multicore.py +0 -0
  96. {hexss-0.26.2 → hexss-0.26.3}/hexss/network.py +0 -0
  97. {hexss-0.26.2 → hexss-0.26.3}/hexss/num/__init__.py +0 -0
  98. {hexss-0.26.2 → hexss-0.26.3}/hexss/numpy/__init__.py +0 -0
  99. {hexss-0.26.2 → hexss-0.26.3}/hexss/pandas/__init__.py +0 -0
  100. {hexss-0.26.2 → hexss-0.26.3}/hexss/pandas/dataframe_transformation.py +0 -0
  101. {hexss-0.26.2 → hexss-0.26.3}/hexss/path.py +0 -0
  102. {hexss-0.26.2 → hexss-0.26.3}/hexss/pyconfig/__init__.py +0 -0
  103. {hexss-0.26.2 → hexss-0.26.3}/hexss/pyconfig/_config.py +0 -0
  104. {hexss-0.26.2 → hexss-0.26.3}/hexss/python/__init__.py +0 -0
  105. {hexss-0.26.2 → hexss-0.26.3}/hexss/python/packages.py +0 -0
  106. {hexss-0.26.2 → hexss-0.26.3}/hexss/raspberrypi/__init__.py +0 -0
  107. {hexss-0.26.2 → hexss-0.26.3}/hexss/raspberrypi/gpio.py +0 -0
  108. {hexss-0.26.2 → hexss-0.26.3}/hexss/serial/__init__.py +0 -0
  109. {hexss-0.26.2 → hexss-0.26.3}/hexss/server/__init__.py +0 -0
  110. {hexss-0.26.2 → hexss-0.26.3}/hexss/server/camera_server.py +0 -0
  111. {hexss-0.26.2 → hexss-0.26.3}/hexss/server/file_manager_server.py +0 -0
  112. {hexss-0.26.2 → hexss-0.26.3}/hexss/server/processes.py +0 -0
  113. {hexss-0.26.2 → hexss-0.26.3}/hexss/server/static/jquery-3.6.0.min.js +0 -0
  114. {hexss-0.26.2 → hexss-0.26.3}/hexss/server/static/script.js +0 -0
  115. {hexss-0.26.2 → hexss-0.26.3}/hexss/server/static/styles.css +0 -0
  116. {hexss-0.26.2 → hexss-0.26.3}/hexss/server/templates/camera.html +0 -0
  117. {hexss-0.26.2 → hexss-0.26.3}/hexss/server/templates/file_manager.html +0 -0
  118. {hexss-0.26.2 → hexss-0.26.3}/hexss/server/templates/file_manager2.html +0 -0
  119. {hexss-0.26.2 → hexss-0.26.3}/hexss/server/templates/process.html +0 -0
  120. {hexss-0.26.2 → hexss-0.26.3}/hexss/string/__init__.py +0 -0
  121. {hexss-0.26.2 → hexss-0.26.3}/hexss/threading/__init__.py +0 -0
  122. {hexss-0.26.2 → hexss-0.26.3}/hexss/threading/mutithread.py +0 -0
  123. {hexss-0.26.2 → hexss-0.26.3}/hexss/windows/__init__.py +0 -0
  124. {hexss-0.26.2 → hexss-0.26.3}/hexss/windows/admin.py +0 -0
  125. {hexss-0.26.2 → hexss-0.26.3}/hexss/windows/hotspot.py +0 -0
  126. {hexss-0.26.2 → hexss-0.26.3}/hexss/windows/wifi.py +0 -0
  127. {hexss-0.26.2 → hexss-0.26.3}/setup.cfg +0 -0
  128. {hexss-0.26.2 → hexss-0.26.3}/setup.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: HexSS
3
- Version: 0.26.2
3
+ Version: 0.26.3
4
4
  Home-page: https://github.com/hexs/hexss
5
5
  License: MIT
6
6
  License-File: LICENSE
@@ -65,6 +65,7 @@ hexss/frame_publisher/__init__.py
65
65
  hexss/frame_publisher/publisher.py
66
66
  hexss/frame_publisher/server.py
67
67
  hexss/git/__init__.py
68
+ hexss/git/__init__2.py
68
69
  hexss/git/test.py
69
70
  hexss/github/__init__.py
70
71
  hexss/github/download.py
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: HexSS
3
- Version: 0.26.2
3
+ Version: 0.26.3
4
4
  Home-page: https://github.com/hexs/hexss
5
5
  License: MIT
6
6
  License-File: LICENSE
@@ -33,7 +33,7 @@ def get_config(file_name):
33
33
  return config
34
34
 
35
35
 
36
- __version__ = '0.26.2'
36
+ __version__ = '0.26.3'
37
37
  hostname = get_hostname()
38
38
  username = get_username()
39
39
  hexss_dir = get_hexss_dir()
@@ -245,7 +245,6 @@ def download(
245
245
 
246
246
 
247
247
  if __name__ == '__main__':
248
-
249
248
  # from hexss.env import set_proxy
250
249
  #
251
250
  # set_proxy() # if use hexss proxy
@@ -268,3 +267,14 @@ if __name__ == '__main__':
268
267
  filename='QC7-7990.zip',
269
268
  dest_dir='downloads'
270
269
  )
270
+ download(
271
+ 'https://developer.download.nvidia.com/compute/cudnn/secure/8.9.7/local_installers/11.x/cudnn-windows-x86_64-8.9.7.29_cuda11-archive.zip?'
272
+ '__token__=exp=1761282766~hmac=cbecdd2da55fa7e1f014a326fcb192fa4d198859d3343ec74505c473f3e708da&'
273
+ 't=eyJscyI6InJlZiIsImxzZCI6IlJFRi1naXRodWIuY29tL2hleHMvVmFsb3JhbnQtQUkvYmxvYi9tYWluL3RyYWluX3lvbG92OF93aXRoX2dwdS9SRUFETUVfZm9yX3VzZV9HUFUubWQifQ==')
274
+
275
+ download(
276
+ 'https://developer.download.nvidia.com/compute/cudnn/secure/8.9.7/local_installers/12.x/cudnn-windows-x86_64-8.9.7.29_cuda12-archive.zip?'
277
+ '__token__=exp=1761282457~hmac=210a75b71bd87d51b15a807076ee12131e6891a8663a002faf4de5fb9d2b4e60&'
278
+ 't=eyJscyI6InJlZiIsImxzZCI6IlJFRi1naXRodWIuY29tL2hleHMvVmFsb3JhbnQtQUkvYmxvYi9tYWluL3RyYWluX3lvbG92OF93aXRoX2dwdS9SRUFETUVfZm9yX3VzZV9HUFUubWQifQ==')
279
+
280
+ download('https://developer.download.nvidia.com/compute/cuda/13.0.1/local_installers/cuda_13.0.1_windows.exe')
@@ -0,0 +1,258 @@
1
+ from pathlib import Path
2
+ from typing import Optional, Union, List
3
+ import os
4
+ import time
5
+ import fnmatch
6
+
7
+ import hexss
8
+ from hexss.constants import *
9
+
10
+ hexss.check_packages('requests', 'GitPython', auto_install=True)
11
+
12
+ import requests
13
+ from git import Repo, GitCommandError, InvalidGitRepositoryError, RemoteProgress
14
+
15
+
16
+ def _ensure_repo(path: Union[Path, str]) -> Repo:
17
+ try:
18
+ return Repo(path)
19
+ except InvalidGitRepositoryError:
20
+ raise RuntimeError(f"'{path}' is not a valid Git repository.")
21
+
22
+
23
+ def _git_safe(*segments: str) -> str:
24
+ # Normalize path for Git/Windows
25
+ return os.path.join(*segments).replace("\\", "/")
26
+
27
+
28
+ # ---------- Core ops ----------
29
+ def clone(path: Union[Path, str], url: str, branch: str = "main", timeout: Optional[int] = None) -> Repo:
30
+ try:
31
+ print(end=f"Cloning '{url}' into '{path}'...\n")
32
+ repo = Repo.clone_from(url, path, branch=branch, single_branch=True, depth=1, timeout=timeout)
33
+ print(end=f"✅ {GREEN}Successfully cloned{END} '{url}' to '{repo.working_dir}'.\n")
34
+ return repo
35
+ except GitCommandError as e:
36
+ raise RuntimeError(f"{RED}Git clone failed{END}: {e.stderr.strip()}") from e
37
+ except Exception as e:
38
+ raise RuntimeError(f"{RED}Unexpected error during clone{END}: {e}") from e
39
+
40
+
41
+ def pull(path: Union[Path, str], branch: str = "main") -> str:
42
+ repo = _ensure_repo(path)
43
+ try:
44
+ print(end=f"Pulling latest changes in '{repo.working_tree_dir}' (branch '{branch}')...\n")
45
+ output = repo.git.pull("origin", branch)
46
+ print(end=f"✅ {GREEN}Pull result{END}: {output}\n")
47
+ return output
48
+ except GitCommandError as e:
49
+ raise RuntimeError(f"{RED}Git pull failed{END}: {e.stderr.strip()}") from e
50
+ except Exception as e:
51
+ raise RuntimeError(f"{RED}Unexpected error during pull{END}: {e}") from e
52
+
53
+
54
+ def clone_or_pull(path: Union[Path, str], url: Optional[str] = None, branch: str = "main") -> Union[Repo, str]:
55
+ git_dir = os.path.join(path, ".git")
56
+ if not os.path.isdir(git_dir):
57
+ if not url:
58
+ raise ValueError("URL is required to clone into an empty directory.")
59
+ return clone(path, url, branch)
60
+ return pull(path, branch)
61
+
62
+
63
+ def auto_pull(path: Union[Path, str], interval: int = 600, branch: str = "main") -> None:
64
+ while True:
65
+ try:
66
+ pull(path, branch)
67
+ except Exception as e:
68
+ print(end=f"{RED}Auto-pull error{END}: {e}\n")
69
+ time.sleep(interval)
70
+
71
+
72
+ def status(path: Union[Path, str], file_patterns: Optional[List[str]] = None, filter_codes: str = 'MADRCU') -> str:
73
+ repo = _ensure_repo(path)
74
+ status_lines = repo.git.status('--porcelain').splitlines()
75
+
76
+ status_map = {
77
+ "M": "modify",
78
+ "A": "add",
79
+ "D": "delete",
80
+ "R": "rename",
81
+ "C": "copy",
82
+ "U": "update",
83
+ "?": "untrack"
84
+ }
85
+
86
+ details = []
87
+ for line in status_lines:
88
+ if not line.strip():
89
+ continue
90
+
91
+ code = line[:2].strip() # e.g. "M", "A", "??"
92
+ file_path = line[3:].strip() # after two status chars + space
93
+
94
+ if not code:
95
+ continue
96
+ if code[0] not in filter_codes:
97
+ continue
98
+
99
+ if file_patterns:
100
+ # Accept either wildcard match or directory prefix match
101
+ if not any(
102
+ fnmatch.fnmatch(file_path, pat) or file_path.startswith(pat.rstrip("/") + "/")
103
+ for pat in file_patterns
104
+ ):
105
+ continue
106
+
107
+ details.append(f"{status_map.get(code[0], code)} {file_path}")
108
+
109
+ return ", ".join(details)
110
+
111
+
112
+ def add(path: Union[Path, str], file_patterns: Optional[List[str]] = None) -> None:
113
+ """
114
+ Prefer Git's pathspec handling (robust wildcards/dirs).
115
+ """
116
+ repo = _ensure_repo(path)
117
+ root = repo.working_tree_dir
118
+
119
+ if not file_patterns:
120
+ repo.git.add(A=True)
121
+ print(end="✅ Staged all changes.\n")
122
+ return
123
+
124
+ # Normalize: if it's a dir, make sure it ends with '/'
125
+ normalized: List[str] = []
126
+ for pat in file_patterns:
127
+ full = _git_safe(root, pat)
128
+ if os.path.isdir(full):
129
+ d = pat.replace("\\", "/")
130
+ if not d.endswith("/"):
131
+ d += "/"
132
+ normalized.append(d)
133
+ else:
134
+ normalized.append(pat)
135
+
136
+ try:
137
+ repo.git.add('--', *normalized)
138
+ except GitCommandError as e:
139
+ raise RuntimeError(f"{RED}git add failed{END}: {e.stderr.strip()}") from e
140
+
141
+ staged = repo.git.diff('--cached', '--name-only').splitlines()
142
+ if staged:
143
+ print(end=f"✅ Staged files ({len(staged)}):\n")
144
+ for f in staged:
145
+ print(" ", f)
146
+ else:
147
+ print(end="⚠️ No matching files found to stage.\n")
148
+
149
+
150
+ def commit(path: Union[Path, str], message: Optional[str] = None) -> Optional[str]:
151
+ """
152
+ Commit staged changes if any. Returns commit hexsha or None if nothing staged.
153
+ """
154
+ repo = _ensure_repo(path)
155
+
156
+ staged = repo.git.diff('--cached', '--name-only').splitlines()
157
+ if not staged:
158
+ print(end=f"{YELLOW}No staged changes to commit.{END}\n")
159
+ return None
160
+
161
+ msg = message or "Auto-commit"
162
+ try:
163
+ commit_obj = repo.index.commit(msg)
164
+ print(end=f"📝 {PINK}Committed{END}: {msg}\n")
165
+ print(end=f"🔗 {commit_obj.hexsha}\n")
166
+ return commit_obj.hexsha
167
+ except GitCommandError as e:
168
+ raise RuntimeError(f"{RED}Git commit failed{END}: {e.stderr.strip()}") from e
169
+
170
+
171
+ def push(path: Union[Path, str], branch: str = "main", commit_message: Optional[str] = None) -> None:
172
+ """
173
+ Push current HEAD to origin/<branch>.
174
+ - If commit_message is provided and there are staged changes, a commit is made before push.
175
+ - If no upstream is set, set upstream to origin/<branch>.
176
+ """
177
+ repo = _ensure_repo(path)
178
+
179
+ if commit_message is not None:
180
+ _ = commit(path, commit_message)
181
+
182
+ try:
183
+ origin = repo.remote(name="origin")
184
+ except ValueError:
185
+ raise RuntimeError(f"{RED}No remote named 'origin'{END} is configured.")
186
+
187
+ # Ensure/checkout the target branch
188
+ try:
189
+ if repo.head.is_detached:
190
+ raise RuntimeError("HEAD is detached. Please attach HEAD to a branch before pushing.")
191
+
192
+ if repo.active_branch.name != branch:
193
+ if branch in repo.heads:
194
+ repo.git.checkout(branch)
195
+ else:
196
+ repo.git.checkout('-b', branch)
197
+ except Exception as e:
198
+ raise RuntimeError(f"{RED}Unable to checkout branch '{branch}'{END}: {e}")
199
+
200
+ # Push with upstream if needed
201
+ try:
202
+ if repo.active_branch.tracking_branch() is None:
203
+ print(end=f"🔧 Setting upstream to origin/{branch}...\n")
204
+ repo.git.push('--set-upstream', 'origin', branch)
205
+ else:
206
+ push_info = origin.push(branch)
207
+ for info in push_info:
208
+ if info.flags & info.ERROR:
209
+ raise RuntimeError(f"Push failed: {info.summary}")
210
+ except GitCommandError as e:
211
+ raise RuntimeError(f"{RED}Git push failed{END}: {e.stderr.strip()}") from e
212
+
213
+ print(end=f"✅ {GREEN}Pushed to origin/{branch} successfully.{END}\n")
214
+
215
+
216
+ def push_if_dirty(path: Union[Path, str], file_patterns: Optional[List[str]] = None, branch: str = "main") -> None:
217
+ add(path, file_patterns)
218
+ s = status(path, file_patterns)
219
+ push(path, branch=branch, commit_message=s if s else None)
220
+
221
+
222
+ def fetch_repositories(username: str) -> List[dict]:
223
+ if not username:
224
+ raise ValueError("GitHub username must be provided.")
225
+ url = f"https://api.github.com/users/{username}/repos"
226
+ try:
227
+ response = requests.get(url, proxies=hexss.proxies)
228
+ response.raise_for_status()
229
+ return response.json()
230
+ except Exception as e:
231
+ print(end=f"{RED}Failed to fetch repos for '{username}'{END}: {e}\n")
232
+ return []
233
+
234
+
235
+ if __name__ == '__main__':
236
+ from pprint import pprint
237
+
238
+ pprint(list(r['name'] for r in fetch_repositories('hexs')))
239
+
240
+ path = Path(r'Project/func')
241
+ url = 'https://github.com/hexs/func.git'
242
+ # url = 'git@github.com/hexs/func.git' # SSH
243
+ clone_or_pull(path, url)
244
+ push_if_dirty(path, ['img/*', '*.txt'])
245
+
246
+ repo_path = r'C:\PythonProjects\auto_inspection_data__QC7-2413'
247
+ pats = [
248
+ 'img_full/',
249
+ 'img_frame_log/',
250
+ 'model/',
251
+ '*.json',
252
+ '.gitignore',
253
+ ]
254
+
255
+ add(repo_path, pats)
256
+ s = status(repo_path, pats)
257
+ print(s)
258
+ push(repo_path, branch='main', commit_message=s if s else None)
@@ -0,0 +1,268 @@
1
+ from pathlib import Path
2
+ from typing import Optional, Union, List
3
+ import os
4
+ import time
5
+ import fnmatch
6
+
7
+ import hexss
8
+ from hexss.constants import *
9
+
10
+ hexss.check_packages('requests', 'GitPython', auto_install=True)
11
+
12
+ import requests
13
+ from git import Repo, GitCommandError, InvalidGitRepositoryError, RemoteProgress
14
+
15
+
16
+ # ---------- Helpers ----------
17
+ def _as_str(path: Union[Path, str]) -> str:
18
+ return str(path) if isinstance(path, Path) else path
19
+
20
+ def _ensure_repo(path: Union[Path, str]) -> Repo:
21
+ try:
22
+ return Repo(_as_str(path))
23
+ except InvalidGitRepositoryError:
24
+ raise RuntimeError(f"'{path}' is not a valid Git repository.")
25
+
26
+ def _git_safe(*segments: str) -> str:
27
+ # Normalize path for Git/Windows
28
+ return os.path.join(*segments).replace("\\", "/")
29
+
30
+ class _CloneProgress(RemoteProgress):
31
+ def update(self, op_code, cur_count, max_count=None, message=''):
32
+ if message:
33
+ print(end=f"{message}\n")
34
+
35
+
36
+ # ---------- Core ops ----------
37
+ def clone(path: Union[Path, str], url: str, branch: str = "main", timeout: Optional[int] = None) -> Repo:
38
+ if not url:
39
+ raise ValueError("A repository URL must be provided for cloning.")
40
+ path_s = _as_str(path)
41
+ try:
42
+ print(end=f"Cloning '{url}' into '{path_s}'...\n")
43
+ repo = Repo.clone_from(
44
+ url, path_s,
45
+ branch=branch,
46
+ single_branch=True,
47
+ depth=1,
48
+ timeout=timeout,
49
+ progress=_CloneProgress()
50
+ )
51
+ print(end=f"✅ {GREEN}Successfully cloned{END} '{url}' to '{repo.working_dir}'.\n")
52
+ return repo
53
+ except GitCommandError as e:
54
+ raise RuntimeError(f"{RED}Git clone failed{END}: {e.stderr.strip()}") from e
55
+ except Exception as e:
56
+ raise RuntimeError(f"{RED}Unexpected error during clone{END}: {e}") from e
57
+
58
+
59
+ def pull(path: Union[Path, str], branch: str = "main") -> str:
60
+ repo = _ensure_repo(path)
61
+ try:
62
+ print(end=f"Pulling latest changes in '{repo.working_tree_dir}' (branch '{branch}')...\n")
63
+ output = repo.git.pull("origin", branch)
64
+ print(end=f"✅ {GREEN}Pull result{END}: {output}\n")
65
+ return output
66
+ except GitCommandError as e:
67
+ raise RuntimeError(f"{RED}Git pull failed{END}: {e.stderr.strip()}") from e
68
+ except Exception as e:
69
+ raise RuntimeError(f"{RED}Unexpected error during pull{END}: {e}") from e
70
+
71
+
72
+ def clone_or_pull(path: Union[Path, str], url: Optional[str] = None, branch: str = "main") -> Union[Repo, str]:
73
+ path_s = _as_str(path)
74
+ git_dir = os.path.join(path_s, ".git")
75
+ if not os.path.isdir(git_dir):
76
+ if not url:
77
+ raise ValueError("URL is required to clone into an empty directory.")
78
+ return clone(path_s, url, branch)
79
+ return pull(path_s, branch)
80
+
81
+
82
+ def auto_pull(path: Union[Path, str], interval: int = 600, branch: str = "main") -> None:
83
+ while True:
84
+ try:
85
+ pull(path, branch)
86
+ except Exception as e:
87
+ print(end=f"{RED}Auto-pull error{END}: {e}\n")
88
+ time.sleep(interval)
89
+
90
+
91
+ def status(path: Union[Path, str], file_patterns: Optional[List[str]] = None, filter_codes: str = 'MADRCU?') -> str:
92
+ """
93
+ Returns a compact comma-separated summary like:
94
+ 'add img_full/a.png, modify model/h.h5, untrack new.json'
95
+ """
96
+ repo = _ensure_repo(path)
97
+ status_lines = repo.git.status('--porcelain').splitlines()
98
+
99
+ status_map = {
100
+ "M": "modify",
101
+ "A": "add",
102
+ "D": "delete",
103
+ "R": "rename",
104
+ "C": "copy",
105
+ "U": "update",
106
+ "?": "untrack"
107
+ }
108
+
109
+ details = []
110
+ for line in status_lines:
111
+ if not line.strip():
112
+ continue
113
+
114
+ code = line[:2].strip() # e.g. "M", "A", "??"
115
+ file_path = line[3:].strip() # after two status chars + space
116
+
117
+ if not code:
118
+ continue
119
+ if code[0] not in filter_codes:
120
+ continue
121
+
122
+ if file_patterns:
123
+ # Accept either wildcard match or directory prefix match
124
+ if not any(
125
+ fnmatch.fnmatch(file_path, pat) or file_path.startswith(pat.rstrip("/") + "/")
126
+ for pat in file_patterns
127
+ ):
128
+ continue
129
+
130
+ details.append(f"{status_map.get(code[0], code)} {file_path}")
131
+
132
+ return ", ".join(details)
133
+
134
+
135
+ def add(path: Union[Path, str], file_patterns: Optional[List[str]] = None) -> None:
136
+ """
137
+ Prefer Git's pathspec handling (robust wildcards/dirs).
138
+ """
139
+ repo = _ensure_repo(path)
140
+ root = repo.working_tree_dir
141
+
142
+ if not file_patterns:
143
+ repo.git.add(A=True)
144
+ print(end="✅ Staged all changes.\n")
145
+ return
146
+
147
+ # Normalize: if it's a dir, make sure it ends with '/'
148
+ normalized: List[str] = []
149
+ for pat in file_patterns:
150
+ full = _git_safe(root, pat)
151
+ if os.path.isdir(full):
152
+ d = pat.replace("\\", "/")
153
+ if not d.endswith("/"):
154
+ d += "/"
155
+ normalized.append(d)
156
+ else:
157
+ normalized.append(pat)
158
+
159
+ try:
160
+ repo.git.add('--', *normalized)
161
+ except GitCommandError as e:
162
+ raise RuntimeError(f"{RED}git add failed{END}: {e.stderr.strip()}") from e
163
+
164
+ staged = repo.git.diff('--cached', '--name-only').splitlines()
165
+ if staged:
166
+ print(end=f"✅ Staged files ({len(staged)}):\n")
167
+ for f in staged:
168
+ print(" ", f)
169
+ else:
170
+ print(end="⚠️ No matching files found to stage.\n")
171
+
172
+
173
+ def commit(path: Union[Path, str], message: Optional[str] = None) -> Optional[str]:
174
+ """
175
+ Commit staged changes if any. Returns commit hexsha or None if nothing staged.
176
+ """
177
+ repo = _ensure_repo(path)
178
+
179
+ staged = repo.git.diff('--cached', '--name-only').splitlines()
180
+ if not staged:
181
+ print(end=f"{YELLOW}No staged changes to commit.{END}\n")
182
+ return None
183
+
184
+ msg = message or "Auto-commit"
185
+ try:
186
+ commit_obj = repo.index.commit(msg)
187
+ print(end=f"📝 {PINK}Committed{END}: {msg}\n")
188
+ print(end=f"🔗 {commit_obj.hexsha}\n")
189
+ return commit_obj.hexsha
190
+ except GitCommandError as e:
191
+ raise RuntimeError(f"{RED}Git commit failed{END}: {e.stderr.strip()}") from e
192
+
193
+
194
+ def push(path: Union[Path, str], branch: str = "main", commit_message: Optional[str] = None) -> None:
195
+ """
196
+ Push current HEAD to origin/<branch>.
197
+ - If commit_message is provided and there are staged changes, a commit is made before push.
198
+ - If no upstream is set, set upstream to origin/<branch>.
199
+ """
200
+ repo = _ensure_repo(path)
201
+
202
+ # ✅ Correct logic: commit only if a message is provided
203
+ if commit_message is not None:
204
+ _ = commit(path, commit_message) # commit() will no-op if nothing staged
205
+
206
+ # Ensure remote exists
207
+ try:
208
+ origin = repo.remote(name="origin")
209
+ except ValueError:
210
+ raise RuntimeError(f"{RED}No remote named 'origin'{END} is configured.")
211
+
212
+ # Ensure/checkout the target branch
213
+ try:
214
+ if repo.head.is_detached:
215
+ raise RuntimeError("HEAD is detached. Please attach HEAD to a branch before pushing.")
216
+
217
+ if repo.active_branch.name != branch:
218
+ if branch in repo.heads:
219
+ repo.git.checkout(branch)
220
+ else:
221
+ repo.git.checkout('-b', branch)
222
+ except Exception as e:
223
+ raise RuntimeError(f"{RED}Unable to checkout branch '{branch}'{END}: {e}")
224
+
225
+ # Push with upstream if needed
226
+ try:
227
+ if repo.active_branch.tracking_branch() is None:
228
+ print(end=f"🔧 Setting upstream to origin/{branch}...\n")
229
+ repo.git.push('--set-upstream', 'origin', branch)
230
+ else:
231
+ push_info = origin.push(branch)
232
+ for info in push_info:
233
+ if info.flags & info.ERROR:
234
+ raise RuntimeError(f"Push failed: {info.summary}")
235
+ except GitCommandError as e:
236
+ raise RuntimeError(f"{RED}Git push failed{END}: {e.stderr.strip()}") from e
237
+
238
+ print(end=f"✅ {GREEN}Pushed to origin/{branch} successfully.{END}\n")
239
+
240
+
241
+ def fetch_repositories(username: str) -> List[dict]:
242
+ if not username:
243
+ raise ValueError("GitHub username must be provided.")
244
+ url = f"https://api.github.com/users/{username}/repos"
245
+ try:
246
+ response = requests.get(url, proxies=hexss.proxies)
247
+ response.raise_for_status()
248
+ return response.json()
249
+ except Exception as e:
250
+ print(end=f"{RED}Failed to fetch repos for '{username}'{END}: {e}\n")
251
+ return []
252
+
253
+
254
+ # ---------- Example usage ----------
255
+ if __name__ == '__main__':
256
+ repo_path = r'C:\PythonProjects\auto_inspection_data__QC7-2413'
257
+ pats = [
258
+ 'img_full/',
259
+ 'img_frame_log/',
260
+ 'model/',
261
+ '*.json',
262
+ '.gitignore',
263
+ ]
264
+
265
+ add(repo_path, pats)
266
+ s = status(repo_path, pats)
267
+ print(s)
268
+ push(repo_path, branch='main', commit_message=s if s else None)
@@ -1,213 +0,0 @@
1
- from typing import Optional, Union, List
2
- import os
3
- import time
4
- import fnmatch
5
-
6
- import hexss
7
- from hexss.constants import *
8
-
9
- hexss.check_packages('requests', 'GitPython', auto_install=True)
10
-
11
- import requests
12
- from git import Repo, GitCommandError, InvalidGitRepositoryError
13
-
14
-
15
- def clone(path: str, url: str, branch: str = "main", timeout: Optional[int] = None) -> Repo:
16
- """
17
- Clone a Git repository to the given path.
18
-
19
- Args:
20
- path (str): Destination directory path.
21
- url (str): Repository URL.
22
- branch (str): Branch to check out after cloning.
23
- timeout (Optional[int]): Timeout for the clone operation in seconds.
24
-
25
- Returns:
26
- Repo: GitPython Repo object for the cloned repository.
27
-
28
- Raises:
29
- ValueError: If url is empty or invalid.
30
- RuntimeError: If Git command fails.
31
- """
32
- if url is None:
33
- raise ValueError("A repository URL must be provided for cloning.")
34
-
35
- try:
36
- print(f"Cloning '{url}' into '{path}'...")
37
- repo = Repo.clone_from(url, path, branch=branch, single_branch=True, depth=1, timeout=timeout)
38
- print(f"✅ {GREEN}Successfully cloned{END} '{url}' to '{repo.working_dir}'.")
39
- return repo
40
- except GitCommandError as e:
41
- raise RuntimeError(f"{RED}Git clone failed{END}: {e.stderr.strip()}") from e
42
- except Exception as e:
43
- raise RuntimeError(f"{RED}Unexpected error during clone{END}: {e}") from e
44
-
45
-
46
- def pull(path: str, branch: str = "main") -> str:
47
- """
48
- Pull latest changes from origin for the given repository path and branch.
49
-
50
- Args:
51
- path (str): Path to existing Git repository.
52
- branch (str): Branch to pull from origin.
53
-
54
- Returns:
55
- str: Output from the Git pull command.
56
-
57
- Raises:
58
- RuntimeError: If directory is not a Git repo or Git command fails.
59
- """
60
- try:
61
- repo = Repo(path)
62
- except InvalidGitRepositoryError:
63
- raise RuntimeError(f"'{path}' is not a valid Git repository.")
64
-
65
- try:
66
- print(f"Pulling latest changes in '{path}' (branch '{branch}')...")
67
- output = repo.git.pull("origin", branch)
68
- print(f"✅ {GREEN}Pull result{END}: {output}")
69
- return output
70
- except GitCommandError as e:
71
- raise RuntimeError(f"{RED}Git pull failed{END}: {e.stderr.strip()}") from e
72
- except Exception as e:
73
- raise RuntimeError(f"{RED}Unexpected error during pull{END}: {e}") from e
74
-
75
-
76
- def clone_or_pull(path: str, url: Optional[str] = None, branch: str = "main") -> Union[Repo, str]:
77
- """
78
- Clone the repository if not already present, otherwise pull latest changes.
79
-
80
- Args:
81
- path (str): Local path for repository.
82
- url (Optional[str]): Repository URL. Required if cloning.
83
- branch (str): Branch name for both clone and pull.
84
-
85
- Returns:
86
- Union[Repo, str]: Repo object if cloned, or pull output if pulled.
87
- """
88
- git_dir = os.path.join(path, ".git")
89
- if not os.path.isdir(git_dir):
90
- if not url:
91
- raise ValueError("URL is required to clone into an empty directory.")
92
- return clone(path, url, branch)
93
- return pull(path, branch)
94
-
95
-
96
- def auto_pull(path: str, interval: int = 600, branch: str = "main") -> None:
97
- """
98
- Continuously pull latest changes at given time intervals.
99
-
100
- Args:
101
- path (str): Path to Git repository.
102
- interval (int): Polling interval in seconds.
103
- branch (str): Branch to pull.
104
- """
105
- while True:
106
- try:
107
- pull(path, branch)
108
- except Exception as e:
109
- print(f"{RED}Auto-pull error{END}: {e}")
110
- time.sleep(interval)
111
-
112
-
113
- def status(path: str, file_patterns: Optional[List[str]] = None, filter_codes: str = 'MADRCU') -> str:
114
- """
115
- Get the working tree status of the repository.
116
-
117
- Args:
118
- path (str): Path to Git repository.
119
- file_patterns (List[str]): List of filename patterns to include (e.g., ['*.py', 'docs/*']).
120
- status_codes (str): Status types to include (e.g., 'MADRCU?' for modified, added, etc.).
121
-
122
- Returns:
123
- str: Comma-separated status summary.
124
- """
125
- repo = Repo(path)
126
- status_lines = repo.git.status('--porcelain').splitlines()
127
-
128
- status_map = {
129
- "M": "modify",
130
- "A": "add",
131
- "D": "delete",
132
- "R": "rename",
133
- "C": "copy",
134
- "U": "update",
135
- "?": "untrack"
136
- }
137
-
138
- details = []
139
- for line in status_lines:
140
- code = line[:2].strip()
141
- file_path = line[3:].strip()
142
- if code and code[0] in filter_codes:
143
- if file_patterns:
144
- if not any(fnmatch.fnmatch(file_path, pattern) for pattern in file_patterns):
145
- continue
146
- status_key = status_map.get(code[0], code)
147
- details.append(f"{status_key} {file_path}")
148
- return ", ".join(details)
149
-
150
-
151
- def add(path: str, file_patterns: Optional[List[str]] = None) -> None:
152
- repo = Repo(path)
153
- git_root = repo.working_tree_dir
154
-
155
- if file_patterns:
156
- matched_files = []
157
- for root, dirs, files in os.walk(git_root):
158
- for file in files:
159
- rel_path = os.path.relpath(os.path.join(root, file), git_root).replace("\\", "/")
160
- if any(fnmatch.fnmatch(rel_path, pattern) for pattern in file_patterns):
161
- matched_files.append(rel_path)
162
- if matched_files:
163
- repo.index.add(matched_files)
164
- print(f"✅ Staged files: {', '.join(matched_files)}")
165
- else:
166
- print("⚠️ No files matched the given patterns.")
167
- else:
168
- repo.git.add(A=True)
169
- print("✅ Staged all changes.")
170
-
171
-
172
- def push_if_dirty(path: str, file_patterns: Optional[List[str]] = None, branch: str = "main",
173
- commit_message: Optional[str] = None) -> None:
174
- try:
175
- repo = Repo(path)
176
- except InvalidGitRepositoryError:
177
- raise RuntimeError(f"'{path}' is not a valid Git repository.")
178
-
179
- if not repo.is_dirty(untracked_files=True):
180
- print(f"{GREEN}Working tree clean; no changes to push.{END}")
181
- return
182
-
183
- add(path, file_patterns)
184
- msg = commit_message or f"Auto-update: {status(path, file_patterns)}"
185
- repo.index.commit(msg)
186
- print(f"{PINK}Committed changes{END}: {msg}")
187
-
188
- origin = repo.remote(name="origin")
189
- push_info = origin.push(branch)
190
- for info in push_info:
191
- if info.flags & info.ERROR:
192
- raise RuntimeError(f"Push failed: {info.summary}")
193
- print(f"✅ {GREEN}Pushed to origin/{branch} successfully.{END}")
194
-
195
-
196
- def fetch_repositories(username: str) -> Optional[List[dict]]:
197
- if not username:
198
- raise ValueError("GitHub username must be provided.")
199
-
200
- url = f"https://api.github.com/users/{username}/repos"
201
- try:
202
- response = requests.get(url, proxies=hexss.proxies)
203
- response.raise_for_status()
204
- return response.json()
205
- except Exception as e:
206
- print(f"{RED}Failed to fetch repos for '{username}'{END}: {e}")
207
- return None
208
-
209
-
210
- if __name__ == '__main__':
211
- path = r'C:\Users\c026730\Desktop\func'
212
- clone_or_pull(path, 'https://github.com/hexs/func.git')
213
- push_if_dirty(path, ['img/*', '*.txt'])
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes