-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsendstash.py
More file actions
executable file
·1970 lines (1686 loc) · 82 KB
/
sendstash.py
File metadata and controls
executable file
·1970 lines (1686 loc) · 82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import os
import sys
import yaml
import subprocess
import argparse
import tempfile
import re
import platform
import shutil
import glob as globmod
from datetime import datetime, timedelta
class SendStash:
# ANSI color codes (auto-disabled when not a TTY)
_COLORS = {
'reset': '\033[0m',
'bold': '\033[1m',
'dim': '\033[2m',
'red': '\033[31m',
'green': '\033[32m',
'yellow': '\033[33m',
'blue': '\033[34m',
'cyan': '\033[36m',
'gray': '\033[90m',
}
def _c(self, color, text):
"""Colorize text if stdout is a TTY."""
if not hasattr(self, '_use_color'):
self._use_color = sys.stdout.isatty()
if self._use_color and color in self._COLORS:
return f"{self._COLORS[color]}{text}{self._COLORS['reset']}"
return str(text)
def __init__(self, config_path=None):
self.config_path = self._find_config_file(config_path)
if not self.config_path:
print(f"{self._c('red', '[err]')} Could not find config.yaml")
print(f" -> Place it in one of the documented locations")
sys.exit(1)
print(f"{self._c('blue', '[info]')} Config: {self.config_path}")
self.config = self._load_config(self.config_path)
self.project_path = None
def _find_config_file(self, specified_path):
"""Finds the config file in a prioritized list of locations."""
if specified_path and os.path.exists(specified_path):
return specified_path
# Path specified by environment variable
env_path = os.getenv('SENDSTASH_CONFIG_PATH')
if env_path and os.path.exists(env_path):
return env_path
# User-specific config directory
user_config_path = os.path.expanduser("~/.config/sendstash/config.yaml")
if os.path.exists(user_config_path):
return user_config_path
# In an adjacent directory: ../sendstash-config/config.yaml
script_dir = os.path.dirname(os.path.realpath(__file__))
adjacent_config_path = os.path.join(script_dir, '..', 'sendstash-config', 'config.yaml')
if os.path.exists(adjacent_config_path):
return os.path.normpath(adjacent_config_path)
# In the same directory as the script
script_config_path = os.path.join(script_dir, 'config.yaml')
if os.path.exists(script_config_path):
return script_config_path
return None
def _load_config(self, config_path):
"""Loads the configuration from a YAML file."""
with open(config_path, 'r') as f:
config = yaml.safe_load(f)
# Resolve password from password_cmd if needed
smb = config.get('smb', {})
if 'password_cmd' in smb and 'password' not in smb:
try:
result = subprocess.run(
smb['password_cmd'], shell=True,
capture_output=True, text=True, check=True
)
smb['password'] = result.stdout.strip()
except subprocess.CalledProcessError as e:
print(f"{self._c('red', '[err]')} password_cmd failed: {e}")
sys.exit(1)
# Expand project paths
root = os.path.expanduser(config.get('root', ''))
if 'projects' in config:
for name, project in config['projects'].items():
project['path'] = os.path.expanduser(project['path'].format(root=root))
return config
def get_project_choices(self):
"""Returns a list of project names from the config."""
return list(self.config.get('projects', {}).keys())
def set_project(self, project_name):
"""Set the working directory to a configured project's path."""
projects = self.config.get('projects', {})
if project_name not in projects:
print(f"{self._c('red', '[err]')} Project '{project_name}' not found")
print(f" -> Available: {', '.join(projects.keys())}")
sys.exit(1)
self.project_path = projects[project_name]['path']
if not os.path.isdir(self.project_path):
print(f"{self._c('red', '[err]')} Path does not exist: {self.project_path}")
sys.exit(1)
print(f"{self._c('blue', '[info]')} Project: {project_name} ({self.project_path})")
def _run_command(self, command, cwd=None, interactive=False, capture=False, env=None):
"""Runs a command and streams its output."""
if capture:
result = subprocess.run(
command, cwd=cwd, shell=isinstance(command, str),
capture_output=True, text=True, env=env
)
return result
elif interactive:
process = subprocess.Popen(command, cwd=cwd, shell=isinstance(command, str), env=env)
process.wait()
return process.returncode
else:
process = subprocess.Popen(
command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
universal_newlines=True, cwd=cwd, shell=isinstance(command, str), env=env
)
for line in process.stdout:
print(line, end='')
process.wait()
return process.returncode
def sync_config(self):
"""Syncs the configuration file itself based on 'config_sync' settings."""
if 'config_sync' not in self.config:
print(f"{self._c('yellow', '[warn]')} 'config_sync' section not defined in config.yaml")
return
sync_settings = self.config['config_sync']
command = sync_settings.get('command')
if not command:
print(f"{self._c('red', '[err]')} 'config_sync' missing 'command' key")
return
config_dir = os.path.dirname(self.config_path)
print(f"{self._c('blue', '[info]')} Syncing config: '{command}' in '{config_dir}'")
return_code = self._run_command(command, cwd=config_dir)
if return_code == 0:
print(f" -> Sync complete, reloading config")
self.config = self._load_config(self.config_path)
else:
print(f"{self._c('red', '[err]')} Config sync failed (exit {return_code})")
sys.exit(1)
def open_folder(self):
"""Opens the sendstash script directory in the file explorer."""
script_dir = os.path.dirname(os.path.realpath(__file__))
print(f"{self._c('blue', '[info]')} Opening: {script_dir}")
try:
if sys.platform == "win32":
subprocess.run(['explorer', script_dir], check=True)
elif sys.platform == "darwin":
subprocess.run(['open', script_dir], check=True)
elif sys.platform == "linux":
file_managers = ['xdg-open', 'nautilus', 'dolphin', 'thunar', 'nemo', 'pcmanfm']
opened = False
for fm in file_managers:
try:
subprocess.run([fm, script_dir], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
opened = True
break
except (subprocess.CalledProcessError, FileNotFoundError):
continue
if not opened:
print(f"{self._c('yellow', '[warn]')} No file manager found")
print(f" -> {script_dir}")
return
else:
print(f"{self._c('yellow', '[warn]')} Unsupported platform: {sys.platform}")
print(f" -> {script_dir}")
return
except subprocess.CalledProcessError as e:
print(f"{self._c('red', '[err]')} {e}")
print(f" -> {script_dir}")
except Exception as e:
print(f"{self._c('red', '[err]')} {e}")
print(f" -> {script_dir}")
def _get_cwd(self):
"""Get the working directory — project path if set, otherwise current dir."""
return self.project_path or os.getcwd()
def _scan_repos_with_stashes(self):
"""Scan {root}/projects/*/ for git repos that have stashes.
Returns [(dir_name, path, stash_count)] for repos WITH stashes."""
root = os.path.expanduser(self.config.get('root', ''))
projects_dir = os.path.join(root, 'projects')
if not os.path.isdir(projects_dir):
print(f"{self._c('yellow', '[warn]')} Projects dir not found: {projects_dir}")
return []
results = []
for entry in sorted(os.listdir(projects_dir)):
repo_path = os.path.join(projects_dir, entry)
if not os.path.isdir(os.path.join(repo_path, '.git')):
continue
result = self._run_command('git stash list', cwd=repo_path, capture=True)
if result.returncode != 0 or not result.stdout.strip():
continue
stash_count = len(result.stdout.strip().split('\n'))
results.append((entry, repo_path, stash_count))
return results
def scan(self, path=None):
"""Recursively scan directories for git repos with stashes."""
if path:
scan_root = os.path.expanduser(path)
else:
scan_root = os.path.expanduser(self.config.get('root', ''))
if not os.path.isdir(scan_root):
print(f"{self._c('red', '[error]')} Directory not found: {scan_root}")
return
print(f"{self._c('blue', '[scan]')} Scanning {scan_root} for repos with stashes...")
results = []
for dirpath, dirnames, _ in os.walk(scan_root):
if '.git' in dirnames:
result = self._run_command('git stash list', cwd=dirpath, capture=True)
if result.returncode == 0 and result.stdout.strip():
stash_count = len(result.stdout.strip().split('\n'))
name = os.path.basename(dirpath)
results.append((name, dirpath, stash_count))
# Don't descend into .git
dirnames.remove('.git')
if not results:
print(f"{self._c('yellow', '[info]')} No repos with stashes found.")
return
print(f"\n{self._c('green', '[found]')} {len(results)} repo(s) with stashes:\n")
for name, repo_path, count in sorted(results, key=lambda x: x[0]):
print(f" {self._c('cyan', name):30s} ({count} stash{'es' if count != 1 else ''}) {repo_path}")
self._ensure_projects_in_config(results)
def _ensure_projects_in_config(self, repos):
"""Check scanned repos against config and prompt to add new ones."""
configured = set(self.config.get('projects', {}).keys())
new_repos = [(name, path) for name, path, _ in repos if name not in configured]
if not new_repos:
return
print(f"\n{self._c('blue', '[info]')} {len(new_repos)} repo(s) not in config:")
for name, path in new_repos:
print(f" - {name}")
try:
choice = input("\n[a]dd all / [s]elect individually / [n]one / [q]uit: ").strip().lower()
except (EOFError, KeyboardInterrupt):
print()
return
if choice == 'q':
print("Quitting.")
sys.exit(0)
to_add = []
if choice == 'a':
to_add = new_repos
elif choice == 's':
for name, path in new_repos:
try:
yn = input(f" Add '{name}'? [y/n]: ").strip().lower()
except (EOFError, KeyboardInterrupt):
print()
break
if yn == 'y':
to_add.append((name, path))
else:
return
if not to_add:
return
# Read raw config, append new projects, write back
root = self.config.get('root', '~/Dev')
with open(self.config_path, 'r') as f:
raw_config = yaml.safe_load(f)
if 'projects' not in raw_config:
raw_config['projects'] = {}
for name, path in to_add:
expanded_root = os.path.expanduser(root)
rel_path = os.path.relpath(path, expanded_root)
raw_config['projects'][name] = {'path': '{root}/' + rel_path}
print(f" {self._c('green', '[+]')} {name}")
with open(self.config_path, 'w') as f:
yaml.safe_dump(raw_config, f, sort_keys=False)
# Reload config
self.config = self._load_config(self.config_path)
print(f"{self._c('blue', '[info]')} Config reloaded ({len(to_add)} added)")
def _get_repo_name(self):
"""Derive repo name from current git repo's root directory name."""
result = self._run_command('git rev-parse --show-toplevel', cwd=self._get_cwd(), capture=True)
if result.returncode != 0:
print(f"{self._c('red', '[err]')} Not inside a git repository")
sys.exit(1)
return os.path.basename(result.stdout.strip())
def _get_branch_name(self):
"""Get the current branch name."""
result = self._run_command('git rev-parse --abbrev-ref HEAD', cwd=self._get_cwd(), capture=True)
if result.returncode != 0:
print(f"{self._c('red', '[err]')} Could not determine branch")
sys.exit(1)
return result.stdout.strip()
def _sanitize_name(self, name):
"""Sanitize a name for use in filenames (replace / with _)."""
return re.sub(r'[/\\]', '_', name)
def _sanitize_for_filename(self, text, max_len=40):
"""Sanitize arbitrary text for use in a filename component."""
# Replace whitespace and unsafe chars with hyphens, collapse runs, strip edges
sanitized = re.sub(r'[^\w.-]+', '-', text).strip('-')
return sanitized[:max_len].rstrip('-')
def _smb_cmd(self, subcmd):
"""Build and run an smbclient command with auth from config."""
smb = self.config['smb']
server = smb['server']
username = smb['username']
password = smb['password']
cmd = ['smbclient', server, '-U', f'{username}%{password}', '-c', subcmd]
return subprocess.run(cmd, capture_output=True, text=True)
def _get_remote_dir(self):
"""Get the base remote directory from config."""
return self.config['smb'].get('remote_dir', 'stash-sync')
def _detect_backend(self):
"""Detect whether to use mount-based I/O or smbclient."""
if hasattr(self, '_backend'):
return self._backend, self._mount_root
smb = self.config['smb']
# 1. Explicit mount_path in config
mount_path = smb.get('mount_path')
if mount_path:
mount_path = os.path.expanduser(mount_path)
if os.path.exists(mount_path):
self._backend = 'mount'
self._mount_root = mount_path
return self._backend, self._mount_root
else:
print(f"{self._c('yellow', '[warn]')} mount_path '{mount_path}' does not exist")
server = smb.get('server', '')
# Parse //server/share into components
parts = server.replace('\\', '/').strip('/').split('/')
if len(parts) < 2:
self._backend = 'smbclient'
self._mount_root = None
return self._backend, self._mount_root
host, share = parts[0], parts[1]
system = platform.system()
is_wsl = False
if system == 'Linux':
try:
with open('/proc/version', 'r') as f:
proc_version = f.read()
if 'microsoft' in proc_version.lower():
is_wsl = True
except (OSError, IOError):
pass
# 2. Auto-detect existing mounts
if system == 'Windows':
unc_path = f'\\\\{host}\\{share}'
if os.path.exists(unc_path):
self._backend = 'mount'
self._mount_root = unc_path
return self._backend, self._mount_root
elif is_wsl:
mnt_path = f'/mnt/{host}/{share}'
if os.path.exists(mnt_path):
self._backend = 'mount'
self._mount_root = mnt_path
return self._backend, self._mount_root
# 3. Attempt auto-mount on Windows/WSL
if system == 'Windows' or is_wsl:
mount_result = self._ensure_mount(host, share, is_wsl)
self._backend = 'mount'
self._mount_root = mount_result
return self._backend, self._mount_root
# 4. Native Linux — fall back to smbclient
self._backend = 'smbclient'
self._mount_root = None
return self._backend, self._mount_root
def _ensure_mount(self, host, share, is_wsl):
"""Attempt to auto-mount the SMB share on Windows/WSL. Exits on failure."""
smb = self.config['smb']
username = smb.get('username', '')
password = smb.get('password', '')
if is_wsl:
unc = f'\\\\\\\\{host}\\\\{share}'
cmd = [
'powershell.exe', '-Command',
f'net use {unc} /user:{username} {password}'
]
mount_path = f'/mnt/{host}/{share}'
else:
# Native Windows
unc = f'\\\\{host}\\{share}'
cmd = ['net', 'use', unc, f'/user:{username}', password]
mount_path = unc
try:
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode == 0 and os.path.exists(mount_path):
print(f"{self._c('blue', '[info]')} Auto-mounted: {mount_path}")
return mount_path
except (OSError, FileNotFoundError):
pass
print(f"{self._c('red', '[err]')} Could not auto-mount SMB share")
if is_wsl:
print(f" -> Try: powershell.exe -Command \"net use \\\\\\\\{host}\\\\{share} /user:{username} <password>\"")
print(f" -> Or: sudo mount -t cifs //{host}/{share} /mnt/{host}/{share} -o username={username},password=<password>")
else:
print(f" -> Try: net use \\\\{host}\\{share} /user:{username} <password>")
print(f" -> Or set 'mount_path' in your config.yaml to the mount point")
sys.exit(1)
def _get_share_path(self, *parts):
"""Return the full local path to a file/dir on the mounted share."""
return os.path.join(self._mount_root, self._get_remote_dir(), *parts)
def _list_patches_raw(self, repo_name):
"""List patches on the share. Returns [(name, size, date), ...] sorted by name."""
backend, _ = self._detect_backend()
if backend == 'mount':
share_dir = self._get_share_path(repo_name)
if not os.path.isdir(share_dir):
return []
patch_files = globmod.glob(os.path.join(share_dir, '*.patch'))
patches = []
for path in patch_files:
name = os.path.basename(path)
stat = os.stat(path)
size = str(stat.st_size)
date = datetime.fromtimestamp(stat.st_mtime).strftime('%a %b %d %H:%M:%S %Y')
patches.append((name, size, date))
patches.sort(key=lambda x: x[0])
return patches
else:
remote_dir = self._get_remote_dir()
smb_subcmd = f"ls {remote_dir}\\{repo_name}\\*.patch"
result = self._smb_cmd(smb_subcmd)
if result.returncode != 0:
return []
return self._parse_ls_output(result.stdout)
def _upload_patch(self, repo_name, local_patch, local_msg, filename, msg_filename):
"""Upload a patch and its message file to the share."""
backend, _ = self._detect_backend()
if backend == 'mount':
dest_dir = self._get_share_path(repo_name)
os.makedirs(dest_dir, exist_ok=True)
shutil.copy2(local_patch, os.path.join(dest_dir, filename))
shutil.copy2(local_msg, os.path.join(dest_dir, msg_filename))
else:
remote_dir = self._get_remote_dir()
smb_subcmd = (
f"mkdir {remote_dir}; "
f"mkdir {remote_dir}\\{repo_name}; "
f"cd {remote_dir}\\{repo_name}; "
f"put {local_patch} {filename}; "
f"put {local_msg} {msg_filename}"
)
result = self._smb_cmd(smb_subcmd)
stderr_lines = result.stderr.strip().split('\n') if result.stderr else []
real_errors = [
line for line in stderr_lines
if line.strip() and 'NT_STATUS_OBJECT_NAME_COLLISION' not in line
]
if result.returncode != 0 and real_errors:
print(f"{self._c('red', '[err]')} Upload failed:")
print('\n'.join(real_errors))
sys.exit(1)
def _download_patch(self, repo_name, patch_name, dest_path):
"""Download a single patch file from the share."""
backend, _ = self._detect_backend()
if backend == 'mount':
src = self._get_share_path(repo_name, patch_name)
shutil.copy2(src, dest_path)
else:
remote_dir = self._get_remote_dir()
smb_subcmd = (
f"cd {remote_dir}\\{repo_name}; "
f"get {patch_name} {dest_path}"
)
result = self._smb_cmd(smb_subcmd)
if result.returncode != 0:
print(f"{self._c('red', '[err]')} Download failed:")
print(result.stderr)
raise RuntimeError("Download failed")
def _delete_patches(self, repo_name, patch_names):
"""Delete patch and message files from the share."""
backend, _ = self._detect_backend()
if backend == 'mount':
for name in patch_names:
patch_path = self._get_share_path(repo_name, name)
if os.path.exists(patch_path):
os.remove(patch_path)
msg_name = name.rsplit('.patch', 1)[0] + '.msg'
msg_path = self._get_share_path(repo_name, msg_name)
if os.path.exists(msg_path):
os.remove(msg_path)
else:
remote_dir = self._get_remote_dir()
delete_cmds = []
for name in patch_names:
delete_cmds.append(f"del {name}")
msg_name = name.rsplit('.patch', 1)[0] + '.msg'
delete_cmds.append(f"del {msg_name}")
smb_subcmd = f"cd {remote_dir}\\{repo_name}; {'; '.join(delete_cmds)}"
result = self._smb_cmd(smb_subcmd)
stderr_lines = result.stderr.strip().split('\n') if result.stderr else []
real_errors = [
line for line in stderr_lines
if line.strip()
and 'NT_STATUS_OBJECT_NAME_NOT_FOUND' not in line
and 'NT_STATUS_NO_SUCH_FILE' not in line
]
if result.returncode != 0 and real_errors:
print(f"{self._c('red', '[err]')} Clean failed:")
print('\n'.join(real_errors))
raise RuntimeError("Delete failed")
def _get_stash_message(self, stash_ref):
"""Get the message for a stash ref from git stash list."""
result = self._run_command('git stash list', cwd=self._get_cwd(), capture=True)
if result.returncode != 0 or not result.stdout.strip():
return ''
# stash_ref is like "stash@{0}", look for matching line
for line in result.stdout.strip().split('\n'):
if line.startswith(stash_ref):
# Format: "stash@{0}: On branch: message"
parts = line.split(':', 2)
if len(parts) >= 3:
return parts[2].strip()
return ''
return ''
def _get_stash_hash(self, stash_ref):
"""Get the short commit hash for a stash ref."""
result = self._run_command(
f'git rev-parse --short=8 "{stash_ref}"',
cwd=self._get_cwd(), capture=True
)
if result.returncode != 0 or not result.stdout.strip():
return ''
return result.stdout.strip()
def _generate_rej_for_skipped(self, patch_path, skipped_files, workdir):
"""Generate .rej files for files that git apply --reject skipped entirely.
When git apply reports "does not exist in index" or "does not match index",
it doesn't generate .rej files. This extracts the diff hunks for those files
from the patch and writes them as .rej files so users can inspect them.
"""
with open(patch_path, 'r', errors='replace') as f:
lines = f.readlines()
i = 0
while i < len(lines):
if lines[i].startswith('diff --git a/'):
# Extract the b/ path
parts = lines[i].split(' b/')
if len(parts) >= 2:
file_path = parts[-1].strip()
else:
i += 1
continue
if file_path in skipped_files:
# Collect all lines for this diff section
diff_lines = [lines[i]]
j = i + 1
while j < len(lines) and not lines[j].startswith('diff --git '):
diff_lines.append(lines[j])
j += 1
# Write .rej file
rej_path = os.path.join(workdir, file_path + '.rej')
rej_dir = os.path.dirname(rej_path)
if rej_dir and not os.path.isdir(rej_dir):
os.makedirs(rej_dir, exist_ok=True)
with open(rej_path, 'w', newline='') as rej:
rej.writelines(diff_lines)
i = j
continue
i += 1
def _prepare_patch_targets(self, patch_path, workdir):
"""Ensure files referenced in a patch exist in workdir with correct base content.
For files that don't exist in the workdir (not in HEAD's tree), reconstructs
the original (pre-patch) content from the diff's context and removal lines,
so that patch(1) can apply hunks against the correct base.
"""
# Parse the patch into per-file sections
with open(patch_path, 'r', errors='replace') as f:
lines = f.readlines()
i = 0
while i < len(lines):
# Find +++ b/path header
if lines[i].startswith('+++ b/'):
rel_path = lines[i][6:].strip()
if rel_path == '/dev/null':
i += 1
continue
full_path = os.path.join(workdir, rel_path)
parent = os.path.dirname(full_path)
if parent and not os.path.isdir(parent):
os.makedirs(parent, exist_ok=True)
if not os.path.exists(full_path):
# Reconstruct original file content from diff hunks
# Context lines (space prefix) and removal lines (- prefix) = original
original_lines = []
j = i + 1
while j < len(lines):
line = lines[j]
if line.startswith('diff --git '):
break
if line.startswith('@@'):
j += 1
continue
if line.startswith(' ') or line.startswith('-'):
original_lines.append(line[1:])
# '+' lines are additions — skip for original content
j += 1
with open(full_path, 'w', newline='') as out:
out.writelines(original_lines)
i += 1
def _apply_patch_in_temp_workdir(self, patch_path, cwd, tmp_env):
"""Fallback: apply a patch using a temporary working directory.
When git apply --cached fails (e.g. new files not in index, or context
mismatch from a diverged base), checkout HEAD's tree into a temp dir,
apply the patch there, then git add -A to update the temp index.
Returns a result-like object with returncode 0 on success, or None on failure.
"""
tmpdir = tempfile.mkdtemp(prefix='sendstash_workdir_')
try:
workdir_env = dict(tmp_env)
workdir_env['GIT_WORK_TREE'] = tmpdir
workdir_env['GIT_DIR'] = os.path.join(cwd, '.git')
# Checkout HEAD's tree into temp workdir
r = self._run_command('git checkout-index -a', cwd=cwd, capture=True, env=workdir_env)
if r.returncode != 0:
print(f"{self._c('yellow', '[warn]')} checkout-index failed, temp workdir may be incomplete")
# Apply patch in the temp working directory (non-cached)
r = self._run_command(
f'git apply --ignore-whitespace {patch_path}',
cwd=tmpdir, capture=True, env=workdir_env
)
if r.returncode != 0:
# Try with --3way for diverged bases (may exit 1 with conflicts, but files are still applied)
r = self._run_command(
f'git apply --3way --ignore-whitespace {patch_path}',
cwd=tmpdir, capture=True, env=workdir_env
)
if r.returncode != 0:
# --3way exits 1 on conflicts but still applies the files — check if any files were modified
applied = any('Applied patch' in line for line in (r.stderr or '').splitlines() + (r.stdout or '').splitlines())
if not applied:
# Fallback: git apply --reject (cross-platform, applies what it can)
self._prepare_patch_targets(patch_path, tmpdir)
# Stage prepared files so git apply --reject can see them in the index
self._run_command('git add -A', cwd=tmpdir, capture=True, env=workdir_env)
r2 = self._run_command(
f'git apply --reject --ignore-whitespace {patch_path}',
cwd=tmpdir, capture=True, env=workdir_env
)
# Generate .rej for files that git apply skipped entirely
# (e.g. "does not exist in index" or "does not match index")
skipped_files = set()
for line in (r2.stderr or '').splitlines():
if ': does not exist in index' in line or ': does not match index' in line:
fname = line.split('error: ', 1)[-1].split(':')[0].strip()
skipped_files.add(fname)
if skipped_files:
self._generate_rej_for_skipped(patch_path, skipped_files, tmpdir)
# Collect .rej files
rej_files = []
for root, dirs, files in os.walk(tmpdir):
for f in files:
if f.endswith('.rej'):
rej_files.append(os.path.relpath(os.path.join(root, f), tmpdir))
# Check if anything was applied or .rej files were generated
applied_reject = 'Applied patch' in (r2.stderr or '') + (r2.stdout or '')
if not applied_reject and not rej_files and r2.returncode != 0:
return r # nothing applied at all
if rej_files:
print(f" -> {self._c('yellow', '[warn]')} Diverged base, .rej in stash: {self._c('yellow', ', '.join(rej_files))}")
# Stage all changes (including new files) into the temp index
r = self._run_command('git add -A', cwd=tmpdir, capture=True, env=workdir_env)
if r.returncode != 0:
return r
# Return success-like object
class _Success:
returncode = 0
stderr = ''
return _Success()
finally:
shutil.rmtree(tmpdir, ignore_errors=True)
def _inject_stash_from_patch(self, patch_path, stash_msg):
"""Inject a stash entry directly from a patch file without touching the working directory."""
cwd = self._get_cwd()
# Get HEAD commit hash and tree
head_result = self._run_command('git rev-parse HEAD', cwd=cwd, capture=True)
if head_result.returncode != 0:
print(f"{self._c('red', '[err]')} Could not resolve HEAD")
return False
head = head_result.stdout.strip()
head_tree_result = self._run_command('git rev-parse HEAD:', cwd=cwd, capture=True)
if head_tree_result.returncode != 0:
print(f"{self._c('red', '[err]')} Could not resolve HEAD tree")
return False
head_tree = head_tree_result.stdout.strip()
# Get branch name
branch_result = self._run_command('git branch --show-current', cwd=cwd, capture=True)
branch = branch_result.stdout.strip() if branch_result.returncode == 0 and branch_result.stdout.strip() else 'detached'
# Get short HEAD description
head_short_result = self._run_command("git log -1 --format='%h %s' HEAD", cwd=cwd, capture=True)
head_short = head_short_result.stdout.strip().strip("'") if head_short_result.returncode == 0 else head[:7]
# Create I commit (index state — identical to HEAD tree since we only modify W)
i_msg = f"index on {branch}: {head_short}"
i_result = self._run_command(
f'git commit-tree {head_tree} -p {head} -m "{i_msg}"',
cwd=cwd, capture=True
)
if i_result.returncode != 0:
print(f"{self._c('red', '[err]')} Index commit failed: {i_result.stderr.strip()}")
return False
i_commit = i_result.stdout.strip()
# Create temporary index file
tmp_index = tempfile.mktemp(prefix='sendstash_idx_')
tmp_env = dict(os.environ, GIT_INDEX_FILE=tmp_index)
try:
# Populate temp index with HEAD's tree
r = self._run_command('git read-tree HEAD', cwd=cwd, capture=True, env=tmp_env)
if r.returncode != 0:
print(f"{self._c('red', '[err]')} Temp index failed: {r.stderr.strip()}")
return False
# Apply patch to temp index (try --3way for diverged bases, --ignore-whitespace for CRLF)
r = self._run_command(f'git apply --cached --3way --ignore-whitespace {patch_path}', cwd=cwd, capture=True, env=tmp_env)
if r.returncode != 0:
# Fallback: try without --3way in case patch lacks blob info
r = self._run_command(f'git apply --cached --ignore-whitespace {patch_path}', cwd=cwd, capture=True, env=tmp_env)
if r.returncode != 0:
# Final fallback: apply in a temp working directory (handles new files, diverged content)
r = self._apply_patch_in_temp_workdir(patch_path, cwd, tmp_env)
if r is None or (hasattr(r, 'returncode') and r.returncode != 0):
print(f"{self._c('red', '[err]')} Patch apply failed: {r.stderr.strip() if hasattr(r, 'stderr') and r.stderr else ''}")
return False
# Write tree from temp index
r = self._run_command('git write-tree', cwd=cwd, capture=True, env=tmp_env)
if r.returncode != 0:
print(f"{self._c('red', '[err]')} Write-tree failed: {r.stderr.strip()}")
return False
w_tree = r.stdout.strip()
finally:
if os.path.exists(tmp_index):
os.unlink(tmp_index)
# Create W commit (working tree state)
w_msg = f"On {branch}: {stash_msg}" if stash_msg else f"On {branch}: WIP"
w_result = self._run_command(
f'git commit-tree {w_tree} -p {head} -p {i_commit} -m "{w_msg}"',
cwd=cwd, capture=True
)
if w_result.returncode != 0:
print(f"{self._c('red', '[err]')} W-commit failed: {w_result.stderr.strip()}")
return False
w_commit = w_result.stdout.strip()
# Store as stash entry
store_result = self._run_command(
f'git stash store -m "{w_msg}" {w_commit}',
cwd=cwd, capture=True
)
if store_result.returncode != 0:
print(f"{self._c('red', '[err]')} Stash store failed: {store_result.stderr.strip()}")
return False
return w_commit
def _get_local_stash_hashes(self):
"""Get the set of stash hashes for all local stash entries."""
entries = self._list_stash_refs()
hashes = set()
for ref, _ in entries:
h = self._get_stash_hash(ref)
if h:
hashes.add(h)
return hashes
def _content_hash(self, patch_content):
"""SHA-256 of patch content with normalized line endings."""
import hashlib
normalized = patch_content.replace('\r\n', '\n').replace('\r', '\n')
return hashlib.sha256(normalized.encode('utf-8', errors='replace')).hexdigest()[:16]
def _semantic_content_hash(self, patch_content):
"""SHA-256 of patch content with index lines stripped.
Git 'index' lines contain blob hashes that change on re-stash even when
the actual diff is identical. Stripping them gives a stable hash for
semantically identical patches.
"""
import hashlib
normalized = patch_content.replace('\r\n', '\n').replace('\r', '\n')
stripped = re.sub(r'^index [0-9a-f]+\.\.[0-9a-f]+( \d+)?$', '', normalized, flags=re.MULTILINE)
return hashlib.sha256(stripped.encode('utf-8', errors='replace')).hexdigest()[:16]
def _get_local_content_hashes(self):
"""Get a set of content hashes for all local stash entries.
Includes both:
- Hashes computed from local `git stash show -p` output
- Source content hashes stored as git notes (refs/notes/sendstash)
(these are added during pull to survive cross-platform hash differences)
"""
entries = self._list_stash_refs()
hashes = set()
# Collect W commit SHAs for current stash entries
stash_commits = set()
for ref, _ in entries:
rev = self._run_command(
f'git rev-parse {ref}',
cwd=self._get_cwd(), capture=True
)
if rev.returncode == 0:
stash_commits.add(rev.stdout.strip())
# Read source content hashes from git notes (refs/notes/sendstash),
# but only for commits that are still current stash entries
result = self._run_command(
'git notes --ref=sendstash list',
cwd=self._get_cwd(), capture=True
)
if result.returncode == 0 and result.stdout.strip():
for line in result.stdout.strip().split('\n'):
parts = line.split()
if len(parts) == 2 and parts[1] in stash_commits:
note_hash = self._run_command(
f'git notes --ref=sendstash show {parts[1]}',
cwd=self._get_cwd(), capture=True
)
if note_hash.returncode == 0:
hashes.add(note_hash.stdout.strip())
for ref, msg in entries:
result = self._run_command(
f'git stash show -p --include-untracked "{ref}"',
cwd=self._get_cwd(), capture=True
)
if result.returncode != 0:
result = self._run_command(
f'git stash show -p "{ref}"',
cwd=self._get_cwd(), capture=True
)
if result.returncode == 0 and result.stdout.strip():
hashes.add(self._content_hash(result.stdout))
hashes.add(self._semantic_content_hash(result.stdout))
return hashes
def _get_remote_hashes(self):
"""Get the set of stash hashes already present on the SMB share."""
repo_name = self._get_repo_name()
patches = self._list_patches_raw(repo_name)
hashes = set()
for name, _, _ in patches:
# Extract 8-char hex hash from filename: branch_name_HASH_timestamp.patch
match = re.search(r'_([0-9a-f]{8})_\d{4}-\d{2}-\d{2}_', name)
if match:
hashes.add(match.group(1))
return hashes
def _get_remote_content_hashes(self, repo_name=None):
"""Get the set of content and semantic hashes from remote patches.
For patches whose .msg already contains a semantic_hash, that value is
used directly. For older .msg files without one, the actual .patch file
is downloaded and the semantic hash is computed on the fly.
"""
if repo_name is None:
repo_name = self._get_repo_name()
patches = self._list_patches_raw(repo_name)
messages = self._fetch_messages(repo_name, patches)
hashes = set()
need_download = []
for patch_name, _, _ in patches:
_, _, ch, sh = messages.get(patch_name, ('', '', '', ''))
if ch:
hashes.add(ch)
if sh:
hashes.add(sh)
elif ch:
# Old .msg without semantic_hash — need to download patch to compute it
need_download.append(patch_name)
# Download and compute semantic hashes for legacy patches
for patch_name in need_download:
with tempfile.NamedTemporaryFile(mode='w', suffix='.patch', delete=False) as f:
temp_path = f.name
try:
self._download_patch(repo_name, patch_name, temp_path)
with open(temp_path, 'r') as f:
content = f.read()
if content.strip():
hashes.add(self._semantic_content_hash(content))
except (RuntimeError, OSError):
pass
finally:
if os.path.exists(temp_path):
os.unlink(temp_path)
return hashes