-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
918 lines (768 loc) · 35.8 KB
/
Copy pathapp.py
File metadata and controls
918 lines (768 loc) · 35.8 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Git Hub - Proje Analiz Merkezi
Web tabanlı Git dosya takip sistemi
"""
import os
import subprocess
import json
from flask import Flask, render_template, jsonify, request, session
import webbrowser
from threading import Timer
import secrets
app = Flask(__name__)
app.secret_key = secrets.token_hex(16) # Her çalıştırmada farklı secret key
class GitAnalyzer:
def __init__(self, project_path):
self.project_path = project_path
self.remote_status = self.check_remote_status()
self.gitignore_patterns = self.load_gitignore_patterns()
def run_git_command(self, command):
"""Git komutunu çalıştır ve sonucu döndür"""
try:
result = subprocess.run(
command,
shell=True,
cwd=self.project_path,
capture_output=True,
text=True,
encoding='utf-8',
errors='replace' # Geçersiz UTF-8 karakterleri � ile değiştir
)
return result.stdout.strip().split('\n') if result.stdout.strip() else []
except Exception as e:
print(f"Git komut hatası: {e}")
return []
def get_tracked_files(self):
"""Takip edilen dosyaları al"""
files = self.run_git_command("git ls-files")
return [f for f in files if f]
def get_ignored_files(self):
"""Ignore edilen dosyaları al"""
# Önce git status ile ignore edilen dosyaları al
files = self.run_git_command("git status --porcelain --ignored")
ignored = []
for line in files:
if line.startswith('!!'):
ignored.append(line[3:].strip())
# Eğer hiç ignore edilen dosya yoksa, git clean ile kontrol et
if not ignored:
clean_files = self.run_git_command("git clean -ndX")
for line in clean_files:
if line.startswith('Would remove '):
ignored.append(line[13:].strip())
return ignored
def get_untracked_files(self):
"""Takip edilmeyen dosyaları al"""
status_lines = self.run_git_command("git status --porcelain")
untracked = []
for line in status_lines:
if line.startswith('??'):
untracked.append(line[3:].strip())
return untracked
def get_file_info(self, filepath):
"""Dosya hakkında detaylı bilgi al"""
full_path = os.path.join(self.project_path, filepath)
info = {
'name': os.path.basename(filepath),
'path': filepath,
'exists': os.path.exists(full_path),
'github_status': self.check_file_on_github(filepath)
}
if info['exists']:
try:
stat = os.stat(full_path)
info['size'] = stat.st_size
info['modified'] = stat.st_mtime
except:
info['size'] = 0
info['modified'] = 0
else:
info['size'] = 0
info['modified'] = 0
return info
def load_gitignore_patterns(self):
"""Sadece .gitignore dosasından pattern'leri yükle"""
patterns = []
gitignore_path = os.path.join(self.project_path, '.gitignore')
# .gitignore dosası varsa oku
if os.path.exists(gitignore_path):
try:
with open(gitignore_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
# Boş satırları ve yorumları atla
if line and not line.startswith('#'):
patterns.append(line)
print(f"📋 .gitignore dosasından {len(patterns)} pattern yüklendi")
except Exception as e:
print(f"⚠️ .gitignore okuma hatası: {e}")
else:
print("📋 .gitignore dosası bulunamadı")
return patterns
def is_file_ignored(self, filepath):
"""Dosyanın ignore edilip edilmediğini kontrol et"""
import fnmatch
# Git'in kendi ignore kontrolü (en doğrusu)
git_check = self.run_git_command(f'git check-ignore "{filepath}"')
if git_check and git_check[0]:
return True, "Git tarafından ignore edildi"
# Klasör için özel kontrol (git check-ignore klasörler için farklı çalışır)
if '/' in filepath:
# Tüm üst klasörleri test et
path_parts = filepath.split('/')
for i in range(1, len(path_parts) + 1):
partial_path = '/'.join(path_parts[:i])
if i < len(path_parts): # Klasör ise
partial_path += '/'
git_check_partial = self.run_git_command(f'git check-ignore "{partial_path}"')
if git_check_partial and git_check_partial[0]:
return True, f"Üst klasör ignore edildi: {partial_path}"
# Manuel pattern kontrolü (geliştirilmiş)
filepath_lower = filepath.lower()
for pattern in self.gitignore_patterns:
pattern_lower = pattern.lower().strip()
if not pattern_lower:
continue
# Klasör pattern'i (/ ile biten)
if pattern_lower.endswith('/'):
folder_pattern = pattern_lower[:-1]
if folder_pattern in filepath_lower or filepath_lower.startswith(folder_pattern + '/'):
return True, f"Klasör pattern'i ile eşleşti: {pattern}"
# Wildcard pattern'i (* içeren)
elif '*' in pattern_lower:
if fnmatch.fnmatch(filepath_lower, pattern_lower):
return True, f"Wildcard ile eşleşti: {pattern}"
# Klasör içindeki dosyalar için de kontrol et
if fnmatch.fnmatch(filepath_lower.split('/')[-1], pattern_lower):
return True, f"Dosya adı wildcard ile eşleşti: {pattern}"
# Tam yol eşleşmesi
elif pattern_lower == filepath_lower:
return True, f"Tam yol eşleşmesi: {pattern}"
# Kısmi yol eşleşmesi (assets/ gibi)
elif pattern_lower in filepath_lower:
return True, f"Kısmi yol eşleşmesi: {pattern}"
# Dosya adı eşleşmesi
elif pattern_lower == filepath_lower.split('/')[-1]:
return True, f"Dosya adı eşleşmesi: {pattern}"
return False, "Ignore edilmemiş"
def check_file_on_github(self, filepath):
"""Dosyanın GitHub'da var olup olmadığını kontrol et"""
if not self.remote_status.get('has_remote') or self.remote_status.get('connection_status') != 'Connected':
return {
'exists_on_github': False,
'status': 'no_remote',
'message': 'GitHub bağlantısı yok'
}
try:
# Önce remote branch'leri kontrol et
remote_branches = self.run_git_command("git branch -r")
available_branches = []
if remote_branches:
for branch in remote_branches:
branch = branch.strip()
if 'origin/' in branch and '->' not in branch:
branch_name = branch.replace('origin/', '')
available_branches.append(branch_name)
# Kullanılacak branch'i belirle
target_branch = None
if 'main' in available_branches:
target_branch = 'main'
elif 'master' in available_branches:
target_branch = 'master'
elif available_branches:
target_branch = available_branches[0]
else:
return {
'exists_on_github': False,
'status': 'no_remote_branch',
'message': 'Remote branch bulunamadı'
}
print(f"🔍 Checking file '{filepath}' on branch 'origin/{target_branch}'")
# Binary dosyalar için güvenli kontrol - sadece varlığını kontrol et
# git ls-tree dosya içeriğini okumaz, sadece tree'de var mı bakar
result = self.run_git_command(f'git ls-tree -r origin/{target_branch} "{filepath}"')
if result and result[0] and result[0].strip():
# Dosya tree'de bulundu
if not any('fatal:' in line.lower() for line in result):
return {
'exists_on_github': True,
'status': 'exists',
'message': f'GitHub\'da mevcut (branch: {target_branch})'
}
# Hata mesajlarını analiz et
error_text = ' '.join(result).lower()
if 'path' in error_text and ('does not exist' in error_text or 'not found' in error_text):
return {
'exists_on_github': False,
'status': 'not_found',
'message': f'GitHub\'da bulunamadı (branch: {target_branch})'
}
elif 'invalid object name' in error_text:
return {
'exists_on_github': False,
'status': 'branch_not_found',
'message': f'Branch bulunamadı: {target_branch}'
}
else:
print(f"❌ Unexpected error for {filepath}: {result}")
return {
'exists_on_github': False,
'status': 'error',
'message': f'Bilinmeyen hata: {error_text[:50]}...'
}
else:
# Git komutu sonuç döndürmedi, detaylı analiz yap
print(f"🔍 No git result for '{filepath}', analyzing...")
# Önce .gitignore kontrolü
is_ignored, ignore_reason = self.is_file_ignored(filepath)
if is_ignored:
return {
'exists_on_github': False,
'status': 'gitignore_match',
'message': f'Ignore edilmiş: {ignore_reason}'
}
# Dosya/klasör durumunu kontrol et
full_path = os.path.join(self.project_path, filepath)
if not os.path.exists(full_path):
return {
'exists_on_github': False,
'status': 'file_not_exists',
'message': 'Dosya/klasör mevcut değil'
}
# Boş klasör mü kontrol et
if os.path.isdir(full_path):
try:
dir_contents = os.listdir(full_path)
if not dir_contents:
return {
'exists_on_github': False,
'status': 'empty_directory',
'message': 'Boş klasör - Git boş klasörleri takip etmez'
}
else:
return {
'exists_on_github': False,
'status': 'directory_with_files',
'message': f'Klasör ({len(dir_contents)} öğe) - Git klasörleri değil içindeki dosyaları takip eder'
}
except PermissionError:
return {
'exists_on_github': False,
'status': 'permission_denied',
'message': 'Klasöre erişim izni yok'
}
# Dosya boyutu kontrol et
if os.path.isfile(full_path):
try:
file_size = os.path.getsize(full_path)
if file_size == 0:
return {
'exists_on_github': False,
'status': 'empty_file',
'message': 'Boş dosya - İçerik yok'
}
elif file_size > 100 * 1024 * 1024: # 100MB
return {
'exists_on_github': False,
'status': 'large_file',
'message': f'Çok büyük dosya ({file_size // (1024*1024)}MB) - GitHub limiti aşabilir'
}
except OSError:
return {
'exists_on_github': False,
'status': 'file_access_error',
'message': 'Dosyaya erişim hatası'
}
# Git durumunu kontrol et
git_status_result = self.run_git_command("git status --porcelain")
is_in_git_status = any(filepath in line for line in git_status_result) if git_status_result else False
if is_in_git_status:
return {
'exists_on_github': False,
'status': 'in_git_status',
'message': 'Git status\'ta görünüyor ama GitHub kontrolü başarısız'
}
# Son çare - bilinmeyen durum
return {
'exists_on_github': False,
'status': 'unknown_state',
'message': 'Durum belirsiz - Manuel kontrol gerekli'
}
except Exception as e:
print(f"❌ Exception in check_file_on_github for {filepath}: {str(e)}")
return {
'exists_on_github': False,
'status': 'exception',
'message': f'Hata: {str(e)}'
}
def get_git_status(self):
"""Git durumu al"""
status_lines = self.run_git_command("git status --porcelain")
status = {
'modified': [],
'added': [],
'deleted': [],
'renamed': [],
'untracked': []
}
for line in status_lines:
if len(line) >= 3:
status_code = line[:2]
filename = line[3:]
if status_code.strip() == 'M':
status['modified'].append(filename)
elif status_code.strip() == 'A':
status['added'].append(filename)
elif status_code.strip() == 'D':
status['deleted'].append(filename)
elif status_code.strip() == 'R':
status['renamed'].append(filename)
elif status_code.strip() == '??':
status['untracked'].append(filename)
return status
def check_remote_status(self):
"""Remote repository durumunu kontrol et"""
try:
# Remote URL'leri al
remotes = self.run_git_command("git remote -v")
if not remotes or not remotes[0]:
return {
'has_remote': False,
'remote_url': None,
'connection_status': 'No remote configured',
'repo_exists': False,
'detailed_status': 'Local repository only'
}
# İlk remote URL'i al (genellikle origin)
remote_url = remotes[0].split()[1] if len(remotes[0].split()) > 1 else None
# Remote bağlantısını test et
print(f"🔍 Testing connection to: {remote_url}")
connection_test = self.run_git_command("git ls-remote --heads origin")
# Bağlantı durumunu analiz et
if connection_test and connection_test[0] and not any('fatal:' in line.lower() for line in connection_test):
status = 'Connected'
repo_exists = True
detailed = 'Repository exists and accessible'
else:
# Hata mesajlarını kontrol et
error_lines = [line for line in connection_test if 'fatal:' in line.lower()]
if any('repository not found' in line.lower() for line in error_lines):
status = 'Repository Not Found'
repo_exists = False
detailed = 'GitHub repository was deleted or moved'
elif any('permission denied' in line.lower() for line in error_lines):
status = 'Permission Denied'
repo_exists = True
detailed = 'Repository exists but access denied'
else:
status = 'Connection Failed'
repo_exists = False
detailed = 'Cannot connect to repository'
# Repository visibility kontrolü (public/private)
visibility = self.check_repository_visibility(remote_url) if repo_exists else 'unknown'
return {
'has_remote': True,
'remote_url': remote_url,
'connection_status': status,
'repo_exists': repo_exists,
'detailed_status': detailed,
'is_github': 'github.com' in (remote_url or '').lower(),
'visibility': visibility
}
except Exception as e:
return {
'has_remote': False,
'remote_url': None,
'connection_status': f'Error: {str(e)}',
'repo_exists': False,
'detailed_status': f'Error checking remote: {str(e)}'
}
def check_repository_visibility(self, remote_url):
"""Repository'nin public/private durumunu kontrol et"""
if not remote_url or 'github.com' not in remote_url.lower():
return 'unknown'
try:
# GitHub URL'den repo bilgilerini çıkar
# https://github.com/user/repo.git -> user/repo
if remote_url.startswith('https://github.com/'):
repo_path = remote_url.replace('https://github.com/', '').replace('.git', '')
elif remote_url.startswith('git@github.com:'):
repo_path = remote_url.replace('git@github.com:', '').replace('.git', '')
else:
return 'unknown'
# curl ile GitHub API'ye istek at (authentication olmadan)
import subprocess
api_url = f"https://api.github.com/repos/{repo_path}"
try:
result = subprocess.run(
['curl', '-s', '-o', '/dev/null', '-w', '%{http_code}', api_url],
capture_output=True,
text=True,
timeout=10
)
if result.returncode == 0:
status_code = result.stdout.strip()
if status_code == '200':
# Public repository - API erişilebilir
return 'public'
elif status_code == '404':
# Private repository veya mevcut değil
# Git bağlantısı çalışıyorsa private, çalışmıyorsa mevcut değil
return 'private'
else:
return 'unknown'
else:
return 'unknown'
except subprocess.TimeoutExpired:
return 'unknown'
except FileNotFoundError:
# curl yok, alternatif yöntem dene
return self.check_visibility_alternative(repo_path)
except Exception as e:
print(f"⚠️ Visibility check error: {e}")
return 'unknown'
def check_visibility_alternative(self, repo_path):
"""curl yoksa alternatif yöntemle visibility kontrol et"""
try:
import urllib.request
import urllib.error
api_url = f"https://api.github.com/repos/{repo_path}"
try:
with urllib.request.urlopen(api_url, timeout=10) as response:
if response.status == 200:
return 'public'
else:
return 'unknown'
except urllib.error.HTTPError as e:
if e.code == 404:
return 'private'
else:
return 'unknown'
except urllib.error.URLError:
return 'unknown'
except Exception as e:
print(f"⚠️ Alternative visibility check error: {e}")
return 'unknown'
def get_repository_info(self):
"""Repository hakkında detaylı bilgi al"""
info = {
'is_git_repo': os.path.exists(os.path.join(self.project_path, '.git')),
'current_branch': None,
'last_commit': None,
'remote_info': self.remote_status
}
if info['is_git_repo']:
# Mevcut branch
branch_info = self.run_git_command("git branch --show-current")
info['current_branch'] = branch_info[0] if branch_info and branch_info[0] else 'Unknown'
# Son commit
commit_info = self.run_git_command("git log --oneline -1")
info['last_commit'] = commit_info[0] if commit_info and commit_info[0] else 'No commits'
return info
# Global değişken - Bu instance için proje yolu
current_project_path = None
def get_project_path():
"""Proje yolunu al"""
return current_project_path
@app.route('/')
def index():
"""Ana sayfa"""
# Session'a proje yolunu kaydet
project_path = get_project_path()
if project_path:
session['project_path'] = project_path
return render_template('index.html')
@app.route('/api/analyze')
def analyze_project():
"""Proje analizi API"""
# Session'dan proje yolunu al
project_path = session.get('project_path') or get_project_path()
if not project_path:
return jsonify({'error': 'Proje yolu ayarlanmamış'}), 400
# Her istek için yeni GitAnalyzer oluştur
git_analyzer = GitAnalyzer(project_path)
try:
# Dosya listelerini al
tracked_files = git_analyzer.get_tracked_files()
ignored_files = git_analyzer.get_ignored_files()
untracked_files = git_analyzer.get_untracked_files()
git_status = git_analyzer.get_git_status()
# İlk yükleme: GitHub kontrolü ile birlikte
tracked_details = []
for file in tracked_files[:50]: # İlk 50 dosya
info = git_analyzer.get_file_info(file)
# GitHub kontrolü yap
info['github_status'] = git_analyzer.check_file_on_github(file)
tracked_details.append(info)
ignored_details = []
for file in ignored_files[:50]: # İlk 50 dosya
info = git_analyzer.get_file_info(file)
# GitHub kontrolü yap
info['github_status'] = git_analyzer.check_file_on_github(file)
ignored_details.append(info)
# Repository bilgilerini al
repo_info = git_analyzer.get_repository_info()
return jsonify({
'success': True,
'project_path': git_analyzer.project_path,
'repository_info': repo_info,
'tracked_files': {
'count': len(tracked_files),
'files': tracked_details,
'total_count': len(tracked_files),
'loaded_count': len(tracked_details)
},
'ignored_files': {
'count': len(ignored_files),
'files': ignored_details,
'total_count': len(ignored_files),
'loaded_count': len(ignored_details)
},
'untracked_files': {
'count': len(untracked_files),
'files': prepare_untracked_details_fast(git_analyzer, untracked_files[:50]),
'total_count': len(untracked_files),
'loaded_count': min(50, len(untracked_files))
},
'git_status': git_status,
'modified_files_details': prepare_modified_details_fast(git_analyzer, git_status)
})
except Exception as e:
return jsonify({'error': f'Analiz hatası: {str(e)}'}), 500
@app.route('/api/load-more/<category>')
def load_more_files(category):
"""Daha fazla dosya yükle"""
project_path = session.get('project_path') or get_project_path()
if not project_path:
return jsonify({'error': 'Proje yolu ayarlanmamış'}), 400
offset = int(request.args.get('offset', 0))
limit = int(request.args.get('limit', 50))
git_analyzer = GitAnalyzer(project_path)
try:
if category == 'tracked':
all_files = git_analyzer.get_tracked_files()
files = all_files[offset:offset+limit]
details = []
for file in files:
info = git_analyzer.get_file_info(file)
info['github_status'] = git_analyzer.check_file_on_github(file)
details.append(info)
total_count = len(all_files)
elif category == 'ignored':
all_files = git_analyzer.get_ignored_files()
files = all_files[offset:offset+limit]
details = []
for file in files:
info = git_analyzer.get_file_info(file)
info['github_status'] = git_analyzer.check_file_on_github(file)
details.append(info)
total_count = len(all_files)
elif category == 'untracked':
all_files = git_analyzer.get_untracked_files()
files = all_files[offset:offset+limit]
details = prepare_untracked_details(git_analyzer, files)
total_count = len(all_files)
else:
return jsonify({'error': 'Geçersiz kategori'}), 400
return jsonify({
'success': True,
'files': details,
'offset': offset,
'limit': limit,
'loaded_count': len(details),
'total_count': total_count,
'has_more': offset + len(details) < total_count
})
except Exception as e:
return jsonify({'error': f'Yükleme hatası: {str(e)}'}), 500
def prepare_untracked_details_fast(git_analyzer, untracked_files):
"""Untracked dosyalar için GitHub kontrolü ile birlikte"""
details = []
for file in untracked_files:
info = git_analyzer.get_file_info(file)
# GitHub kontrolü yap
info['github_status'] = git_analyzer.check_file_on_github(file)
details.append(info)
return details
def prepare_untracked_details(git_analyzer, untracked_files):
"""Untracked dosyalar için detaylı bilgi hazırla"""
details = []
for file in untracked_files:
info = git_analyzer.get_file_info(file)
# Untracked dosyalar için de GitHub kontrolü yap
info['github_status'] = git_analyzer.check_file_on_github(file)
details.append(info)
return details
def prepare_modified_details_fast(git_analyzer, git_status):
"""Modified dosyalar için GitHub kontrolü ile birlikte"""
details = []
all_modified = []
# Tüm modified dosyaları topla
all_modified.extend([(f, 'Modified') for f in git_status.get('modified', [])])
all_modified.extend([(f, 'Added') for f in git_status.get('added', [])])
all_modified.extend([(f, 'Deleted') for f in git_status.get('deleted', [])])
all_modified.extend([(f, 'Renamed') for f in git_status.get('renamed', [])])
for file_path, status in all_modified[:50]: # İlk 50 dosya
info = git_analyzer.get_file_info(file_path)
info['status'] = status
# GitHub kontrolü yap
info['github_status'] = git_analyzer.check_file_on_github(file_path)
details.append(info)
return details
def prepare_modified_details(git_analyzer, git_status):
"""Modified dosyalar için detaylı bilgi hazırla"""
details = []
all_modified = []
# Tüm modified dosyaları topla
all_modified.extend([(f, 'Modified') for f in git_status.get('modified', [])])
all_modified.extend([(f, 'Added') for f in git_status.get('added', [])])
all_modified.extend([(f, 'Deleted') for f in git_status.get('deleted', [])])
all_modified.extend([(f, 'Renamed') for f in git_status.get('renamed', [])])
for file_path, status in all_modified:
info = git_analyzer.get_file_info(file_path)
info['status'] = status
# Modified dosyalar için de GitHub kontrolü yap
info['github_status'] = git_analyzer.check_file_on_github(file_path)
details.append(info)
return details
@app.route('/api/file-details/<path:filepath>')
def get_file_details(filepath):
"""Belirli bir dosyanın detaylarını al"""
# Session'dan proje yolunu al
project_path = session.get('project_path') or get_project_path()
if not project_path:
return jsonify({'error': 'Proje yolu ayarlanmamış'}), 400
# Yeni GitAnalyzer oluştur
git_analyzer = GitAnalyzer(project_path)
try:
info = git_analyzer.get_file_info(filepath)
# Git bilgilerini ekle
git_info = git_analyzer.run_git_command(f'git log --oneline -1 "{filepath}"')
if git_info and git_info[0]:
info['last_commit'] = git_info[0]
else:
info['last_commit'] = 'Henüz commit edilmemiş'
return jsonify(info)
except Exception as e:
return jsonify({'error': f'Dosya detay hatası: {str(e)}'}), 500
@app.route('/api/check-remote-status')
def check_remote_status():
"""Remote repository durumunu detaylı kontrol et"""
project_path = session.get('project_path') or get_project_path()
if not project_path:
return jsonify({'error': 'Proje yolu ayarlanmamış'}), 400
git_analyzer = GitAnalyzer(project_path)
remote_info = git_analyzer.remote_status
return jsonify({
'success': True,
'remote_info': remote_info,
'recommendations': {
'can_remove': remote_info.get('connection_status') in ['Repository Not Found', 'Connection Failed'],
'needs_new_remote': not remote_info.get('has_remote'),
'is_working': remote_info.get('connection_status') == 'Connected'
}
})
@app.route('/api/remove-remote', methods=['POST'])
def remove_remote():
"""Remote repository bağlantısını kaldır"""
project_path = session.get('project_path') or get_project_path()
if not project_path:
return jsonify({'error': 'Proje yolu ayarlanmamış'}), 400
git_analyzer = GitAnalyzer(project_path)
try:
# Remote'u kaldır
result = git_analyzer.run_git_command("git remote remove origin")
if result and len(result) > 1 and result[1]: # Hata varsa
return jsonify({'error': f'Remote kaldırma hatası: {result[1]}'}), 500
return jsonify({
'success': True,
'message': 'Remote bağlantısı başarıyla kaldırıldı'
})
except Exception as e:
return jsonify({'error': f'Remote kaldırma hatası: {str(e)}'}), 500
@app.route('/api/add-remote', methods=['POST'])
def add_remote():
"""Yeni remote repository bağlantısı ekle"""
project_path = session.get('project_path') or get_project_path()
if not project_path:
return jsonify({'error': 'Proje yolu ayarlanmamış'}), 400
data = request.get_json()
remote_url = data.get('remote_url', '').strip()
if not remote_url:
return jsonify({'error': 'Remote URL gerekli'}), 400
# URL formatını kontrol et
if not (remote_url.startswith('https://github.com/') or remote_url.startswith('git@github.com:')):
return jsonify({'error': 'Geçerli bir GitHub URL\'si girin'}), 400
git_analyzer = GitAnalyzer(project_path)
try:
# Mevcut remote'u kontrol et
existing_remotes = git_analyzer.run_git_command("git remote")
if existing_remotes and 'origin' in existing_remotes:
# Mevcut remote'u güncelle
result = git_analyzer.run_git_command(f'git remote set-url origin "{remote_url}"')
action = 'güncellendi'
else:
# Yeni remote ekle
result = git_analyzer.run_git_command(f'git remote add origin "{remote_url}"')
action = 'eklendi'
if result and len(result) > 1 and result[1]: # Hata varsa
return jsonify({'error': f'Remote {action} hatası: {result[1]}'}), 500
# Bağlantıyı test et
test_result = git_analyzer.run_git_command("git ls-remote --heads origin")
return jsonify({
'success': True,
'message': f'Remote başarıyla {action}',
'connection_test': 'Bağlantı başarılı' if test_result and test_result[0] else 'Bağlantı test edilemedi'
})
except Exception as e:
return jsonify({'error': f'Remote ekleme hatası: {str(e)}'}), 500
def open_browser():
"""Tarayıcıyı aç"""
webbrowser.open('http://localhost:5555')
def find_available_port(start_port=5555):
"""Kullanılabilir port bul"""
import socket
port = start_port
while port < start_port + 100:
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('127.0.0.1', port))
print(f"✅ Port {port} kullanılabilir")
return port
except OSError as e:
print(f"❌ Port {port} kullanımda: {e}")
port += 1
print(f"⚠️ Uygun port bulunamadı, varsayılan {start_port} kullanılıyor")
return start_port
if __name__ == '__main__':
# Proje yolunu environment variable'dan al
project_path = os.environ.get('GIT_PROJECT_PATH', os.getcwd())
print(f"🚀 Git Hub başlatılıyor...")
print(f"📁 Proje yolu: {project_path}")
# Global değişkene proje yolunu kaydet
current_project_path = project_path
# Kullanılabilir port bul
import random
start_port = random.randint(5555, 5600) # Random başlangıç portu
available_port = find_available_port(start_port)
print(f"🔍 Port arama başlangıcı: {start_port}")
print(f"✅ Seçilen port: {available_port}")
def open_browser_with_port():
webbrowser.open(f'http://localhost:{available_port}')
# Tarayıcıyı 3 saniye sonra aç (daha fazla zaman ver)
Timer(3, open_browser_with_port).start()
# Flask uygulamasını başlat
print(f"🌐 Web arayüzü: http://localhost:{available_port}")
print(f"📂 Bu instance proje yolu: {project_path}")
# Development server uyarısını bastır
import logging
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
try:
app.run(host='127.0.0.1', port=available_port, debug=False, use_reloader=False, threaded=True)
except Exception as e:
print(f"❌ Server başlatma hatası: {e}")
input("Devam etmek için Enter'a basın...")