chiark / gitweb /
Merge branch 'exceptions' into 'master'
[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 os
22 import shutil
23 import urllib.request
24 from argparse import ArgumentParser
25 from configparser import ConfigParser
26 import logging
27
28 from . import common
29 from . import metadata
30 from .exception import FDroidException
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             raise FDroidException("Unable to determine vcs type. " + repo)
127     elif url.startswith('https://') and url.endswith('.git'):
128         projecttype = 'git'
129         repo = url
130         repotype = 'git'
131         app.SourceCode = ""
132         app.WebSite = ""
133     if not projecttype:
134         raise FDroidException("Unable to determine the project type. " +
135                               "The URL you supplied was not in one of the supported formats. " +
136                               "Please consult the manual for a list of supported formats, " +
137                               "and supply one of those.")
138
139     # Ensure we have a sensible-looking repo address at this point. If not, we
140     # might have got a page format we weren't expecting. (Note that we
141     # specifically don't want git@...)
142     if ((repotype != 'bzr' and (not repo.startswith('http://') and
143         not repo.startswith('https://') and
144         not repo.startswith('git://'))) or
145             ' ' in repo):
146         raise FDroidException("Repo address '{0}' does not seem to be valid".format(repo))
147
148     # Get a copy of the source so we can extract some info...
149     logging.info('Getting source from ' + repotype + ' repo at ' + repo)
150     build_dir = os.path.join(tmp_dir, 'importer')
151     if os.path.exists(build_dir):
152         shutil.rmtree(build_dir)
153     vcs = common.getvcs(repotype, repo, build_dir)
154     vcs.gotorevision(options.rev)
155     root_dir = get_subdir(build_dir)
156
157     app.RepoType = repotype
158     app.Repo = repo
159
160     return root_dir, build_dir
161
162
163 config = None
164 options = None
165
166
167 def get_subdir(build_dir):
168     if options.subdir:
169         return os.path.join(build_dir, options.subdir)
170
171     return build_dir
172
173
174 def main():
175
176     global config, options
177
178     # Parse command line...
179     parser = ArgumentParser()
180     common.setup_global_opts(parser)
181     parser.add_argument("-u", "--url", default=None,
182                         help="Project URL to import from.")
183     parser.add_argument("-s", "--subdir", default=None,
184                         help="Path to main android project subdirectory, if not in root.")
185     parser.add_argument("-c", "--categories", default=None,
186                         help="Comma separated list of categories.")
187     parser.add_argument("-l", "--license", default=None,
188                         help="Overall license of the project.")
189     parser.add_argument("--rev", default=None,
190                         help="Allows a different revision (or git branch) to be specified for the initial import")
191     metadata.add_metadata_arguments(parser)
192     options = parser.parse_args()
193     metadata.warnings_action = options.W
194
195     config = common.read_config(options)
196
197     apps = metadata.read_metadata()
198     app = metadata.App()
199     app.UpdateCheckMode = "Tags"
200
201     root_dir = None
202     build_dir = None
203
204     local_metadata_files = common.get_local_metadata_files()
205     if local_metadata_files != []:
206         raise FDroidException("This repo already has local metadata: %s" % local_metadata_files[0])
207
208     if options.url is None and os.path.isdir('.git'):
209         app.AutoName = os.path.basename(os.getcwd())
210         app.RepoType = 'git'
211
212         build = {}
213         root_dir = get_subdir(os.getcwd())
214         if os.path.exists('build.gradle'):
215             build.gradle = ['yes']
216
217         import git
218         repo = git.repo.Repo(root_dir)  # git repo
219         for remote in git.Remote.iter_items(repo):
220             if remote.name == 'origin':
221                 url = repo.remotes.origin.url
222                 if url.startswith('https://git'):  # github, gitlab
223                     app.SourceCode = url.rstrip('.git')
224                 app.Repo = url
225                 break
226         # repo.head.commit.binsha is a bytearray stored in a str
227         build.commit = binascii.hexlify(bytearray(repo.head.commit.binsha))
228         write_local_file = True
229     elif options.url:
230         root_dir, build_dir = get_metadata_from_url(app, options.url)
231         build = metadata.Build()
232         build.commit = '?'
233         build.disable = 'Generated by import.py - check/set version fields and commit id'
234         write_local_file = False
235     else:
236         raise FDroidException("Specify project url.")
237
238     # Extract some information...
239     paths = common.manifest_paths(root_dir, [])
240     if paths:
241
242         versionName, versionCode, package = common.parse_androidmanifests(paths, app)
243         if not package:
244             raise FDroidException("Couldn't find package ID")
245         if not versionName:
246             logging.warn("Couldn't find latest version name")
247         if not versionCode:
248             logging.warn("Couldn't find latest version code")
249     else:
250         spec = os.path.join(root_dir, 'buildozer.spec')
251         if os.path.exists(spec):
252             defaults = {'orientation': 'landscape', 'icon': '',
253                         'permissions': '', 'android.api': "18"}
254             bconfig = ConfigParser(defaults, allow_no_value=True)
255             bconfig.read(spec)
256             package = bconfig.get('app', 'package.domain') + '.' + bconfig.get('app', 'package.name')
257             versionName = bconfig.get('app', 'version')
258             versionCode = None
259         else:
260             raise FDroidException("No android or kivy project could be found. Specify --subdir?")
261
262     # Make sure it's actually new...
263     if package in apps:
264         raise FDroidException("Package " + package + " already exists")
265
266     # Create a build line...
267     build.versionName = versionName or '?'
268     build.versionCode = versionCode or '?'
269     if options.subdir:
270         build.subdir = options.subdir
271     if options.license:
272         app.License = options.license
273     if options.categories:
274         app.Categories = options.categories
275     if os.path.exists(os.path.join(root_dir, 'jni')):
276         build.buildjni = ['yes']
277     if os.path.exists(os.path.join(root_dir, 'build.gradle')):
278         build.gradle = ['yes']
279
280     metadata.post_metadata_parse(app)
281
282     app.builds.append(build)
283
284     if write_local_file:
285         metadata.write_metadata('.fdroid.yml', app)
286     else:
287         # Keep the repo directory to save bandwidth...
288         if not os.path.exists('build'):
289             os.mkdir('build')
290         if build_dir is not None:
291             shutil.move(build_dir, os.path.join('build', package))
292         with open('build/.fdroidvcs-' + package, 'w') as f:
293             f.write(app.RepoType + ' ' + app.Repo)
294
295         metadatapath = os.path.join('metadata', package + '.txt')
296         metadata.write_metadata(metadatapath, app)
297         logging.info("Wrote " + metadatapath)
298
299
300 if __name__ == "__main__":
301     main()