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>
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.
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.
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/>.
25 from argparse import ArgumentParser
26 from configparser import ConfigParser
30 from . import metadata
31 from .exception import FDroidException
34 # Get the repo type and address from the given web page. The page is scanned
35 # in a rather naive manner for 'git clone xxxx', 'hg clone xxxx', etc, and
36 # when one of these is found it's assumed that's the information we want.
37 # Returns repotype, address, or None, reason
38 def getrepofrompage(url):
40 req = urllib.request.urlopen(url)
41 if req.getcode() != 200:
42 return (None, 'Unable to get ' + url + ' - return code ' + str(req.getcode()))
43 page = req.read().decode(req.headers.get_content_charset())
46 m = re.search('data-fetch-url="(.*)"', page)
50 if repo.endswith('.git'):
55 # Works for BitBucket (obsolete)
56 index = page.find('hg clone')
59 repo = page[index + 9:]
60 index = repo.find('<')
62 return (None, "Error while getting repo address")
64 repo = repo.split('"')[0]
65 return (repotype, repo)
67 # Works for BitBucket (obsolete)
68 index = page.find('git clone')
71 repo = page[index + 10:]
72 index = repo.find('<')
74 return (None, "Error while getting repo address")
76 repo = repo.split('"')[0]
77 return (repotype, repo)
79 return (None, "No information found." + page)
86 def get_metadata_from_url(app, url):
89 if not os.path.isdir(tmp_dir):
90 logging.info("Creating temporary directory")
93 # Figure out what kind of project it is...
95 app.WebSite = url # by default, we might override it
96 if url.startswith('git://'):
102 elif url.startswith('https://github.com'):
103 projecttype = 'github'
107 app.IssueTracker = url + '/issues'
109 elif url.startswith('https://gitlab.com/'):
110 projecttype = 'gitlab'
111 # git can be fussy with gitlab URLs unless they end in .git
112 if url.endswith('.git'):
117 app.SourceCode = url + '/tree/HEAD'
118 app.IssueTracker = url + '/issues'
119 elif url.startswith('https://notabug.org/'):
120 projecttype = 'notabug'
121 if url.endswith('.git'):
126 app.IssueTracker = url + '/issues'
128 elif url.startswith('https://bitbucket.org/'):
129 if url.endswith('/'):
131 projecttype = 'bitbucket'
132 app.SourceCode = url + '/src'
133 app.IssueTracker = url + '/issues'
134 # Figure out the repo type and adddress...
135 repotype, repo = getrepofrompage(app.SourceCode)
137 raise FDroidException("Unable to determine vcs type. " + repo)
138 elif url.startswith('https://') and url.endswith('.git'):
145 raise FDroidException("Unable to determine the project type. " +
146 "The URL you supplied was not in one of the supported formats. " +
147 "Please consult the manual for a list of supported formats, " +
148 "and supply one of those.")
150 # Ensure we have a sensible-looking repo address at this point. If not, we
151 # might have got a page format we weren't expecting. (Note that we
152 # specifically don't want git@...)
153 if ((repotype != 'bzr' and (not repo.startswith('http://') and
154 not repo.startswith('https://') and
155 not repo.startswith('git://'))) or
157 raise FDroidException("Repo address '{0}' does not seem to be valid".format(repo))
159 # Get a copy of the source so we can extract some info...
160 logging.info('Getting source from ' + repotype + ' repo at ' + repo)
161 build_dir = os.path.join(tmp_dir, 'importer')
162 if os.path.exists(build_dir):
163 shutil.rmtree(build_dir)
164 vcs = common.getvcs(repotype, repo, build_dir)
165 vcs.gotorevision(options.rev)
166 root_dir = get_subdir(build_dir)
168 app.RepoType = repotype
171 return root_dir, build_dir
178 def get_subdir(build_dir):
180 return os.path.join(build_dir, options.subdir)
187 global config, options
189 # Parse command line...
190 parser = ArgumentParser()
191 common.setup_global_opts(parser)
192 parser.add_argument("-u", "--url", default=None,
193 help="Project URL to import from.")
194 parser.add_argument("-s", "--subdir", default=None,
195 help="Path to main android project subdirectory, if not in root.")
196 parser.add_argument("-c", "--categories", default=None,
197 help="Comma separated list of categories.")
198 parser.add_argument("-l", "--license", default=None,
199 help="Overall license of the project.")
200 parser.add_argument("--rev", default=None,
201 help="Allows a different revision (or git branch) to be specified for the initial import")
202 metadata.add_metadata_arguments(parser)
203 options = parser.parse_args()
204 metadata.warnings_action = options.W
206 config = common.read_config(options)
208 apps = metadata.read_metadata()
210 app.UpdateCheckMode = "Tags"
215 local_metadata_files = common.get_local_metadata_files()
216 if local_metadata_files != []:
217 raise FDroidException("This repo already has local metadata: %s" % local_metadata_files[0])
219 if options.url is None and os.path.isdir('.git'):
220 app.AutoName = os.path.basename(os.getcwd())
224 root_dir = get_subdir(os.getcwd())
225 if os.path.exists('build.gradle'):
226 build.gradle = ['yes']
229 repo = git.repo.Repo(root_dir) # git repo
230 for remote in git.Remote.iter_items(repo):
231 if remote.name == 'origin':
232 url = repo.remotes.origin.url
233 if url.startswith('https://git'): # github, gitlab
234 app.SourceCode = url.rstrip('.git')
237 # repo.head.commit.binsha is a bytearray stored in a str
238 build.commit = binascii.hexlify(bytearray(repo.head.commit.binsha))
239 write_local_file = True
241 root_dir, build_dir = get_metadata_from_url(app, options.url)
242 build = metadata.Build()
244 build.disable = 'Generated by import.py - check/set version fields and commit id'
245 write_local_file = False
247 raise FDroidException("Specify project url.")
249 # Extract some information...
250 paths = common.manifest_paths(root_dir, [])
253 versionName, versionCode, package = common.parse_androidmanifests(paths, app)
255 raise FDroidException("Couldn't find package ID")
257 logging.warn("Couldn't find latest version name")
259 logging.warn("Couldn't find latest version code")
261 spec = os.path.join(root_dir, 'buildozer.spec')
262 if os.path.exists(spec):
263 defaults = {'orientation': 'landscape', 'icon': '',
264 'permissions': '', 'android.api': "18"}
265 bconfig = ConfigParser(defaults, allow_no_value=True)
267 package = bconfig.get('app', 'package.domain') + '.' + bconfig.get('app', 'package.name')
268 versionName = bconfig.get('app', 'version')
271 raise FDroidException("No android or kivy project could be found. Specify --subdir?")
273 # Make sure it's actually new...
275 raise FDroidException("Package " + package + " already exists")
277 # Create a build line...
278 build.versionName = versionName or '?'
279 build.versionCode = versionCode or '?'
281 build.subdir = options.subdir
283 app.License = options.license
284 if options.categories:
285 app.Categories = options.categories
286 if os.path.exists(os.path.join(root_dir, 'jni')):
287 build.buildjni = ['yes']
288 if os.path.exists(os.path.join(root_dir, 'build.gradle')):
289 build.gradle = ['yes']
291 metadata.post_metadata_parse(app)
293 app.builds.append(build)
296 metadata.write_metadata('.fdroid.yml', app)
298 # Keep the repo directory to save bandwidth...
299 if not os.path.exists('build'):
301 if build_dir is not None:
302 shutil.move(build_dir, os.path.join('build', package))
303 with open('build/.fdroidvcs-' + package, 'w') as f:
304 f.write(app.RepoType + ' ' + app.Repo)
306 metadatapath = os.path.join('metadata', package + '.txt')
307 metadata.write_metadata(metadatapath, app)
308 logging.info("Wrote " + metadatapath)
311 if __name__ == "__main__":