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