From 86a86adc4609b877dce9597b8f91961fc43f7d5d Mon Sep 17 00:00:00 2001
From: Markus Scheidgen <markus.scheidgen@gmail.com>
Date: Tue, 16 Jul 2019 16:31:16 +0200
Subject: [PATCH] Added chown cmd to admin cli. [skip ci]

---
 nomad/admin/upload.py | 34 +++++++++++++++++++++++++++++++++-
 1 file changed, 33 insertions(+), 1 deletion(-)

diff --git a/nomad/admin/upload.py b/nomad/admin/upload.py
index 82436d8c41..ec5bf4285f 100644
--- a/nomad/admin/upload.py
+++ b/nomad/admin/upload.py
@@ -15,8 +15,9 @@
 import click
 from tabulate import tabulate
 from mongoengine import Q
+from pymongo import UpdateOne
 
-from nomad import processing as proc, infrastructure, utils, search, files
+from nomad import processing as proc, infrastructure, utils, search, files, coe_repo
 from .__main__ import cli
 
 
@@ -63,6 +64,37 @@ def ls(ctx, uploads):
         headers=['id', 'name', 'user', 'status', 'published']))
 
 
+@upload.command(help='Change the owner of the upload and all its calcs.')
+@click.argument('USER', nargs=1)
+@click.argument('UPLOADS', nargs=-1)
+@click.pass_context
+def chown(ctx, user, uploads):
+    infrastructure.setup_repository_db()
+    _, uploads = query_uploads(ctx, uploads)
+
+    print('%d uploads selected, changing its owner ...' % uploads.count())
+
+    user_id = str(user)
+    user = coe_repo.User.from_user_id(user_id)
+
+    for upload in uploads:
+        upload.user_id = user_id
+        upload_with_metadata = upload.to_upload_with_metadata()
+        calcs = upload_with_metadata.calcs
+
+        def create_update(calc):
+            return UpdateOne(
+                {'_id': calc.calc_id},
+                {'$set': {'metadata.uploader': user.to_popo()}})
+
+        proc.Calc._get_collection().bulk_write([create_update(calc) for calc in calcs])
+        upload.save()
+
+        upload_with_metadata = upload.to_upload_with_metadata()
+        calcs = upload_with_metadata.calcs
+        search.publish(calcs)
+
+
 @upload.command(help='Delete selected upload')
 @click.argument('UPLOADS', nargs=-1)
 @click.option('--with-coe-repo', help='Also attempt to delete from repository db', is_flag=True)
-- 
GitLab