chiark / gitweb /
import: get build dir from settings.gradle
[fdroidserver.git] / fdroidserver / import.py
index 60146536c3a162bb45ce1e9dcc27451ca0e4972b..550e7469398d166bcfc0db35b5fec2bf244bb4f3 100644 (file)
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 import binascii
-import sys
 import os
+import re
 import shutil
 import urllib.request
 from argparse import ArgumentParser
 from configparser import ConfigParser
 import logging
 
+from . import _
 from . import common
 from . import metadata
+from .exception import FDroidException
+
+
+SETTINGS_GRADLE = re.compile('''include\s+['"]:([^'"]*)['"]''')
 
 
 # Get the repo type and address from the given web page. The page is scanned
@@ -39,33 +44,43 @@ def getrepofrompage(url):
     req = urllib.request.urlopen(url)
     if req.getcode() != 200:
         return (None, 'Unable to get ' + url + ' - return code ' + str(req.getcode()))
-    page = req.read()
+    page = req.read().decode(req.headers.get_content_charset())
 
     # Works for BitBucket
+    m = re.search('data-fetch-url="(.*)"', page)
+    if m is not None:
+        repo = m.group(1)
+
+        if repo.endswith('.git'):
+            return ('git', repo)
+
+        return ('hg', repo)
+
+    # Works for BitBucket (obsolete)
     index = page.find('hg clone')
     if index != -1:
         repotype = 'hg'
         repo = page[index + 9:]
         index = repo.find('<')
         if index == -1:
-            return (None, "Error while getting repo address")
+            return (None, _("Error while getting repo address"))
         repo = repo[:index]
         repo = repo.split('"')[0]
         return (repotype, repo)
 
-    # Works for BitBucket
+    # Works for BitBucket (obsolete)
     index = page.find('git clone')
     if index != -1:
         repotype = 'git'
         repo = page[index + 10:]
         index = repo.find('<')
         if index == -1:
-            return (None, "Error while getting repo address")
+            return (None, _("Error while getting repo address"))
         repo = repo[:index]
         repo = repo.split('"')[0]
         return (repotype, repo)
 
-    return (None, "No information found." + page)
+    return (None, _("No information found.") + page)
 
 
 config = None
@@ -76,7 +91,7 @@ def get_metadata_from_url(app, url):
 
     tmp_dir = 'tmp'
     if not os.path.isdir(tmp_dir):
-        logging.info("Creating temporary directory")
+        logging.info(_("Creating temporary directory"))
         os.makedirs(tmp_dir)
 
     # Figure out what kind of project it is...
@@ -105,6 +120,15 @@ def get_metadata_from_url(app, url):
         app.WebSite = url
         app.SourceCode = url + '/tree/HEAD'
         app.IssueTracker = url + '/issues'
+    elif url.startswith('https://notabug.org/'):
+        projecttype = 'notabug'
+        if url.endswith('.git'):
+            url = url[:-4]
+        repo = url + '.git'
+        repotype = 'git'
+        app.SourceCode = url
+        app.IssueTracker = url + '/issues'
+        app.WebSite = ""
     elif url.startswith('https://bitbucket.org/'):
         if url.endswith('/'):
             url = url[:-1]
@@ -112,15 +136,20 @@ def get_metadata_from_url(app, url):
         app.SourceCode = url + '/src'
         app.IssueTracker = url + '/issues'
         # Figure out the repo type and adddress...
-        repotype, repo = getrepofrompage(app.SourceCode)
+        repotype, repo = getrepofrompage(url)
         if not repotype:
-            logging.error("Unable to determine vcs type. " + repo)
-            sys.exit(1)
+            raise FDroidException("Unable to determine vcs type. " + repo)
+    elif url.startswith('https://') and url.endswith('.git'):
+        projecttype = 'git'
+        repo = url
+        repotype = 'git'
+        app.SourceCode = ""
+        app.WebSite = ""
     if not projecttype:
-        logging.error("Unable to determine the project type.")
-        logging.error("The URL you supplied was not in one of the supported formats. Please consult")
-        logging.error("the manual for a list of supported formats, and supply one of those.")
-        sys.exit(1)
+        raise FDroidException("Unable to determine the project type. " +
+                              "The URL you supplied was not in one of the supported formats. " +
+                              "Please consult the manual for a list of supported formats, " +
+                              "and supply one of those.")
 
     # Ensure we have a sensible-looking repo address at this point. If not, we
     # might have got a page format we weren't expecting. (Note that we
@@ -129,8 +158,7 @@ def get_metadata_from_url(app, url):
         not repo.startswith('https://') and
         not repo.startswith('git://'))) or
             ' ' in repo):
-        logging.error("Repo address '{0}' does not seem to be valid".format(repo))
-        sys.exit(1)
+        raise FDroidException("Repo address '{0}' does not seem to be valid".format(repo))
 
     # Get a copy of the source so we can extract some info...
     logging.info('Getting source from ' + repotype + ' repo at ' + repo)
