-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsearch.py
More file actions
104 lines (91 loc) · 3.01 KB
/
Copy pathsearch.py
File metadata and controls
104 lines (91 loc) · 3.01 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
#!/usr/bin/env python3
"""
Python script to search keywords in all project inside Gitlab
and print the files where the occurrences appear.
author: Juan Lozano <lozanotux@gmail.com>
version: 1.0
date: 2024-06-10
pip dependencies:
- requests
"""
# -----------------------------
# Import Section
# -----------------------------
import requests
import sys
import time
import urllib.parse
# -----------------------------
# Variables Section
# -----------------------------
GITLAB_DOMAIN = 'https://{YOUR_GITLAB_INSTANCE_URL}'
GITLAB_TOKEN = '{YOUR_GITLAB_PERSONAL_ACCESS_TOKEN}'
RATE_LIMIT = True
HITS_PER_MINUTE = 25 # Gitlab API Rate Limit
WAIT_TIME = 60 / HITS_PER_MINUTE
ITEMS_PERPAGE = 100
def print_help_message():
print("")
print("Gitlab Search Tool\n")
print("Usage: search [QUERY]\n")
if len(sys.argv) < 2:
print("\n[ERROR] insufficient arguments!")
print_help_message()
exit()
if sys.argv[1] == "--help":
print_help_message()
exit()
# -----------------------------
# Process Section
# -----------------------------
def find_hits():
end = False
page = 1
print("Searching...")
keyword = urllib.parse.quote(sys.argv[1], safe="")
while not end:
contents = requests.get(
f"{GITLAB_DOMAIN}/api/v4/projects"
f"?private_token={GITLAB_TOKEN}"
f"&per_page={ITEMS_PERPAGE}&page={page}"
)
if contents.status_code == 200:
if len(contents.json()) == 0:
end = True
break
else:
contents_data = contents.json()
for i in range(len(contents.json())):
project_id = contents_data[i]['id']
project_name = contents_data[i]['name']
# Rate Limit Control
time.sleep(WAIT_TIME)
hits = requests.get(
f"{GITLAB_DOMAIN}/api/v4/projects/{project_id}/search"
f"?scope=blobs&search={keyword}"
f"&private_token={GITLAB_TOKEN}"
)
if hits.status_code == 200:
if len(hits.json()) > 0:
print("\n")
print('-'*50)
print(f' {project_name}')
print('-'*50)
for j in range(len(hits.json())):
hit_data = hits.json()
print(f"• {hit_data[j]['path']}")
else:
print(
f"[!] Failed to make the HTTP Request for project"
f" {project_name} -"
f" Error Code: {hits.status_code}"
)
else:
print(f"[!] Failed to make the HTTP Request for page {page}")
print(contents.text)
page += 1
if __name__ == "__main__":
try:
find_hits()
except KeyboardInterrupt:
pass