From 5e99fc4a8a8c3d8c066d5b3522678de8d675cb5d Mon Sep 17 00:00:00 2001
From: Karsten Hopp <karsten@redhat.com>
Date: Jun 23 2016 12:55:19 +0000
Subject: allow overwriting disttag for certain users (new permission 'module')


---

diff --git a/builder/kojid b/builder/kojid
index e2dc040..cb201bf 100755
--- a/builder/kojid
+++ b/builder/kojid
@@ -175,7 +175,7 @@ class BuildRoot(object):
         self.config = self.session.getBuildConfig(self.tag_id, event=self.event_id)
 
     def _new(self, tag, arch, task_id, repo_id=None, install_group='build',
-             setup_dns=False, bind_opts=None, maven_opts=None, maven_envs=None, deps=None):
+             setup_dns=False, bind_opts=None, maven_opts=None, maven_envs=None, deps=None, disttag=None):
         """Create a brand new repo"""
         if not repo_id:
             raise koji.BuildrootError, "A repo id must be provided"
@@ -216,6 +216,7 @@ class BuildRoot(object):
         self.bind_opts = bind_opts
         self.maven_opts = maven_opts
         self.maven_envs = maven_envs
+        self.disttag = disttag
         self.deps = deps
         self._writeMockConfig()
 
@@ -237,8 +238,10 @@ class BuildRoot(object):
         opts['install_group'] = self.install_group
         opts['maven_opts'] = self.maven_opts
         opts['maven_envs'] = self.maven_envs
+        opts['disttag'] = self.disttag
         opts['bind_opts'] = self.bind_opts
         opts['target_arch'] = self.target_arch
+        opts['disttag'] = self.disttag
         if 'mock.package_manager' in self.config['extra']:
             opts['package_manager'] = self.config['extra']['mock.package_manager']
         output = koji.genMockConfig(self.name, self.br_arch, managed=True, **opts)
@@ -855,7 +858,7 @@ class BuildTask(BaseTaskHandler):
         #(initBuild raises an exception if there is a conflict)
         try:
             self.extra_information = { "src": src, "data": data, "target": target }
-            srpm,rpms,brmap,logs = self.runBuilds(srpm,build_tag,archlist,repo_info['id'])
+            srpm,rpms,brmap,logs = self.runBuilds(srpm,build_tag,archlist,repo_info['id'], opts.get('disttag'))
 
             if opts.get('scratch'):
                 #scratch builds do not get imported
@@ -955,7 +958,7 @@ class BuildTask(BaseTaskHandler):
             raise koji.BuildError, "No matching arches were found"
         return archdict.keys()
 
-    def runBuilds(self, srpm, build_tag, archlist, repo_id):
+    def runBuilds(self, srpm, build_tag, archlist, repo_id, disttag=None):
         self.logger.debug("Spawning jobs for arches: %r" % (archlist))
         subtasks = {}
         keep_srpm = True
@@ -965,7 +968,7 @@ class BuildTask(BaseTaskHandler):
             else:
                 taskarch = koji.canonArch(arch)
             subtasks[arch] = self.session.host.subtask(method='buildArch',
-                                                       arglist=[srpm, build_tag, arch, keep_srpm, {'repo_id': repo_id}],
+                                                       arglist=[srpm, build_tag, arch, keep_srpm, {'repo_id': repo_id, 'disttag': disttag}],
                                                        label=arch,
                                                        parent=self.id,
                                                        arch=taskarch)
@@ -1090,6 +1093,7 @@ class BuildArchTask(BaseBuildTask):
         repo_id = opts.get('repo_id')
         if not repo_id:
             raise koji.BuildError, "A repo id must be provided"
+        disttag = opts.get('disttag')
         repo_info = self.session.repoInfo(repo_id, strict=True)
         event_id = repo_info['create_event']
 
@@ -1114,7 +1118,8 @@ class BuildArchTask(BaseBuildTask):
         self.updateWeight(name)
 
         rootopts = {
-            'repo_id': repo_id
+            'repo_id': repo_id,
+            'disttag': disttag
             }
         br_arch = self.find_arch(arch, self.session.host.getHost(), self.session.getBuildConfig(root, event=event_id))
         broot = BuildRoot(self.session, self.options, root, br_arch, self.id, **rootopts)
