Commits

Anonymous committed 70fb690

[bin]: #1225 Tag changer.

Comments (0)

Files changed (2)

bin/tag_changer.py

+from ckanext.importlib.api_command import ApiCommand
+from ckanclient import CkanApiNotFoundError
+
+class TagChanger(object):
+    def __init__(self, ckanclient, from_tag_name, to_tag_name):
+        self.ckanclient = ckanclient
+        self.from_tag_name = from_tag_name
+        self.to_tag_name = to_tag_name
+
+        self.warn_user()
+        self.change_tags()
+
+    def warn_user(self):
+        ''' Tell user what about what is likely to happen and check he is
+            happy to proceed.
+        '''
+        self.tag_pkgs = []
+        for tag_name in (self.from_tag_name, self.to_tag_name):
+            try:
+                tag_pkgs = self.ckanclient.tag_entity_get(tag_name)
+            except CkanApiNotFoundError, e:
+                tag_pkgs = []
+            self.tag_pkgs.append(tag_pkgs)
+            print 'Tag %s: %i packages' % (tag_name, len(tag_pkgs))
+            if tag_pkgs:
+                print '      e.g.: %s' % ' '.join(tag_pkgs[:5])
+
+        if self.tag_pkgs[0]:
+            is_sure = raw_input('Are you sure you want to change the tags for %i packages? ' % len(self.tag_pkgs[0]))
+            if is_sure.strip().lower() in ('y', 'yes'):
+                return
+            else:
+                print 'Exiting'
+                sys.exit(0)
+        else:
+            print 'Nothing to do'
+            sys.exit(0)
+
+    def change_tags(self):
+        pkg_names = self.tag_pkgs[0]
+        for pkg_name in pkg_names:
+            pkg = self.ckanclient.package_entity_get(pkg_name)
+            original_tags = pkg['tags'][:]
+            pkg['tags'].remove(self.from_tag_name)
+            pkg['tags'].append(self.to_tag_name)
+            self.ckanclient.package_entity_put(pkg)
+            print '%s: %r -> %r' % (pkg_name, original_tags, pkg['tags'])
+        print 'Changed tag for %s packages' % len(pkg_names)
+                
+class Cmd(ApiCommand):
+    usage = 'usage: %prog [options] <existing-tag-name> <new-tag-name>'
+    def __init__(self, usage=None):
+        super(Cmd, self).__init__(usage)
+
+    def command(self):
+        super(Cmd, self).command()
+
+        if len(self.args) < 2:
+            self.parser.error('Please specify tags to change')
+        if len(self.args) > 2:
+            self.parser.error('Too many parameters')
+        from_tag_name, to_tag_name = self.args
+
+        changer = TagChanger(self.client, from_tag_name, to_tag_name)
+
+def load():
+    Cmd().command()
+
     amqp_listener = ckanext.amqp:listener
     link_checker = ckanext.link_checker:checker
     scotland_loader = bin.loadscotland:load
+    tag_changer = bin.tag_changer:load
     """,
     test_suite = 'nose.collector',
 )