chiark / gitweb /
Open metadata files in only one place
[fdroidserver.git] / fdroidserver / import.py
index c1c01d358d7bbadb3c8bdb546261a07c8641e1c5..e1d69c3c3eb91f63bcbf65469775d74ff8404735 100644 (file)
@@ -22,7 +22,7 @@ import sys
 import os
 import shutil
 import urllib
-from optparse import OptionParser
+from argparse import ArgumentParser
 from ConfigParser import ConfigParser
 import logging
 import common
@@ -70,76 +70,47 @@ config = None
 options = None
 
 
-def main():
-
-    global config, options
-
-    # Parse command line...
-    parser = OptionParser()
-    parser.add_option("-v", "--verbose", action="store_true", default=False,
-                      help="Spew out even more information than normal")
-    parser.add_option("-q", "--quiet", action="store_true", default=False,
-                      help="Restrict output to warnings and errors")
-    parser.add_option("-u", "--url", default=None,
-                      help="Project URL to import from.")
-    parser.add_option("-s", "--subdir", default=None,
-                      help="Path to main android project subdirectory, if not in root.")
-    parser.add_option("--rev", default=None,
-                      help="Allows a different revision (or git branch) to be specified for the initial import")
-    (options, args) = parser.parse_args()
-
-    config = common.read_config(options)
-
-    if not options.url:
-        logging.error("Specify project url.")
-        sys.exit(1)
-    url = options.url
+def get_metadata_from_url(app, url):
 
     tmp_dir = 'tmp'
     if not os.path.isdir(tmp_dir):
         logging.info("Creating temporary directory")
         os.makedirs(tmp_dir)
 
-    # Get all apps...
-    apps = metadata.read_metadata()
-
     # Figure out what kind of project it is...
     projecttype = None
-    issuetracker = None
-    license = None
-    website = url  # by default, we might override it
+    app.WebSite = url  # by default, we might override it
     if url.startswith('git://'):
         projecttype = 'git'
         repo = url
         repotype = 'git'
-        sourcecode = ""
-        website = ""
+        app.SourceCode = ""
+        app.WebSite = ""
     elif url.startswith('https://github.com'):
         projecttype = 'github'
         repo = url
         repotype = 'git'
-        sourcecode = url
-        issuetracker = url + '/issues'
-        website = ""
+        app.SourceCode = url
+        app.IssueTracker = url + '/issues'
+        app.WebSite = ""
     elif url.startswith('https://gitlab.com/'):
         projecttype = 'gitlab'
-        repo = url
-        repotype = 'git'
-        sourcecode = url + '/tree/HEAD'
-        issuetracker = url + '/issues'
-    elif url.startswith('https://gitorious.org/'):
-        projecttype = 'gitorious'
-        repo = 'https://git.gitorious.org/' + url[22:] + '.git'
+        # git can be fussy with gitlab URLs unless they end in .git
+        if url.endswith('.git'):
+            repo = url
+        else:
+            repo = url + '.git'
         repotype = 'git'
-        sourcecode = url
+        app.SourceCode = url + '/tree/HEAD'
+        app.IssueTracker = url + '/issues'
     elif url.startswith('https://bitbucket.org/'):
         if url.endswith('/'):
             url = url[:-1]
         projecttype = 'bitbucket'
-        sourcecode = url + '/src'
-        issuetracker = url + '/issues'
+        app.SourceCode = url + '/src'
+        app.IssueTracker = url + '/issues'
         # Figure out the repo type and adddress...
-        repotype, repo = getrepofrompage(sourcecode)
+        repotype, repo = getrepofrompage(app.SourceCode)
         if not repotype:
             logging.error("Unable to determine vcs type. " + repo)
             sys.exit(1)
@@ -161,21 +132,69 @@ def main():
 
     # Get a copy of the source so we can extract some info...
     logging.info('Getting source from ' + repotype + ' repo at ' + repo)
-    src_dir = os.path.join(tmp_dir, 'importer')
-    if os.path.exists(src_dir):
-        shutil.rmtree(src_dir)
-    vcs = common.getvcs(repotype, repo, src_dir)
+    build_dir = os.path.join(tmp_dir, 'importer')
+    if os.path.exists(build_dir):
+        shutil.rmtree(build_dir)
+    vcs = common.getvcs(repotype, repo, build_dir)
     vcs.gotorevision(options.rev)
