@@ -169,14 +169,41 @@ def sync_usage():
169169 # Git sync
170170 print ("🔄 Syncing to Git..." )
171171
172+ should_pop_stash = False
172173 try :
173- # Pull latest
174- subprocess .run (['git' , 'pull' , '--rebase' ], cwd = repo_path , check = False )
174+ # Check for unstaged changes (excluding data/)
175+ status_result = subprocess .run (
176+ ['git' , 'status' , '--porcelain' ],
177+ cwd = repo_path ,
178+ capture_output = True ,
179+ text = True
180+ )
181+
182+ # Check if there are changes other than data/ directory
183+ other_changes = [line for line in status_result .stdout .splitlines ()
184+ if line and not line .strip ().startswith ('??' ) and 'data/' not in line ]
185+
186+ # Stash other changes if any (before pull --rebase)
187+ if other_changes :
188+ print ("📦 Stashing other changes..." )
189+ subprocess .run (['git' , 'stash' , '--include-untracked' , '-m' , 'Auto-stash before sync' ],
190+ cwd = repo_path , check = False , capture_output = True )
191+ should_pop_stash = True
192+
193+ # Fetch and pull FIRST (before adding local changes)
194+ subprocess .run (['git' , 'fetch' , 'origin' ], cwd = repo_path , check = False , capture_output = True )
195+
196+ pull_result = subprocess .run (
197+ ['git' , 'pull' , '--rebase' , 'origin' , 'main' ],
198+ cwd = repo_path ,
199+ capture_output = True ,
200+ text = True
201+ )
175202
176- # Add changes
203+ # Add data changes AFTER pull (so rebase doesn't unstage them)
177204 subprocess .run (['git' , 'add' , 'data/' ], cwd = repo_path , check = True )
178205
179- # Commit
206+ # Commit data changes if any
180207 commit_msg = f"Update usage from { device_id } - { datetime .now ().strftime ('%Y-%m-%d %H:%M' )} "
181208 result = subprocess .run (
182209 ['git' , 'commit' , '-m' , commit_msg ],
@@ -207,9 +234,23 @@ def sync_usage():
207234 else :
208235 print ("⚠️ Commit failed" )
209236 print (result .stderr )
237+
238+ # Restore stashed changes if any
239+ if should_pop_stash :
240+ pop_result = subprocess .run (
241+ ['git' , 'stash' , 'pop' ],
242+ cwd = repo_path ,
243+ capture_output = True ,
244+ text = True
245+ )
246+ if pop_result .returncode == 0 :
247+ print ("📦 Restored stashed changes" )
210248
211249 except subprocess .CalledProcessError as e :
212250 print (f"❌ Git operation failed: { e } " )
251+ # Restore stash even on error
252+ if should_pop_stash :
253+ subprocess .run (['git' , 'stash' , 'pop' ], cwd = repo_path , check = False )
213254 sys .exit (1 )
214255
215256 print ()
0 commit comments