115b4672b1b7ba52f478f20fde5ab4b5a579a9ec
[integration.git] / bootstrap / codesearch / create_config.py
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3
4 """Create configuration for code search."""
5
6 import argparse
7 import json
8 import urllib.request
9 import sys
10
11 DEFAULT_GERRIT = "gerrit.onap.org"
12 API_PREFIX = "/r"
13 API_PROJECTS = "/projects/"
14
15 MAGIC_PREFIX = ")]}'"
16
17 GITWEB_ANCHOR = "#l{line}"
18 GIT_ANCHOR = "#n{line}"
19
20
21 def get_projects_list(gerrit):
22     """Request list of all available projects from ONAP Gerrit."""
23     resp = urllib.request.urlopen("https://{}{}{}".format(gerrit, API_PREFIX, API_PROJECTS))
24     resp_body = resp.read()
25
26     no_magic = resp_body[len(MAGIC_PREFIX):]
27     decoded = no_magic.decode("utf-8")
28     projects = json.loads(decoded)
29
30     return projects.keys()
31
32
33 def create_repos_list(projects, gerrit, ssh, git):
34     """Create a map of all projects to their repositories' URLs."""
35     gerrit_url = "https://{}{}".format(gerrit, API_PREFIX)
36     gerrit_project_url = "{}/{{}}.git".format(gerrit_url)
37     gitweb_code_url = "{}/gitweb?p={{}}.git;hb=HEAD;a=blob;f={{path}}{{anchor}}".format(gerrit_url)
38
39     repos_list = {}
40     for project in projects:
41         project_url = gerrit_project_url.format(project)
42         code_url = gitweb_code_url.format(project)
43         anchor = GITWEB_ANCHOR
44
45         if ssh and len(ssh) == 2:
46             user, port = ssh[0], ssh[1]
47             project_url = "ssh://{}@{}:{}/{}.git".format(user, gerrit, port, project)
48         if git:
49             code_url = "https://{}/{}/tree/{{path}}{{anchor}}".format(git, project)
50             anchor = GIT_ANCHOR
51
52         repos_list[project] = {
53             "url": project_url,
54             "url-pattern": {
55                 "base-url": code_url,
56                 "anchor": anchor
57             }
58         }
59
60     return repos_list
61
62
63 def parse_arguments():
64     """Return parsed command-line arguments."""
65     parser = argparse.ArgumentParser(description=__doc__)
66     parser.add_argument('--gerrit', help='Gerrit address', default=DEFAULT_GERRIT)
67     parser.add_argument('--ssh', help='SSH information: user, port', nargs=2)
68     parser.add_argument('--git', help='external git address')
69
70     return parser.parse_args()
71
72
73 def main():
74     """Main entry point for the script."""
75     arguments = parse_arguments()
76
77     projects = get_projects_list(arguments.gerrit)
78     repos = create_repos_list(projects, arguments.gerrit, arguments.ssh, arguments.git)
79     config = {
80         "max-concurrent-indexers": 2,
81         "dbpath": "data",
82         "health-check-uri": "/healthz",
83         "repos": repos
84     }
85     print(json.dumps(config, sort_keys=True, indent=4, separators=(',', ': ')))
86
87
88 if __name__ == '__main__':
89     sys.exit(main())