@@ -155,6 +183,13 @@ def get_subdir(build_dir):
     if options.subdir:
         return os.path.join(build_dir, options.subdir)
 
+    settings_gradle = os.path.join(build_dir, 'settings.gradle')
+    if os.path.exists(settings_gradle):
+        with open(settings_gradle) as fp:
+            m = SETTINGS_GRADLE.search(fp.read())
+            if m:
+                return os.path.join(build_dir, m.group(1))
+
     return build_dir
 
 
@@ -166,11 +201,15 @@ def main():
     parser = ArgumentParser()
     common.setup_global_opts(parser)
     parser.add_argument("-u", "--url", default=None,
-                        help="Project URL to import from.")
+                        help=_("Project URL to import from."))
     parser.add_argument("-s", "--subdir", default=None,
-                        help="Path to main android project subdirectory, if not in root.")
+                        help=_("Path to main Android project subdirectory, if not in root."))
+    parser.add_argument("-c", "--categories", default=None,
+                        help=_("Comma separated list of categories."))
+    parser.add_argument("-l", "--license", default=None,
+                        help=_("Overall license of the project."))
     parser.add_argument("--rev", default=None,
-                        help="Allows a different revision (or git branch) to be specified for the initial import")
+                        help=_("Allows a different revision (or git branch) to be specified for the initial import"))
     metadata.add_metadata_arguments(parser)
     options = parser.parse_args()
     metadata.warnings_action = options.W
@@ -186,8 +225,7 @@ def main():
 
     local_metadata_files = common.get_local_metadata_files()
     if local_metadata_files != []:
-        logging.error("This repo already has local metadata: %s" % local_metadata_files[0])
-        sys.exit(1)
+        raise FDroidException(_("This repo already has local metadata: %s") % local_metadata_files[0])
 
     if options.url is None and os.path.isdir('.git'):
         app.AutoName = os.path.basename(os.getcwd())
@@ -217,21 +255,19 @@ def main():
         build.disable = 'Generated by import.py - check/set version fields and commit id'
         write_local_file = False
     else:
-        logging.error("Specify project url.")
-        sys.exit(1)
+        raise FDroidException("Specify project url.")
 
     # Extract some information...
     paths = common.manifest_paths(root_dir, [])
     if paths:
 
-        version, vercode, package = common.parse_androidmanifests(paths, app)
+        versionName, versionCode, package = common.parse_androidmanifests(paths, app)
         if not package:
-            logging.error("Couldn't find package ID")
-            sys.exit(1)
-        if not version:
-            logging.warn("Couldn't find latest version name")
-        if not vercode:
-            logging.warn("Couldn't find latest version code")
+            raise FDroidException(_("Couldn't find package ID"))
+        if not versionName:
+            logging.warn(_("Couldn't find latest version name"))
+        if not versionCode:
+            logging.warn(_("Couldn't find latest version code"))
     else:
         spec = os.path.join(root_dir, 'buildozer.spec')
         if os.path.exists(spec):
@@ -240,24 +276,28 @@ def main():
             bconfig = ConfigParser(defaults, allow_no_value=True)
             bconfig.read(spec)
             package = bconfig.get('app', 'package.domain') + '.' + bconfig.get('app', 'package.name')
-            version = bconfig.get('app', 'version')
-            vercode = None
+            versionName = bconfig.get('app', 'version')
+            versionCode = None
         else:
-            logging.error("No android or kivy project could be found. Specify --subdir?")
-            sys.exit(1)
+            raise FDroidException(_("No android or kivy project could be found. Specify --subdir?"))
 
     # Make sure it's actually new...
     if package in apps:
-        logging.error("Package " + package + " already exists")
-        sys.exit(1)
+        raise FDroidException("Package " + package + " already exists")
 
     # Create a build line...
-    build.version = version or '?'
-    build.vercode = vercode or '?'
+    build.versionName = versionName or '?'
+    build.versionCode = versionCode or '?'
     if options.subdir:
         build.subdir = options.subdir
+    if options.license:
+        app.License = options.license
+    if options.categories:
+        app.Categories = options.categories
     if os.path.exists(os.path.join(root_dir, 'jni')):
         build.buildjni = ['yes']
+    if os.path.exists(os.path.join(root_dir, 'build.gradle')):
+        build.gradle = ['yes']
 
     metadata.post_metadata_parse(app)
 
@@ -274,7 +314,7 @@ def main():
         with open('build/.fdroidvcs-' + package, 'w') as f:
             f.write(app.RepoType + ' ' + app.Repo)
 
-        metadatapath = os.path.join('metadata', package + '.txt')
+        metadatapath = os.path.join('metadata', package + '.yml')
         metadata.write_metadata(metadatapath, app)
         logging.info("Wrote " + metadatapath)