@@ -1327,7 +1332,7 @@ class BuildMavenTask(BaseBuildTask):
         buildroot = BuildRoot(self.session, self.options, build_tag['id'], br_arch, self.id,
                               install_group='maven-build', setup_dns=True, repo_id=repo_id,
                               maven_opts=maven_opts, maven_envs=opts.get('envs'),
-                              deps=opts.get('deps'))
+                              deps=opts.get('deps'),disttag=opts.get('disttag'))
         buildroot.workdir = self.workdir
         self.logger.debug("Initializing buildroot")
         buildroot.init()
@@ -1636,13 +1641,13 @@ class WrapperRPMTask(BaseBuildTask):
         repo_id = opts.get('repo_id')
         if not repo_id:
             raise koji.BuildError, "A repo id must be provided"
-
+        disttag = opts.get('disttag')
         repo_info = self.session.repoInfo(repo_id, strict=True)
         event_id = repo_info['create_event']
         build_tag = self.session.getTag(build_target['build_tag'], strict=True)
         br_arch = self.find_arch('noarch', self.session.host.getHost(), self.session.getBuildConfig(build_tag['id'], event=event_id))
 
-        buildroot = BuildRoot(self.session, self.options, build_tag['id'], br_arch, self.id, install_group='wrapper-rpm-build', repo_id=repo_id)
+        buildroot = BuildRoot(self.session, self.options, build_tag['id'], br_arch, self.id, install_group='wrapper-rpm-build', repo_id=repo_id, disttag=disttag)
         buildroot.workdir = self.workdir
         self.logger.debug("Initializing buildroot")
         buildroot.init()
@@ -3908,7 +3913,7 @@ class BuildSRPMFromSCMTask(BaseBuildTask):
         repo_id = opts.get('repo_id')
         if not repo_id:
             raise koji.BuildError, "A repo id must be provided"
-
+        disttag = opts.get('disttag')
         repo_info = self.session.repoInfo(repo_id, strict=True)
         event_id = repo_info['create_event']
         build_tag = self.session.getTag(build_tag, strict=True, event=event_id)
@@ -3917,7 +3922,8 @@ class BuildSRPMFromSCMTask(BaseBuildTask):
         # a SCM or lookaside cache to retrieve the srpm contents
         rootopts = {'install_group': 'srpm-build',
                     'setup_dns': True,
-                    'repo_id': repo_id}
+                    'repo_id': repo_id,
+                    'disttag': disttag}
         br_arch = self.find_arch('noarch', self.session.host.getHost(), self.session.getBuildConfig(build_tag['id'], event=event_id))
         broot = BuildRoot(self.session, self.options, build_tag['id'], br_arch, self.id, **rootopts)
         broot.workdir = self.workdir
diff --git a/cli/koji b/cli/koji
index 958c6ad..19872e7 100755
--- a/cli/koji
+++ b/cli/koji
@@ -886,6 +886,9 @@ def handle_build(options, session, args):
                       help=_("Do not display progress of the upload"))
     parser.add_option("--background", action="store_true",
                       help=_("Run the build at a lower priority"))
+    parser.add_option("--disttag", action="store", type="string",
+                      help=_("[module permissions required], overwrite disttag"))
+
     (build_opts, args) = parser.parse_args(args)
     if len(args) != 2:
         parser.error(_("Exactly two arguments (a build target and a SCM URL or srpm file) are required"))
@@ -910,7 +913,12 @@ def handle_build(options, session, args):
     opts = {}
     if build_opts.arch_override:
         opts['arch_override'] = ' '.join(build_opts.arch_override.replace(',',' ').split())
-    for key in ('skip_tag', 'scratch', 'repo_id'):
+    # XXX
+    # Q: will all module builds need a disttag different than default ?
+    if build_opts.disttag:
+        if not "module" in session.getPerms():
+                parser.error(_("Error: Insufficient permissions to use --disttag. Ask your admin to add you to the 'module' group."))
+    for key in ('skip_tag', 'scratch', 'repo_id', 'disttag'):
         val = getattr(build_opts, key)
         if val is not None:
             opts[key] = val
diff --git a/koji/__init__.py b/koji/__init__.py
index 14ceba1..ba1f8f8 100644
--- a/koji/__init__.py
+++ b/koji/__init__.py
@@ -1392,6 +1392,8 @@ name=build
                 parts.append("config_opts['plugin_conf']['bind_mount_opts'][%r].append((%r, %r))\n" % (key, mnt_src, mnt_dest))
         parts.append("\n")
 
+    if opts.get('disttag'):
+        macros['%dist'] = opts['disttag']
     for key, value in macros.iteritems():
         parts.append("config_opts['macros'][%r] = %r\n" % (key, value))
     parts.append("\n")

