chiark / gitweb /
import app into fdroid directly from git clone
[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 config = None
71 options = None
72
73
74 def get_metadata_from_url(app, url):
75
76     tmp_dir = 'tmp'
77     if not os.path.isdir(tmp_dir):
78         logging.info("Creating temporary directory")
79         os.makedirs(tmp_dir)
80
81     # Figure out what kind of project it is...
82     projecttype = None
83     app.WebSite = url  # by default, we might override it
84     if url.startswith('git://'):
85         projecttype = 'git'
86         repo = url
87         repotype = 'git'
88         app.SourceCode = ""
89         app.WebSite = ""
90     elif url.startswith('https://github.com'):
91         projecttype = 'github'
92         repo = url
93         repotype = 'git'
94         app.SourceCode = url
95         app.IssueTracker = url + '/issues'
96         app.WebSite = ""
97     elif url.startswith('https://gitlab.com/'):
98         projecttype = 'gitlab'
99         # git can be fussy with gitlab URLs unless they end in .git
100         if url.endswith('.git'):
101             url = url[:-4]
102         repo = url + '.git'
103         repotype = 'git'
104         app.WebSite = url
105         app.SourceCode = url + '/tree/HEAD'
106         app.IssueTracker = url + '/issues'
107     elif url.startswith('https://bitbucket.org/'):
108         if url.endswith('/'):
109             url = url[:-1]
110         projecttype = 'bitbucket'
111         app.SourceCode = url + '/src'
112         app.IssueTracker = url + '/issues'
113         # Figure out the repo type and adddress...
114         repotype, repo = getrepofrompage(app.SourceCode)
115         if not repotype:
116             logging.error("Unable to determine vcs type. " + repo)
117             sys.exit(1)
118     if not projecttype:
119         logging.error("Unable to determine the project type.")
120         logging.error("The URL you supplied was not in one of the supported formats. Please consult")
121         logging.error("the manual for a list of supported formats, and supply one of those.")
122         sys.exit(1)
123
124     # Ensure we have a sensible-looking repo address at this point. If not, we
125     # might have got a page format we weren't expecting. (Note that we
126     # specifically don't want git@...)
127     if ((repotype != 'bzr' and (not repo.startswith('http://') and
128         not repo.startswith('https://') and
129         not repo.startswith('git://'))) or
130             ' ' in repo):
131         logging.error("Repo address '{0}' does not seem to be valid".format(repo))
132         sys.exit(1)
133
134     # Get a copy of the source so we can extract some info...
135     logging.info('Getting source from ' + repotype + ' repo at ' + repo)
136     build_dir = os.path.join(tmp_dir, 'importer')
137     if os.path.exists(build_dir):
138         shutil.rmtree(build_dir)
139     vcs = common.getvcs(repotype, repo, build_dir)
140     vcs.gotorevision(options.rev)
141     root_dir = get_subdir(build_dir)
142
143     app.RepoType = repotype
144     app.Repo = repo
145
146     return root_dir, build_dir
147
148
149 config = None
150 options = None
151
152
153 def get_subdir(build_dir):
154     if options.subdir:
155         return os.path.join(build_dir, options.subdir)
156
157     return build_dir
158
159
160 def main():
161
162     global config, options
163
164     # Parse command line...
165     parser = ArgumentParser()
166     common.setup_global_opts(parser)
167     parser.add_argument("-u", "--url", default=None,
168                         help="Project URL to import from.")
169     parser.add_argument("-s", "--subdir", default=None,
170                         help="Path to main android project subdirectory, if not in root.")
171     parser.add_argument("--rev", default=None,
172                         help="Allows a different revision (or git branch) to be specified for the initial import")
173     options = parser.parse_args()
174
175     config = common.read_config(options)
176
177     apps = metadata.read_metadata()
178     app = metadata.App()
179     app.UpdateCheckMode = "Tags"
180
181     root_dir = None
182     build_dir = None
183
184     local_metadata_files = common.get_local_metadata_files()
185     if local_metadata_files != []:
186         logging.error("This repo already has local metadata: %s" % local_metadata_files[0])
187         sys.exit(1)
188
189     if options.url is None and os.path.isdir('.git'):
190         app.AutoName = os.path.basename(os.getcwd())
191         app.RepoType = 'git'
192
193         build = {}
194         root_dir = get_subdir(os.getcwd())
195         if os.path.exists('build.gradle'):
196             build.gradle = ['yes']
197
198         import git
199         repo = git.repo.Repo(root_dir)  # git repo
200         for remote in git.Remote.iter_items(repo):
201             if remote.name == 'origin':
202                 url = repo.remotes.origin.url
203                 if url.startswith('https://git'):  # github, gitlab
204                     app.SourceCode = url.rstrip('.git')
205                 app.Repo = url
206                 break
207         # repo.head.commit.binsha is a bytearray stored in a str
208         build.commit = binascii.hexlify(bytearray(repo.head.commit.binsha))
209         write_local_file = True
210     elif options.url:
211         root_dir, build_dir = get_metadata_from_url(app, options.url)
212         build = metadata.Build()
213         build.commit = '?'
214         build.disable = 'Generated by import.py - check/set version fields and commit id'
215         write_local_file = False
216     else:
217         logging.error("Specify project url.")
218         sys.exit(1)
219
220     # Extract some information...
221     paths = common.manifest_paths(root_dir, [])
222     if paths:
223
224         version, vercode, package = common.parse_androidmanifests(paths, app)
225         if not package:
226             logging.error("Couldn't find package ID")
227             sys.exit(1)
228         if not version:
229             logging.warn("Couldn't find latest version name")
230         if not vercode:
231             logging.warn("Couldn't find latest version code")
232     else:
233         spec = os.path.join(root_dir, 'buildozer.spec')
234         if os.path.exists(spec):
235             defaults = {'orientation': 'landscape', 'icon': '',
236                         'permissions': '', 'android.api': "18"}
237             bconfig = ConfigParser(defaults, allow_no_value=True)
238             bconfig.read(spec)
239             package = bconfig.get('app', 'package.domain') + '.' + bconfig.get('app', 'package.name')
240             version = bconfig.get('app', 'version')
241             vercode = None
242         else:
243             logging.error("No android or kivy project could be found. Specify --subdir?")
244             sys.exit(1)
245
246     # Make sure it's actually new...
247     if package in apps:
248         logging.error("Package " + package + " already exists")
249         sys.exit(1)
250
251     # Create a build line...
252     build.version = version or '?'
253     build.vercode = vercode or '?'
254     if options.subdir:
255         build.subdir = options.subdir
256     if os.path.exists(os.path.join(root_dir, 'jni')):
257         build.buildjni = ['yes']
258
259     metadata.post_metadata_parse(app)
260
261     app.builds.append(build)
262
263     if write_local_file:
264         metadata.write_metadata('.fdroid.yaml', app)
265     else:
266         # Keep the repo directory to save bandwidth...
267         if not os.path.exists('build'):
268             os.mkdir('build')
269         if build_dir is not None:
270             shutil.move(build_dir, os.path.join('build', package))
271         with open('build/.fdroidvcs-' + package, 'w') as f:
272             f.write(app.RepoType + ' ' + app.Repo)
273
274         metadatapath = os.path.join('metadata', package + '.txt')
275         metadata.write_metadata(metadatapath, app)
276         logging.info("Wrote " + metadatapath)
277
278
279 if __name__ == "__main__":
280     main()