celiolr commited on
Commit
61759de
·
verified ·
1 Parent(s): 4420cb1

Deploy Docker: scripts\list_tfs_docs.py

Browse files
Files changed (1) hide show
  1. scripts//list_tfs_docs.py +203 -0
scripts//list_tfs_docs.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Script to list documents in specified TFS repositories.
4
+ Can receive repository patterns from the command line or use a predefined list.
5
+ """
6
+
7
+ import sys
8
+ import argparse
9
+ from pathlib import Path
10
+ import logging
11
+ import re
12
+ from typing import List, Dict, Tuple
13
+
14
+ # Add the app directory to the path
15
+ sys.path.append(str(Path(__file__).parent.parent))
16
+
17
+ from app.utils.tfs_client import TFSClient
18
+ from app.core.config import settings
19
+
20
+ # --- LISTA DE REPOSITÓRIOS PADRÃO ---
21
+ DEFAULT_REPO_PATTERNS = [
22
+ "cpcstools",
23
+ "PEX",
24
+ ]
25
+ DEFAULT_REPO_PATTERNS = []
26
+
27
+ # --- LISTA DE ARQUIVOS E PASTAS EXCLUÍDOS (Case Insensitive) ---
28
+ EXCLUDED_NAMES = [
29
+ "lib_list.txt",
30
+ "pull_request_template.md",
31
+ "contributing.md",
32
+ ".azuredevops"
33
+ ]
34
+
35
+ # --- PASTAS PERMITIDAS PARA BUSCA (além da raiz) ---
36
+ ALLOWED_DOC_FOLDERS = [
37
+ "doc", "docs",
38
+ "documentacao", "documentação",
39
+ "manual", "manuais",
40
+ # "spec", "specs"
41
+ ]
42
+ # ------------------------------------
43
+
44
+ def is_path_allowed(file_path_str: str) -> bool:
45
+ """
46
+ Verifica se o arquivo deve ser incluído baseado na sua localização.
47
+ Regra: Aceita se estiver na raiz OU se estiver dentro de uma pasta permitida de PRIMEIRO NÍVEL.
48
+ """
49
+ path_str = file_path_str.replace('\\', '/')
50
+ if path_str.startswith('/'):
51
+ path_str = path_str[1:]
52
+
53
+ path_obj = Path(path_str)
54
+ parts = path_obj.parts
55
+
56
+ # 1. Se só tem uma parte (ex: "arquivo.doc"), está na raiz -> PERMITIDO
57
+ if len(parts) == 1:
58
+ return True
59
+
60
+ # 2. Verifica se a PRIMEIRA pasta do caminho está na lista de permitidas
61
+ # Ex: "docs/manual.pdf" -> parts[0] é "docs" -> PERMITIDO
62
+ # Ex: "src/codigo/docs/info.txt" -> parts[0] é "src" -> NEGADO
63
+ first_folder = parts[0]
64
+ if first_folder.lower() in ALLOWED_DOC_FOLDERS:
65
+ return True
66
+
67
+ return False
68
+
69
+ def filter_latest_versions(file_paths: List[str]) -> List[str]:
70
+ """
71
+ Filtra arquivos para manter apenas a versão mais recente.
72
+ Trata 'Arquivo.ext' como versão 0 e 'Arquivo_V1.ext' como versão 1.
73
+ """
74
+ version_pattern = re.compile(r'^(.*?)[\s_]*[vV](\d+)$')
75
+ versioned_files: Dict[str, Tuple[int, str]] = {}
76
+
77
+ for file_path in file_paths:
78
+ path_obj = Path(file_path)
79
+ stem = path_obj.stem
80
+ suffix = path_obj.suffix
81
+ parent = str(path_obj.parent)
82
+
83
+ match = version_pattern.match(stem)
84
+
85
+ if match:
86
+ base_name = match.group(1).strip()
87
+ version = int(match.group(2))
88
+ else:
89
+ base_name = stem.strip()
90
+ version = 0
91
+
92
+ key = f"{parent}/{base_name}{suffix}".lower()
93
+
94
+ if key in versioned_files:
95
+ current_max_ver, _ = versioned_files[key]
96
+ if version > current_max_ver:
97
+ versioned_files[key] = (version, file_path)
98
+ else:
99
+ versioned_files[key] = (version, file_path)
100
+
101
+ return sorted([info[1] for info in versioned_files.values()])
102
+
103
+ def main():
104
+ """Main function to list documents"""
105
+ parser = argparse.ArgumentParser(description="List documents in TFS repositories using name patterns")
106
+ parser.add_argument(
107
+ "patterns",
108
+ nargs='*',
109
+ default=None,
110
+ help="Optional: List of repository name patterns to search for"
111
+ )
112
+ parser.add_argument(
113
+ "--verbose", "-v",
114
+ action="store_true",
115
+ help="Enable verbose logging"
116
+ )
117
+ args = parser.parse_args()
118
+
119
+ if args.patterns:
120
+ repo_patterns_to_use = args.patterns
121
+ print("🔍 Using repository patterns from command line.")
122
+ elif DEFAULT_REPO_PATTERNS:
123
+ repo_patterns_to_use = DEFAULT_REPO_PATTERNS
124
+ print("🔍 Using predefined repository patterns from the script.")
125
+ else:
126
+ # Se não houver padrões definidos, busca em TODOS os repositórios
127
+ repo_patterns_to_use = [None]
128
+ print("🔍 No patterns provided. Searching ALL repositories.")
129
+
130
+ log_level = logging.DEBUG if args.verbose else logging.INFO
131
+ logging.basicConfig(
132
+ level=log_level,
133
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
134
+ )
135
+ logger = logging.getLogger(__name__)
136
+
137
+ if not all([settings.tfs_url, settings.tfs_pat, settings.tfs_project]):
138
+ print("❌ TFS not configured. Please set TFS_URL, TFS_PAT, and TFS_PROJECT in your .env file.")
139
+ return
140
+
141
+ print("=" * 60)
142
+ print(" TFS Document Lister (Smart Filter v5)")
143
+ print("=" * 60)
144
+
145
+ try:
146
+ tfs_client = TFSClient()
147
+ if not tfs_client.connection:
148
+ print("❌ Failed to connect to TFS. Check your configuration and network.")
149
+ return
150
+
151
+ supported_extensions = settings.supported_extensions
152
+ print(f"🔍 Searching for files with extensions: {', '.join(supported_extensions)}")
153
+ print(f"📂 Allowed root folders: {', '.join(ALLOWED_DOC_FOLDERS)}")
154
+ print(f"🚫 Excluding names: {', '.join(EXCLUDED_NAMES)}\n")
155
+
156
+ for pattern in repo_patterns_to_use:
157
+ if pattern:
158
+ print(f"--- Searching for repositories matching pattern: '{pattern}' ---")
159
+ else:
160
+ print("--- Searching for ALL repositories ---")
161
+
162
+ matching_repos = tfs_client.get_repositories(name_pattern=pattern)
163
+
164
+ if not matching_repos:
165
+ msg = f"matching '{pattern}'" if pattern else ""
166
+ print(f" No repositories found {msg}.")
167
+ continue
168
+
169
+ for repo in matching_repos:
170
+ repo_url = getattr(repo, 'web_url', getattr(repo, 'remote_url', 'URL not available'))
171
+
172
+ print(f"\n Inspecting repository: {repo.name}")
173
+ print(f" URL: {repo_url}")
174
+
175
+ files = tfs_client.list_files_in_repo(repo.name, supported_extensions)
176
+
177
+ non_excluded_files = [
178
+ f for f in files
179
+ if Path(f).name.lower() not in [e.lower() for e in EXCLUDED_NAMES] and
180
+ not any(part.lower() in [e.lower() for e in EXCLUDED_NAMES] for part in Path(f).parts)
181
+ ]
182
+
183
+ location_filtered_files = [f for f in non_excluded_files if is_path_allowed(f)]
184
+
185
+ final_files = filter_latest_versions(location_filtered_files)
186
+
187
+ if final_files:
188
+ print(f" Found {len(final_files)} supported documents (filtered):")
189
+ for file_path in final_files:
190
+ print(f" - {file_path}")
191
+ else:
192
+ print(" No supported documents found after filtering.")
193
+
194
+ print("-" * (len(pattern) + 40 if pattern else 60) + "\n")
195
+
196
+ except Exception as e:
197
+ logger.error(f"An unexpected error occurred: {e}", exc_info=True)
198
+ print(f"❌ An unexpected error occurred. Check the logs for details.")
199
+
200
+ print("🎉 Done!")
201
+
202
+ if __name__ == "__main__":
203
+ main()