+    root_dir = get_subdir(build_dir)
+
+    app.RepoType = repotype
+    app.Repo = repo
+
+    return root_dir, build_dir
+
+
+config = None
+options = None
+
+
+def get_subdir(build_dir):
     if options.subdir:
-        root_dir = os.path.join(src_dir, options.subdir)
+        return os.path.join(build_dir, options.subdir)
+
+    return build_dir
+
+
+def main():
+
+    global config, options
+
+    # Parse command line...
+    parser = ArgumentParser()
+    common.setup_global_opts(parser)
+    parser.add_argument("-u", "--url", default=None,
+                        help="Project URL to import from.")
+    parser.add_argument("-s", "--subdir", default=None,
+                        help="Path to main android project subdirectory, if not in root.")
+    parser.add_argument("--rev", default=None,
+                        help="Allows a different revision (or git branch) to be specified for the initial import")
+    options = parser.parse_args()
+
+    config = common.read_config(options)
+
+    apps = metadata.read_metadata()
+    app = metadata.App()
+    app.UpdateCheckMode = "Tags"
+
+    root_dir = None
+    build_dir = None
+
+    if options.url:
+        root_dir, build_dir = get_metadata_from_url(app, options.url)
+    elif os.path.isdir('.git'):
+        if options.url:
+            app.WebSite = options.url
+        root_dir = get_subdir(os.getcwd())
     else:
-        root_dir = src_dir
+        logging.error("Specify project url.")
+        sys.exit(1)
 
     # Extract some information...
     paths = common.manifest_paths(root_dir, [])
     if paths:
 
-        version, vercode, package = common.parse_androidmanifests(paths)
+        version, vercode, package = common.parse_androidmanifests(paths, app)
         if not package:
             logging.error("Couldn't find package ID")
             sys.exit(1)
@@ -202,46 +221,31 @@ def main():
         logging.error("Package " + package + " already exists")
         sys.exit(1)
 
-    # Construct the metadata...
-    app = metadata.parse_metadata(None)[1]
-    app['Web Site'] = website
-    app['Source Code'] = sourcecode
-    if issuetracker:
-        app['Issue Tracker'] = issuetracker
-    if license:
-        app['License'] = license
-    app['Repo Type'] = repotype
-    app['Repo'] = repo
-    app['Update Check Mode'] = "Tags"
-
     # Create a build line...
-    build = {}
-    build['version'] = version or '?'
-    build['vercode'] = vercode or '?'
-    build['commit'] = '?'
-    build['disable'] = 'Generated by import.py - check/set version fields and commit id'
+    build = metadata.Build()
+    build.version = version or '?'
+    build.vercode = vercode or '?'
+    build.commit = '?'
+    build.disable = 'Generated by import.py - check/set version fields and commit id'
     if options.subdir:
-        build['subdir'] = options.subdir
+        build.subdir = options.subdir
     if os.path.exists(os.path.join(root_dir, 'jni')):
-        build['buildjni'] = ['yes']
-
-    for flag, value in metadata.flag_defaults.iteritems():
-        if flag in build:
-            continue
-        build[flag] = value
+        build.buildjni = ['yes']
 
-    app['builds'].append(build)
+    app.builds.append(build)
 
     # Keep the repo directory to save bandwidth...
     if not os.path.exists('build'):
         os.mkdir('build')
-    shutil.move(src_dir, os.path.join('build', package))
+    if build_dir is not None:
+        shutil.move(build_dir, os.path.join('build', package))
     with open('build/.fdroidvcs-' + package, 'w') as f:
-        f.write(repotype + ' ' + repo)
+        f.write(app.RepoType + ' ' + app.Repo)
 
-    metafile = os.path.join('metadata', package + '.txt')
-    metadata.write_metadata(metafile, app)
-    logging.info("Wrote " + metafile)
+    metadatapath = os.path.join('metadata', package + '.txt')
+    with open(metadatapath, 'w') as f:
+        metadata.write_metadata('txt', f, app)
+    logging.info("Wrote " + metadatapath)
 
 
 if __name__ == "__main__":