Lookup users by name instead of by email.

Searching by email address is currently broken on our installation, probably
as a consequence to protect users' privacy.  This version attempts to look up
accounts by name.  If multiple or no matches are found, then an error message
will be shown and the account skipped.
master
James Eagan 2023-10-05 17:08:24 +02:00
parent bf15188573
commit 4e2d9747b2
1 changed files with 18 additions and 9 deletions

View File

@ -28,12 +28,15 @@ def readNames(fileName):
if hasHeader: if hasHeader:
next(reader) next(reader)
for row in reader: for row in reader:
result.append((row[0], row[1], row[2])) result.append((row[0], row[1], row[2], row[3]))
return result return result
def lookupUser(email, gitlab): def lookupUser(email, gitlab):
""" Return the first found user; throw if not found """ """ Return the first found user; throw if not found """
return gitlab.users.list(search=email)[0] matches = gitlab.users.list(search=email)
if len(matches) == 1:
return matches[0]
raise IndexError("Found {} matching users".format(len(matches)))
def createProject(name, groupId, gitlab): def createProject(name, groupId, gitlab):
return gitlab.projects.create({'name': name, return gitlab.projects.create({'name': name,
@ -44,22 +47,27 @@ def addProjectMember(project, userId, accessLevel):
'access_level': accessLevel}) 'access_level': accessLevel})
def makeProjectsInGroupId(groupId, csvFile, token, options={}): def makeProjectsInGroupId(groupId, csvFile, token, options={}):
print(groupId, csvFile, options); return # print(groupId, csvFile, options)
api = gitlab.Gitlab(GITLAB_URL, token) api = gitlab.Gitlab(GITLAB_URL, token)
for (lastName, firstName, email) in readNames(csvFile): for (lastName, firstName, email, login) in readNames(csvFile):
try: try:
user = lookupUser(email, api) user = lookupUser(f"{lastName} {firstName}", api)
print("::: Creating project for {} {} <{}> -- {} ({})…".format(
print("::: {}Creating project for {} {} <{}> -- {} ({})…".format(
"Not " if options.dry_run else "",
lastName, firstName, email, user.name, user.id)) lastName, firstName, email, user.name, user.id))
if options.dry_run:
continue
project = createProject('{} {}'.format(lastName, firstName), project = createProject('{} {}'.format(lastName, firstName),
groupId, api) groupId, api)
member = addProjectMember(project, user.id, member = addProjectMember(project, user.id,
gitlab.MAINTAINER_ACCESS) gitlab.MAINTAINER_ACCESS)
except IndexError as e: except IndexError as e:
print >> sys.stderr, "!!! Could not create project for {}: User not found ({})".format(email, e) print("!!! Skipping {}: User not found ({})".format(email, e), file=sys.stderr)
except Exception as e: except Exception as e:
# print("!!! Could not create user for {}: {}".format(email, e), file=sys.stderr) # print("!!! Could not create user for {}: {}".format(email, e), file=sys.stderr)
print >> sys.stderr, "!!! Error creating project for {}: {}".format(email, e) print("!!! Error creating project for {}: {}".format(email, e), file=sys.stderr)
if __name__ == '__main__': if __name__ == '__main__':
import argparse import argparse
@ -77,9 +85,10 @@ if __name__ == '__main__':
def parse_args(): def parse_args():
parser = argparse.ArgumentParser(description="Create GitLab repositories") parser = argparse.ArgumentParser(description="Create GitLab repositories")
parser.add_argument("csv", help="CSV file as exported from Synapses. The first three columns are assumed to be last name, first name, email address.") parser.add_argument("csv", help="CSV file as exported from Synapses. The first four columns are assumed to be last name, first name, email address, login.")
parser.add_argument("groupId", help="The GitLab id where all projects will be added.") parser.add_argument("groupId", help="The GitLab id where all projects will be added.")
parser.add_argument("-t", "--token", help="GitLab API token as created at {}/-/profile/personal_access_tokens".format(GITLAB_URL)) parser.add_argument("-t", "--token", help="GitLab API token as created at {}/-/profile/personal_access_tokens".format(GITLAB_URL))
parser.add_argument("-n", "--dry-run", help="Do not actually create repositories.", action="store_true")
# TODO: parser.add_argument("--extract-groups", help="Extract groups from the fourth column in the CSV file", action="store_true") # TODO: parser.add_argument("--extract-groups", help="Extract groups from the fourth column in the CSV file", action="store_true")
args = parser.parse_args() args = parser.parse_args()