chiark / gitweb /
import: add option to specify license and categories, auto-detect build.gradle
[fdroidserver.git] / fdroidserver / import.py
1 #!/usr/bin/env python3
2 #
3 # import.py - part of the FDroid server tools
4 # Copyright (C) 2010-13, Ciaran Gultnieks, ciaran@ciarang.com
5 # Copyright (C) 2013-2014 Daniel Martí <mvdan@mvdan.cc>
6 #
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU Affero General Public License for more details.
16 #
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20 import binascii
21 import sys
22 import os
23 import shutil
24 import urllib.request
25 from argparse import ArgumentParser
26 from configparser import ConfigParser
27 import logging
28
29 from . import common
30 from . import metadata
31
32
33 # Get the repo type and address from the given web page. The page is scanned
34 # in a rather naive manner for 'git clone xxxx', 'hg clone xxxx', etc, and
35 # when one of these is found it's assumed that's the information we want.
36 # Returns repotype, address, or None, reason
37 def getrepofrompage(url):
38
39     req = urllib.request.urlopen(url)
40     if req.getcode() != 200:
41         return (None, 'Unable to get ' + url + ' - return code ' + str(req.getcode()))
42     page = req.read()
43
44     # Works for BitBucket
45     index = page.find('hg clone')
46     if index != -1:
47         repotype = 'hg'
48         repo = page[index + 9:]
49         index = repo.find('<')
50         if index == -1:
51             return (None, "Error while getting repo address")
52         repo = repo[:index]
53         repo = repo.split('"')[0]
54         return (repotype, repo)
55
56     # Works for BitBucket
57     index = page.find('git clone')
58     if index != -1:
59         repotype = 'git'
60         repo = page[index + 10:]
61         index = repo.find('<')
62         if index == -1:
63             return (None, "Error while getting repo address")
64         repo = repo[:index]
65         repo = repo.split('"')[0]
66         return (repotype, repo)
67
68     return (None, "No information found." + page)
69
70
71 config = None
72 options = None
73
74
75 def get_metadata_from_url(app, url):
76
77     tmp_dir = 'tmp'
78     if not os.path.isdir(tmp_dir):
79         logging.info("Creating temporary directory")
80         os.makedirs(tmp_dir)
81
82     # Figure out what kind of project it is...
83     projecttype = None
84     app.WebSite = url  # by default, we might override it
85     if url.startswith('git://'):
86         projecttype = 'git'
87         repo = url
88         repotype = 'git'
89         app.SourceCode = ""
90         app.WebSite = ""
91     elif url.startswith('https://github.com'):
92         projecttype = 'github'
93         repo = url
94         repotype = 'git'
95         app.SourceCode = url
96         app.IssueTracker = url + '/issues'
97         app.WebSite = ""
98     elif url.startswith('https://gitlab.com/'):
99         projecttype = 'gitlab'
100         # git can be fussy with gitlab URLs unless they end in .git
101         if url.endswith('.git'):
102             url = url[:-4]
103         repo = url + '.git'
104         repotype = 'git'
105         app.WebSite = url
106         app.SourceCode = url + '/tree/HEAD'
107         app.IssueTracker = url + '/issues'
108     elif url.startswith('https://notabug.org/'):
109         projecttype = 'notabug'
110         if url.endswith('.git'):
111             url = url[:-4]
112         repo = url + '.git'
113         repotype = 'git'
114         app.SourceCode = url
115         app.IssueTracker = url + '/issues'
116         app.WebSite = ""
117     elif url.startswith('https://bitbucket.org/'):
118         if url.endswith('/'):
119             url = url[:-1]
120         projecttype = 'bitbucket'
121         app.SourceCode = url + '/src'
122         app.IssueTracker = url + '/issues'
123         # Figure out the repo type and adddress...
124         repotype, repo = getrepofrompage(app.SourceCode)
125         if not repotype:
126             logging.error("Unable to determine vcs type. " + repo)
127             sys.exit(1)
128     elif url.startswith('https://') and url.endswith('.git'):
129         projecttype = 'git'
130         repo = url
131         repotype = 'git'
132         app.SourceCode = ""
133         app.WebSite = ""
134     if not projecttype:
135         logging.error("Unable to determine the project type.")
136         logging.error("The URL you supplied was not in one of the supported formats. Please consult")
137         logging.error("the manual for a list of supported formats, and supply one of those.")
138         sys.exit(1)
139
140     # Ensure we have a sensible-looking repo address at this point. If not, we
141     # might have got a page format we weren't expecting. (Note that we
142     # specifically don't want git@...)
143     if ((repotype != 'bzr' and (not repo.startswith('http://') and
144         not repo.startswith('https://') and
145         not repo.startswith('git://'))) or
146             ' ' in repo):
147         logging.error("Repo address '{0}' does not seem to be valid".format(repo))
148         sys.exit(1)
149
150     # Get a copy of the source so we can extract some info...
151     logging.info('Getting source from ' + repotype + ' repo at ' + repo)
152     build_dir = os.path.join(tmp_dir, 'importer')
153     if os.path.exists(build_dir):
154         shutil.rmtree(build_dir)
155     vcs = common.getvcs(repotype, repo, build_dir)
156     vcs.gotorevision(options.rev)
157     root_dir = get_subdir(build_dir)
158
159     app.RepoType = repotype
160     app.Repo = repo
161
162     return root_dir, build_dir
163
164
165 config = None
166 options = None
167
168
169 def get_subdir(build_dir):
170     if options.subdir:
171         return os.path.join(build_dir, options.subdir)
172
173     return build_dir
174
175
176 def main():
177
178     global config, options
179
180     # Parse command line...
181     parser = ArgumentParser()
182     common.setup_global_opts(parser)
183     parser.add_argument("-u", "--url", default=None,
184                         help="Project URL to import from.")
185     parser.add_argument("-s", "--subdir", default=None,
186                         help="Path to main android project subdirectory, if not in root.")
187     parser.add_argument("-c", "--categories", default=None,
188                         help="Comma separated list of categories.")
189     parser.add_argument("-l", "--license", default=None,
190                         help="Overall license of the project.")
191     parser.add_argument("--rev", default=None,
192                         help="Allows a different revision (or git branch) to be specified for the initial import")
193     metadata.add_metadata_arguments(parser)
194     options = parser.parse_args()
195     metadata.warnings_action = options.W
196
197     config = common.read_config(options)
198
199     apps = metadata.read_metadata()
200     app = metadata.App()
201     app.UpdateCheckMode = "Tags"
202
203     root_dir = None
204     build_dir = None
205
206     local_metadata_files = common.get_local_metadata_files()
207     if local_metadata_files != []:
208         logging.error("This repo already has local metadata: %s" % local_metadata_files[0])
209         sys.exit(1)
210
211     if options.url is None and os.path.isdir('.git'):
212         app.AutoName = os.path.basename(os.getcwd())
213         app.RepoType = 'git'
214
215         build = {}
216         root_dir = get_subdir(os.getcwd())
217         if os.path.exists('build.gradle'):
218             build.gradle = ['yes']
219
220         import git
221         repo = git.repo.Repo(root_dir)  # git repo
222         for remote in git.Remote.iter_items(repo):
223             if remote.name == 'origin':
224                 url = repo.remotes.origin.url
225                 if url.startswith('https://git'):  # github, gitlab
226                     app.SourceCode = url.rstrip('.git')
227                 app.Repo = url
228                 break
229         # repo.head.commit.binsha is a bytearray stored in a str
230         build.commit = binascii.hexlify(bytearray(repo.head.commit.binsha))
231         write_local_file = True
232     elif options.url:
233         root_dir, build_dir = get_metadata_from_url(app, options.url)
234         build = metadata.Build()
235         build.commit = '?'
236         build.disable = 'Generated by import.py - check/set version fields and commit id'
237         write_local_file = False
238     else:
239         logging.error("Specify project url.")
240         sys.exit(1)
241
242     # Extract some information...
243     paths = common.manifest_paths(root_dir, [])
244     if paths:
245
246         versionName, versionCode, package = common.parse_androidmanifests(paths, app)
247         if not package:
248             logging.error("Couldn't find package ID")
249             sys.exit(1)
250         if not versionName:
251             logging.warn("Couldn't find latest version name")
252         if not versionCode:
253             logging.warn("Couldn't find latest version code")
254     else:
255         spec = os.path.join(root_dir, 'buildozer.spec')
256         if os.path.exists(spec):
257             defaults = {'orientation': 'landscape', 'icon': '',
258                         'permissions': '', 'android.api': "18"}
259             bconfig = ConfigParser(defaults, allow_no_value=True)
260             bconfig.read(spec)
261             package = bconfig.get('app', 'package.domain') + '.' + bconfig.get('app', 'package.name')
262             versionName = bconfig.get('app', 'version')
263             versionCode = None
264         else:
265             logging.error("No android or kivy project could be found. Specify --subdir?")
266             sys.exit(1)
267
268     # Make sure it's actually new...
269     if package in apps:
270         logging.error("Package " + package + " already exists")
271         sys.exit(1)
272
273     # Create a build line...
274     build.versionName = versionName or '?'
275     build.versionCode = versionCode or '?'
276     if options.subdir:
277         build.subdir = options.subdir
278     if options.license:
279         app.License = options.license
280     if options.categories:
281         app.Categories = options.categories
282     if os.path.exists(os.path.join(root_dir, 'jni')):
283         build.buildjni = ['yes']
284     if os.path.exists(os.path.join(root_dir, 'build.gradle')):
285         build.gradle = ['yes']
286
287     metadata.post_metadata_parse(app)
288
289     app.builds.append(build)
290
291     if write_local_file:
292         metadata.write_metadata('.fdroid.yml', app)
293     else:
294         # Keep the repo directory to save bandwidth...
295         if not os.path.exists('build'):
296             os.mkdir('build')
297         if build_dir is not None:
298             shutil.move(build_dir, os.path.join('build', package))
299         with open('build/.fdroidvcs-' + package, 'w') as f:
300             f.write(app.RepoType + ' ' + app.Repo)
301
302         metadatapath = os.path.join('metadata', package + '.txt')
303         metadata.write_metadata(metadatapath, app)
304         logging.info("Wrote " + metadatapath)
305
306
307 if __name__ == "__main__":
308     main()