From 1c8fcdbe6e534b5886f41a492e9b7789b5047b7c Mon Sep 17 00:00:00 2001 From: ejochman <34144949+ejochman@users.noreply.github.com> Date: Mon, 15 Jan 2018 12:04:59 -0800 Subject: [PATCH] Consolidate simple system error exits (#672) * Consolidate simple system error exits Use systemErrorExit() to print a consistent string to stderr and exit with the desired return code. * Consolidate simple system error exits Use systemErrorExit() to print a consistent string to stderr and exit with the desired return code. * Fix additional paren --- src/gam.py | 906 ++++++++++++++++++----------------------------------- 1 file changed, 303 insertions(+), 603 deletions(-) diff --git a/src/gam.py b/src/gam.py index 14addc63..9340a910 100755 --- a/src/gam.py +++ b/src/gam.py @@ -173,12 +173,10 @@ def getString(i, item, emptyOK=False, optional=False): return argstr if emptyOK or optional: return u'' - print u'ERROR: expected a Non-empty <{0}>'.format(item) - sys.exit(2) + systemErrorExit(2, u'expected a Non-empty <{0}>'.format(item)) elif optional: return u'' - print u'ERROR: expected a <{0}>'.format(item) - sys.exit(2) + systemErrorExit(2, u'expected a <{0}>'.format(item)) YYYYMMDD_FORMAT = u'%Y-%m-%d' YYYYMMDD_FORMAT_REQUIRED = u'yyyy-mm-dd' @@ -193,12 +191,10 @@ def getYYYYMMDD(i, emptyOK=False, returnTimeStamp=False): return argstr return timeStamp except ValueError: - print u'ERROR: expected a <{0}>; got {1}'.format(YYYYMMDD_FORMAT_REQUIRED, argstr) - sys.exit(2) + systemErrorExit(2, u'expected a <{0}>; got {1}'.format(YYYYMMDD_FORMAT_REQUIRED, argstr)) elif emptyOK: return u'' - print u'ERROR: expected a <{0}>'.format(YYYYMMDD_FORMAT_REQUIRED) - sys.exit(2) + systemErrorExit(2, u'expected a <{0}>'.format(YYYYMMDD_FORMAT_REQUIRED)) def getTimeOrDeltaFromNow(time_string): """Get an ISO 8601 date/time or a positive/negative delta applied to now. @@ -219,8 +215,7 @@ def getTimeOrDeltaFromNow(time_string): return time_string mg = re.match(DELTA_PATTERN, time_string.lower()) if mg is None: - print u'ERROR: %s is not a valid delta, expected (+|-)(m|h|d|w)' % time_string - sys.exit(2) + systemErrorExit(2, u'%s is not a valid delta, expected (+|-)(m|h|d|w)' % time_string) sign = mg.group(1) delta = int(mg.group(2)) @@ -324,8 +319,7 @@ def readFile(filename, mode=u'rb', continueOnError=False, displayError=True, enc return None systemErrorExit(6, e) except (LookupError, UnicodeDecodeError, UnicodeError) as e: - print u'ERROR: %s' % e - sys.exit(2) + systemErrorExit(2, u'%s' % e) # # Write a file # @@ -370,8 +364,7 @@ class UnicodeDictReader(object): except (csv.Error, StopIteration): self.fieldnames = [] except LookupError as e: - print u'ERROR: %s' % e - sys.exit(2) + systemErrorExit(2, u'%s' % e) self.numfields = len(self.fieldnames) def __iter__(self): @@ -550,8 +543,7 @@ def doGAMVersion(checkForArgs=True): simple = True i += 1 else: - print u'ERROR: %s is not a valid argument for "gam version"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, u'%s is not a valid argument for "gam version"' % sys.argv[i]) if simple: sys.stdout.write(gam_version) return @@ -1090,8 +1082,7 @@ def doCheckServiceAccount(users): print u'\nAll scopes passed!\nService account %s is fully authorized.' % service_account else: user_domain = user[user.find(u'@')+1:] - print u''' -ERROR: Some scopes failed! Please go to: + scopes_failed = '''Some scopes failed! Please go to: https://admin.google.com/%s/AdminHome?#OGX:ManageOauthClients @@ -1102,7 +1093,7 @@ and grant Client name: Access to scopes: %s\n''' % (user_domain, service_account, ',\n'.join(all_scopes)) - sys.exit(int(not all_scopes_pass)) + systemErrorExit(int(not all_scopes_pass), scopes_failed) # Batch processing request_id fields RI_ENTITY = 0 @@ -1162,8 +1153,7 @@ def showReport(): to_drive = True i += 1 else: - print u'ERROR: %s is not a valid argument to "gam report"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, u'%s is not a valid argument to "gam report"' % sys.argv[i]) if try_date is None: try_date = unicode(datetime.date.today()) if report in [u'users', u'user']: @@ -1360,8 +1350,7 @@ def watchGmail(users): def addDelegates(users, i): if i == 4: if sys.argv[i].lower() != u'to': - print u'ERROR: %s is not a valid argument for "gam delegate", expected to' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, u'%s is not a valid argument for "gam delegate", expected to' % sys.argv[i]) i += 1 delegate = sys.argv[i].lower() if not delegate.find(u'@') > 0: @@ -1399,8 +1388,7 @@ def addDelegates(users, i): elif httpStatus > 499: waitOnFailure(n, retries, str(httpStatus)) else: - print u'ERROR: Could not create delegation - %s - %s' % (httpStatus, result) - sys.exit(3) + systemErrorExit(3, u'Could not create delegation - %s - %s' % (httpStatus, result)) def gen_sha512_hash(password): from passlib.handlers.sha2_crypt import sha512_crypt @@ -1424,8 +1412,7 @@ def printShowDelegates(users, csvFormat): todrive = True i += 1 else: - print u'ERROR: %s is not a valid argument for "gam show delegates"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, u'%s is not a valid argument for "gam show delegates"' % sys.argv[i]) for user in users: if user.find(u'@') == -1: userName = user @@ -1498,8 +1485,7 @@ def doAddCourseParticipant(): service = croom.courses().aliases() body = {u'alias': addCourseIdScope(new_id)} else: - print u'ERROR: %s is not a valid argument to "gam course ID add"' % participant_type - sys.exit(2) + systemErrorExit(2, u'%s is not a valid argument to "gam course ID add"' % participant_type) callGAPI(service, u'create', courseId=courseId, body=body) print u'Added %s as a %s of course %s' % (removeCourseIdScope(new_id), participant_type, removeCourseIdScope(courseId)) @@ -1540,8 +1526,7 @@ def doDelCourseParticipant(): service = croom.courses().aliases() kwargs = {u'alias': addCourseIdScope(remove_id)} else: - print u'ERROR: %s is not a valid argument to "gam course ID delete"' % participant_type - sys.exit(2) + systemErrorExit(2, u'%s is not a valid argument to "gam course ID delete"' % participant_type) callGAPI(service, u'delete', courseId=courseId, **kwargs) print u'Removed %s as a %s of course %s' % (removeCourseIdScope(remove_id), participant_type, removeCourseIdScope(courseId)) @@ -1557,8 +1542,7 @@ def _getValidCourseStates(croom): def _getValidatedState(state, validStates): state = state.upper() if state not in validStates: - print u'ERROR: course state must be one of: %s. Got %s' % (u', '.join(validStates).lower(), state.lower()) - sys.exit(2) + systemErrorExit(2, u'course state must be one of: %s. Got %s' % (u', '.join(validStates).lower(), state.lower())) return state def getCourseAttribute(myarg, value, body, croom, function): @@ -1578,8 +1562,7 @@ def getCourseAttribute(myarg, value, body, croom, function): validStates = _getValidCourseStates(croom) body[u'courseState'] = _getValidatedState(value, validStates) else: - print u'ERROR: %s is not a valid argument to "gam %s course"' % (myarg, function) - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument to "gam %s course"' % (myarg, function)) def _getCourseStates(croom, value, courseStates): validStates = _getValidCourseStates(croom) @@ -1625,8 +1608,7 @@ def doUpdateDomain(): body[u'customerDomain'] = domain_name i += 1 else: - print u'ERROR: %s is not a valid argument for "gam update domain"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam update domain"' % sys.argv[i]) callGAPI(cd.customers(), u'update', customerKey=GC_Values[GC_CUSTOMER_ID], body=body) print u'%s is now the primary domain.' % domain_name @@ -1723,11 +1705,9 @@ def doUpdateCustomer(): body[u'language'] = sys.argv[i+1] i += 2 else: - print u'ERROR: %s is not a valid argument for "gam update customer"' % myarg - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam update customer"' % myarg) if not body: - print u'ERROR: no arguments specified for "gam update customer"' - sys.exit(2) + systemErrorExit(2, 'no arguments specified for "gam update customer"') callGAPI(cd.customers(), u'update', customerKey=GC_Values[GC_CUSTOMER_ID], body=body) print u'Updated customer' @@ -1753,8 +1733,7 @@ def doPrintDomains(): todrive = True i += 1 else: - print u'ERROR: %s is not a valid argument for "gam print domains".' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam print domains".' % sys.argv[i]) results = callGAPI(cd.domains(), u'list', customer=GC_Values[GC_CUSTOMER_ID]) for domain in results[u'domains']: domain_attributes = {} @@ -1797,8 +1776,7 @@ def doPrintDomainAliases(): todrive = True i += 1 else: - print u'ERROR: %s is not a valid argument for "gam print domainaliases".' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam print domainaliases".' % sys.argv[i]) results = callGAPI(cd.domainAliases(), u'list', customer=GC_Values[GC_CUSTOMER_ID]) for domainAlias in results[u'domainAliases']: domainAlias_attributes = {} @@ -1836,12 +1814,10 @@ def doCreateAdmin(): else: body[u'roleId'] = roleid_from_role(role) if not body[u'roleId']: - print u'ERROR: %s is not a valid role. Please ensure role name is exactly as shown in admin console.' % role - sys.exit(4) + systemErrorExit(4, '%s is not a valid role. Please ensure role name is exactly as shown in admin console.' % role) body[u'scopeType'] = sys.argv[5].upper() if body[u'scopeType'] not in [u'CUSTOMER', u'ORG_UNIT']: - print u'ERROR: scope type must be customer or org_unit; got %s' % body[u'scopeType'] - sys.exit(3) + systemErrorExit(3, 'scope type must be customer or org_unit; got %s' % body[u'scopeType']) if body[u'scopeType'] == u'ORG_UNIT': orgUnit = sys.argv[6] if orgUnit[:3] == u'id:': @@ -1875,8 +1851,7 @@ def doPrintAdminRoles(): todrive = True i += 1 else: - print u'ERROR: %s is not a valid argument for "gam print adminroles".' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam print adminroles".' % sys.argv[i]) roles = callGAPIpages(cd.roles(), u'list', u'items', customer=GC_Values[GC_CUSTOMER_ID], fields=fields) for role in roles: @@ -1907,15 +1882,13 @@ def doPrintAdmins(): else: roleId = roleid_from_role(role) if not roleId: - print u'ERROR: %s is not a valid role' % role - sys.exit(5) + systemErrorExit(5, '%s is not a valid role' % role) i += 2 elif myarg == u'todrive': todrive = True i += 1 else: - print u'ERROR: %s is not a valid argument for "gam print admins".' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam print admins".' % sys.argv[i]) admins = callGAPIpages(cd.roleAssignments(), u'list', u'items', customer=GC_Values[GC_CUSTOMER_ID], userKey=userKey, roleId=roleId, fields=fields) for admin in admins: @@ -2001,8 +1974,7 @@ def app2appID(dt, app): for online_service in online_services: if serviceName == online_service[u'name'].lower(): return (online_service[u'name'], online_service[u'id']) - print u'ERROR: %s is not a valid service for data transfer.' % app - sys.exit(2) + systemErrorExit(2, '%s is not a valid service for data transfer.' % app) def convertToUserID(user): if user[:4].lower() == u'uid:': @@ -2013,8 +1985,7 @@ def convertToUserID(user): try: return callGAPI(cd.users(), u'get', throw_reasons=[GAPI_USER_NOT_FOUND, GAPI_BAD_REQUEST, GAPI_FORBIDDEN], userKey=user, fields=u'id')[u'id'] except (GAPI_userNotFound, GAPI_badRequest, GAPI_forbidden): - print u'ERROR: no such user %s' % user - sys.exit(3) + systemErrorExit(3, 'no such user %s' % user) def convertUserIDtoEmail(uid): cd = buildGAPIObject(u'directory') @@ -2075,8 +2046,7 @@ def doPrintDataTransfers(): todrive = True i += 1 else: - print u'ERROR: %s is not a valid argument for "gam print transfers"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam print transfers"' % sys.argv[i]) transfers = callGAPIpages(dt.transfers(), u'list', u'dataTransfers', customerId=GC_Values[GC_CUSTOMER_ID], status=status, newOwnerUserId=newOwnerUserId, oldOwnerUserId=oldOwnerUserId) @@ -2156,8 +2126,7 @@ def doPrintShowGuardians(csvFormat): studentIds = getUsersToModify(entity_type=myarg, entity=sys.argv[i+1]) i += 2 else: - print u'ERROR: %s is not a valid argument for "gam %s guardians"' % (sys.argv[i], [u'show', u'print'][csvFormat]) - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam %s guardians"' % (sys.argv[i], [u'show', u'print'][csvFormat])) i = 0 count = len(studentIds) for studentId in studentIds: @@ -2213,8 +2182,7 @@ def doCancelGuardianInvitation(): invitationId = sys.argv[3] studentId = normalizeStudentGuardianEmailAddressOrUID(sys.argv[4]) if not _cancelGuardianInvitation(croom, studentId, invitationId): - stderrErrorMsg(u'Guardian invitation %s for %s does not exist' % (invitationId, studentId)) - sys.exit(3) + systemErrorExit(3, u'Guardian invitation %s for %s does not exist' % (invitationId, studentId)) def _deleteGuardian(croom, studentId, guardianId, guardianEmail): try: @@ -2242,8 +2210,7 @@ def doDeleteGuardian(): invitationsOnly = True i += 1 else: - print u'ERROR: %s is not a valid argument for "gam delete guardian"' % (sys.argv[i]) - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam delete guardian"' % (sys.argv[i])) if not invitationsOnly: if guardianIdIsEmail: try: @@ -2354,8 +2321,7 @@ def doPrintCourses(): if field != u'id': fList.append(COURSE_ARGUMENT_TO_PROPERTY_MAP[field]) else: - print u'ERROR: %s is not a valid argument for "gam print courses %s"' % (field, myarg) - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam print courses %s"' % (field, myarg)) def _saveParticipants(course, participants, role): jcount = len(participants) @@ -2426,8 +2392,7 @@ def doPrintCourses(): elif myarg == u'show': showMembers = sys.argv[i+1].lower() if showMembers not in [u'all', u'students', u'teachers']: - print u'ERROR: show must be all, students or teachers; got %s' % showMembers - sys.exit(2) + systemErrorExit(2, 'show must be all, students or teachers; got %s' % showMembers) i += 2 elif myarg == u'fields': if not fieldsList: @@ -2438,8 +2403,7 @@ def doPrintCourses(): _processFieldsList(myarg, i, skipFieldsList) i += 2 else: - print u'ERROR: %s is not a valid argument for "gam print courses"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam print courses"' % sys.argv[i]) fields = u'nextPageToken,courses({0})'.format(u','.join(set(fieldsList))) if fieldsList else None sys.stderr.write(u'Retrieving courses for organization (may take some time for large accounts)...\n') page_message = u'Got %%num_items%% courses...\n' @@ -2519,12 +2483,10 @@ def doPrintCourseParticipants(): elif myarg == u'show': showMembers = sys.argv[i+1].lower() if showMembers not in [u'all', u'students', u'teachers']: - print u'ERROR: show must be all, students or teachers; got %s' % showMembers - sys.exit(2) + systemErrorExit(2, 'show must be all, students or teachers; got %s' % showMembers) i += 2 else: - print u'ERROR: %s is not a valid argument for "gam print course-participants"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam print course-participants"' % sys.argv[i]) if len(courses) == 0: sys.stderr.write(u'Retrieving courses for organization (may take some time for large accounts)...\n') page_message = u'Got %%num_items%% courses...\n' @@ -2579,8 +2541,7 @@ def doPrintPrintJobs(): older_or_newer = u'newer' age_number = sys.argv[i+1][:-1] if not age_number.isdigit(): - print u'ERROR: expected a number; got %s' % age_number - sys.exit(2) + systemErrorExit(2, 'expected a number; got %s' % age_number) age_unit = sys.argv[i+1][-1].lower() if age_unit == u'm': age = int(time.time()) - (int(age_number) * 60) @@ -2589,8 +2550,7 @@ def doPrintPrintJobs(): elif age_unit == u'd': age = int(time.time()) - (int(age_number) * 60 * 60 * 24) else: - print u'ERROR: expected m (minutes), h (hours) or d (days); got %s' % age_unit - sys.exit(2) + systemErrorExit(2, 'expected m (minutes), h (hours) or d (days); got %s' % age_unit) i += 2 elif myarg == u'query': query = sys.argv[i+1] @@ -2607,8 +2567,7 @@ def doPrintPrintJobs(): elif myarg == u'orderby': sortorder = sys.argv[i+1].lower().replace(u'_', u'') if sortorder not in PRINTJOB_ASCENDINGORDER_MAP: - print u'ERROR: orderby must be one of %s; got %s' % (u', '.join(PRINTJOB_ASCENDINGORDER_MAP), sortorder) - sys.exit(2) + systemErrorExit(2, 'orderby must be one of %s; got %s' % (u', '.join(PRINTJOB_ASCENDINGORDER_MAP), sortorder)) sortorder = PRINTJOB_ASCENDINGORDER_MAP[sortorder] i += 2 elif myarg in [u'printer', u'printerid']: @@ -2621,8 +2580,7 @@ def doPrintPrintJobs(): jobLimit = max(0, int(sys.argv[i+1])) i += 2 else: - print u'ERROR: %s is not a valid argument for "gam print printjobs"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam print printjobs"' % sys.argv[i]) if sortorder and descending: sortorder = PRINTJOB_DESCENDINGORDER_MAP[sortorder] if printerid: @@ -2705,8 +2663,7 @@ def doPrintPrinters(): todrive = True i += 1 else: - print u'ERROR: %s is not a valid argument for "gam print printers"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam print printers"' % sys.argv[i]) printers = callGAPI(cp.printers(), u'list', q=query, type=printer_type, connection_status=connection_status, extra_fields=extra_fields) checkCloudPrintResult(printers) for printer in printers[u'printers']: @@ -2743,8 +2700,7 @@ def changeCalendarAttendees(users): allevents = True i += 1 else: - print u'ERROR: %s is not a valid argument for "gam update calattendees"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam update calattendees"' % sys.argv[i]) attendee_map = {} f = openFile(csv_file) csvFile = csv.reader(f) @@ -2822,8 +2778,7 @@ def getCalendarAttributes(i, body, function): elif sys.argv[i+1].lower() in false_values: body[u'selected'] = False else: - print u'ERROR: Value for selected must be true or false; got %s' % sys.argv[i+1] - sys.exit(2) + systemErrorExit(2, 'Value for selected must be true or false; got %s' % sys.argv[i+1]) i += 2 elif myarg == u'hidden': if sys.argv[i+1].lower() in true_values: @@ -2831,8 +2786,7 @@ def getCalendarAttributes(i, body, function): elif sys.argv[i+1].lower() in false_values: body[u'hidden'] = False else: - print u'ERROR: Value for hidden must be true or false; got %s' % sys.argv[i+1] - sys.exit(2) + systemErrorExit(2, 'Value for hidden must be true or false; got %s' % sys.argv[i+1]) i += 2 elif myarg == u'summary': body[u'summaryOverride'] = sys.argv[i+1] @@ -2853,13 +2807,11 @@ def getCalendarAttributes(i, body, function): method = sys.argv[i+1].lower() if method not in CLEAR_NONE_ARGUMENT: if method not in CALENDAR_REMINDER_METHODS: - print u'ERROR: Method must be one of %s; got %s' % (u', '.join(CALENDAR_REMINDER_METHODS+CLEAR_NONE_ARGUMENT), method) - sys.exit(2) + systemErrorExit(2, 'Method must be one of %s; got %s' % (u', '.join(CALENDAR_REMINDER_METHODS+CLEAR_NONE_ARGUMENT), method)) try: minutes = int(sys.argv[i+2]) except ValueError: - print u'ERROR: Reminder time must be specified in minutes; got %s' % sys.argv[i+2] - sys.exit(2) + systemErrorExit(2, 'Reminder time must be specified in minutes; got %s' % sys.argv[i+2]) body[u'defaultReminders'].append({u'method': method, u'minutes': minutes}) i += 3 else: @@ -2869,19 +2821,16 @@ def getCalendarAttributes(i, body, function): method = sys.argv[i+1].lower() if method not in CLEAR_NONE_ARGUMENT: if method not in CALENDAR_NOTIFICATION_METHODS: - print u'ERROR: Method must be one of %s; got %s' % (u', '.join(CALENDAR_NOTIFICATION_METHODS+CLEAR_NONE_ARGUMENT), method) - sys.exit(2) + systemErrorExit(2, 'Method must be one of %s; got %s' % (u', '.join(CALENDAR_NOTIFICATION_METHODS+CLEAR_NONE_ARGUMENT), method)) eventType = sys.argv[i+2].lower() if eventType not in CALENDAR_NOTIFICATION_TYPES_MAP: - print u'ERROR: Event must be one of %s; got %s' % (u', '.join(CALENDAR_NOTIFICATION_TYPES_MAP), eventType) - sys.exit(2) + systemErrorExit(2, 'Event must be one of %s; got %s' % (u', '.join(CALENDAR_NOTIFICATION_TYPES_MAP), eventType)) body[u'notificationSettings'][u'notifications'].append({u'method': method, u'type': CALENDAR_NOTIFICATION_TYPES_MAP[eventType]}) i += 3 else: i += 2 else: - print u'ERROR: %s is not a valid argument for "gam %s calendar"' % (sys.argv[i], function) - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam %s calendar"' % (sys.argv[i], function)) return colorRgbFormat def addCalendar(users): @@ -3026,8 +2975,7 @@ def doPrintJobFetch(): older_or_newer = u'newer' age_number = sys.argv[i+1][:-1] if not age_number.isdigit(): - print u'ERROR: expected a number; got %s' % age_number - sys.exit(2) + systemErrorExit(2, 'expected a number; got %s' % age_number) age_unit = sys.argv[i+1][-1].lower() if age_unit == u'm': age = int(time.time()) - (int(age_number) * 60) @@ -3036,8 +2984,7 @@ def doPrintJobFetch(): elif age_unit == u'd': age = int(time.time()) - (int(age_number) * 60 * 60 * 24) else: - print u'ERROR: expected m (minutes), h (hours) or d (days); got %s' % age_unit - sys.exit(2) + systemErrorExit(2, 'expected m (minutes), h (hours) or d (days); got %s' % age_unit) i += 2 elif myarg == u'query': query = sys.argv[i+1] @@ -3054,8 +3001,7 @@ def doPrintJobFetch(): elif myarg == u'orderby': sortorder = sys.argv[i+1].lower().replace(u'_', u'') if sortorder not in PRINTJOB_ASCENDINGORDER_MAP: - print u'ERROR: orderby must be one of %s; got %s' % (u', '.join(PRINTJOB_ASCENDINGORDER_MAP), sortorder) - sys.exit(2) + systemErrorExit(2, 'orderby must be one of %s; got %s' % (u', '.join(PRINTJOB_ASCENDINGORDER_MAP), sortorder)) sortorder = PRINTJOB_ASCENDINGORDER_MAP[sortorder] i += 2 elif myarg in [u'owner', u'user']: @@ -3073,8 +3019,7 @@ def doPrintJobFetch(): os.makedirs(targetFolder) i += 2 else: - print u'ERROR: %s is not a valid argument for "gam printjobs fetch"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam printjobs fetch"' % sys.argv[i]) if sortorder and descending: sortorder = PRINTJOB_DESCENDINGORDER_MAP[sortorder] if printerid: @@ -3151,8 +3096,7 @@ def doGetPrinterInfo(): everything = True i += 1 else: - print u'ERROR: %s is not a valid argument for "gam info printer"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam info printer"' % sys.argv[i]) result = callGAPI(cp.printers(), u'get', printerid=printerid) checkCloudPrintResult(result) printer_info = result[u'printers'][0] @@ -3187,8 +3131,7 @@ def doUpdatePrinter(): arg_in_item = True break if not arg_in_item: - print u'ERROR: %s is not a valid argument for "gam update printer"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam update printer"' % sys.argv[i]) result = callGAPI(cp.printers(), u'update', printerid=printerid, **kwargs) checkCloudPrintResult(result) print u'Updated printer %s' % printerid @@ -3260,8 +3203,7 @@ def doPrintJobSubmit(): form_fields[u'title'] = sys.argv[i+1] i += 2 else: - print u'ERROR: %s is not a valid argument for "gam printer ... print"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam printer ... print"' % sys.argv[i]) form_files = {} if content[:4] == u'http': form_fields[u'content'] = content @@ -3304,11 +3246,10 @@ def checkCloudPrintResult(result): try: result = json.loads(result) except ValueError: - print u'ERROR: unexpected response: %s' % result - sys.exit(3) + systemErrorExit(3, 'unexpected response: %s' % result) if not result[u'success']: - print u'ERROR %s: %s' % (result[u'errorCode'], result[u'message']) - sys.exit(result[u'errorCode']) + systemErrorExit( + result[u'errorCode'], '%s: %s' % (result[u'errorCode'], result[u'message'])) def formatACLRule(rule): if rule[u'scope'][u'type'] != u'default': @@ -3339,8 +3280,7 @@ def doCalendarAddACL(calendarId=None, act_as=None, role=None, scope=None, entity else: body[u'role'] = sys.argv[4].lower() if body[u'role'] not in [u'freebusy', u'read', u'reader', u'editor', u'writer', u'owner', u'none']: - print u'ERROR: Role must be one of freebusy, reader, editor, writer, owner, none; got %s' % body[u'role'] - sys.exit(2) + systemErrorExit(2, 'Role must be one of freebusy, reader, editor, writer, owner, none; got %s' % body[u'role']) if body[u'role'] == u'freebusy': body[u'role'] = u'freeBusyReader' elif body[u'role'] in [u'read', u'reader']: @@ -3425,8 +3365,7 @@ def doCalendarDeleteEvent(): doit = True i += 1 else: - print u'ERROR: %s is not a valid argument for "gam calendar deleteevent"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam calendar deleteevent"' % sys.argv[i]) if doit: for eventId in events: print u' deleting eventId %s' % eventId @@ -3501,8 +3440,7 @@ def doCalendarAddEvent(): if sys.argv[i+1].lower() in [u'default', u'public', u'private']: body[u'visibility'] = sys.argv[i+1].lower() else: - print u'ERROR: visibility must be one of default, public, private; got %s' % sys.argv[i+1] - sys.exit(2) + systemErrorExit(2, 'visibility must be one of default, public, private; got %s' % sys.argv[i+1]) i += 2 elif myarg == u'tentative': body[u'status'] = u'tentative' @@ -3543,8 +3481,7 @@ def doCalendarAddEvent(): body[u'colorId'] = str(sys.argv[i+1]) i += 2 else: - print u'ERROR: %s is not a valid argument for "gam calendar addevent"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam calendar addevent"' % sys.argv[i]) if not timeZone and u'recurrence' in body: timeZone = callGAPI(cal.calendars(), u'get', calendarId=calendarId, fields=u'timeZone')[u'timeZone'] if u'recurrence' in body: @@ -3563,8 +3500,7 @@ def doProfile(users): elif myarg in [u'unshare', u'unshared']: body = {u'includeInGlobalAddressList': False} else: - print u'ERROR: value for "gam profile" must be true or false; got %s' % sys.argv[4] - sys.exit(2) + systemErrorExit(2, 'value for "gam profile" must be true or false; got %s' % sys.argv[4]) i = 0 count = len(users) for user in users: @@ -3641,8 +3577,7 @@ def getPhoto(users): showPhotoData = False i += 1 else: - print u'ERROR: %s is not a valid argument for "gam get photo"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam get photo"' % sys.argv[i]) i = 0 count = len(users) for user in users: @@ -3730,8 +3665,7 @@ def printShowCalendars(users, csvFormat): todrive = True i += 1 else: - print u'ERROR: %s is not a valid argument for "gam %s calendars"' % (myarg, [u'show', u'print'][csvFormat]) - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam %s calendars"' % (myarg, [u'show', u'print'][csvFormat])) i = 0 count = len(users) for user in users: @@ -3785,8 +3719,7 @@ def printDriveSettings(users): todrive = True i += 1 else: - print u'ERROR: %s is not a valid argument for "gam show drivesettings"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam show drivesettings"' % sys.argv[i]) dont_show = [u'kind', u'exportFormats', u'importFormats', u'maxUploadSize', u'maxImportSizes', u'user', u'appInstalled'] csvRows = [] titles = [u'email',] @@ -3849,8 +3782,7 @@ def printDriveActivity(users): todrive = True i += 1 else: - print u'ERROR: %s is not a valid argument for "gam show driveactivity"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam show driveactivity"' % sys.argv[i]) for user in users: user, activity = buildActivityGAPIObject(user) if not activity: @@ -3889,8 +3821,7 @@ def showDriveFileACL(users): useDomainAdminAccess = True i += 1 else: - print u'ERROR: %s is not a valid argument to "gam show drivefileacl".' % sys.argv[i] - sys.exit(3) + systemErrorExit(3, '%s is not a valid argument to "gam show drivefileacl".' % sys.argv[i]) for user in users: user, drive = buildDrive3GAPIObject(user) if not drive: @@ -3928,8 +3859,7 @@ def delDriveFileACL(users): useDomainAdminAccess = True i += 1 else: - print u'ERROR: %s is not a valid argument to "gam delete drivefileacl".' % sys.argv[i] - sys.exit(3) + systemErrorExit(3, '%s is not a valid argument to "gam delete drivefileacl".' % sys.argv[i]) for user in users: user, drive = buildDrive3GAPIObject(user) if not drive: @@ -3955,8 +3885,7 @@ def addDriveFileACL(users): body[u'domain'] = sys.argv[7] i = 8 else: - print u'ERROR: permission type must be user, group domain or anyone; got %s' % body[u'type'] - sys.exit(5) + systemErrorExit(5, 'permission type must be user, group domain or anyone; got %s' % body[u'type']) while i < len(sys.argv): myarg = sys.argv[i].lower().replace(u'_', u'') if myarg == u'withlink': @@ -3968,8 +3897,7 @@ def addDriveFileACL(users): elif myarg == u'role': body[u'role'] = sys.argv[i+1] if body[u'role'] not in [u'reader', u'commenter', u'writer', u'owner', u'organizer', u'editor']: - print u'ERROR: role must be reader, commenter, writer, organizer, or owner; got %s' % body[u'role'] - sys.exit(2) + systemErrorExit(2, 'role must be reader, commenter, writer, organizer, or owner; got %s' % body[u'role']) if body[u'role'] == u'editor': body[u'role'] = u'writer' elif body[u'role'] == u'owner': @@ -3990,8 +3918,7 @@ def addDriveFileACL(users): useDomainAdminAccess = True i += 1 else: - print u'ERROR: %s is not a valid argument for "gam add drivefileacl"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam add drivefileacl"' % sys.argv[i]) for user in users: user, drive = buildDrive3GAPIObject(user) if not drive: @@ -4025,8 +3952,7 @@ def updateDriveFileACL(users): elif myarg == u'role': body[u'role'] = sys.argv[i+1] if body[u'role'] not in [u'reader', u'commenter', u'writer', u'owner', u'organizer', u'editor']: - print u'ERROR: role must be reader, commenter, writer, organizer, or owner; got %s' % body[u'role'] - sys.exit(2) + systemErrorExit(2, 'role must be reader, commenter, writer, organizer, or owner; got %s' % body[u'role']) if body[u'role'] == u'editor': body[u'role'] = u'writer' elif body[u'role'] == u'owner': @@ -4036,8 +3962,7 @@ def updateDriveFileACL(users): useDomainAdminAccess = True i += 1 else: - print u'ERROR: %s is not a valid argument for "gam update drivefileacl"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam update drivefileacl"' % sys.argv[i]) for user in users: user, drive = buildDrive3GAPIObject(user) if not drive: @@ -4089,8 +4014,7 @@ def printDriveFileList(users): else: orderByList.append(u'{0} desc'.format(fieldName)) else: - print u'ERROR: orderby must be one of {0}; got {1}'.format(u', '.join(sorted(DRIVEFILE_ORDERBY_CHOICES_MAP.keys())), fieldName) - sys.exit(2) + systemErrorExit(2, 'orderby must be one of {0}; got {1}'.format(u', '.join(sorted(DRIVEFILE_ORDERBY_CHOICES_MAP.keys())), fieldName)) elif myarg == u'query': query += u' and %s' % sys.argv[i+1] i += 2 @@ -4111,8 +4035,7 @@ def printDriveFileList(users): addFieldToCSVfile(myarg, {myarg: [DRIVEFILE_LABEL_CHOICES_MAP[myarg]]}, labelsList, fieldsTitles, titles) i += 1 else: - print u'ERROR: %s is not a valid argument for "gam show filelist"' % myarg - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam show filelist"' % myarg) if fieldsList or labelsList: fields = u'nextPageToken,items(' if fieldsList: @@ -4213,8 +4136,7 @@ def getFileIdFromAlternateLink(altLink): loc = fileId.find(u'&') if loc != -1: return fileId[:loc] - print u'ERROR: %s is not a valid Drive File alternateLink' % altLink - sys.exit(2) + systemErrorExit(2, '%s is not a valid Drive File alternateLink' % altLink) def deleteDriveFile(users): fileIds = sys.argv[5] @@ -4229,8 +4151,7 @@ def deleteDriveFile(users): function = u'untrash' i += 1 else: - print u'ERROR: %s is not a valid argument for "gam delete drivefile"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam delete drivefile"' % sys.argv[i]) action = DELETE_DRIVEFILE_FUNCTION_TO_ACTION_MAP[function] for user in users: user, drive = buildDriveGAPIObject(user) @@ -4285,11 +4206,9 @@ def showDriveFileTree(users): else: orderByList.append(u'{0} desc'.format(fieldName)) else: - print u'ERROR: orderby must be one of {0}; got {1}'.format(u', '.join(sorted(DRIVEFILE_ORDERBY_CHOICES_MAP.keys())), fieldName) - sys.exit(2) + systemErrorExit(2, 'orderby must be one of {0}; got {1}'.format(u', '.join(sorted(DRIVEFILE_ORDERBY_CHOICES_MAP.keys())), fieldName)) else: - print u'ERROR: %s is not a valid argument for "gam show filetree"' % myarg - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam show filetree"' % myarg) if orderByList: orderBy = u','.join(orderByList) else: @@ -4369,8 +4288,7 @@ def getDriveFileAttribute(i, body, parameters, myarg, update=False): elif value in false_values: body[u'labels'][DRIVEFILE_LABEL_CHOICES_MAP[myarg]] = False else: - print u'ERROR: value for %s must be true or false; got %s' % (myarg, sys.argv[i+1]) - sys.exit(2) + systemErrorExit(2, 'value for %s must be true or false; got %s' % (myarg, sys.argv[i+1])) i += 2 else: body[u'labels'][DRIVEFILE_LABEL_CHOICES_MAP[myarg]] = True @@ -4389,8 +4307,7 @@ def getDriveFileAttribute(i, body, parameters, myarg, update=False): if mimeType in MIMETYPE_CHOICES_MAP: body[u'mimeType'] = MIMETYPE_CHOICES_MAP[mimeType] else: - print u'ERROR: mimetype must be one of %s; got %s"' % (u', '.join(MIMETYPE_CHOICES_MAP), mimeType) - sys.exit(2) + systemErrorExit(2, 'mimetype must be one of %s; got %s"' % (u', '.join(MIMETYPE_CHOICES_MAP), mimeType)) i += 2 elif myarg == u'parentid': body.setdefault(u'parents', []) @@ -4406,8 +4323,7 @@ def getDriveFileAttribute(i, body, parameters, myarg, update=False): body[u'writersCanShare'] = False i += 1 else: - print u'ERROR: %s is not a valid argument for "gam %s drivefile"' % (myarg, [u'add', u'update'][update]) - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam %s drivefile"' % (myarg, [u'add', u'update'][update])) return i def doUpdateDriveFile(users): @@ -4436,11 +4352,9 @@ def doUpdateDriveFile(users): else: i = getDriveFileAttribute(i, body, parameters, myarg, True) if not fileIdSelection[u'query'] and not fileIdSelection[u'fileIds']: - print u'ERROR: you need to specify either id, query or drivefilename in order to determine the file(s) to update' - sys.exit(2) + systemErrorExit(2, 'you need to specify either id, query or drivefilename in order to determine the file(s) to update') if fileIdSelection[u'query'] and fileIdSelection[u'fileIds']: - print u'ERROR: you cannot specify multiple file identifiers. Choose one of id, drivefilename, query.' - sys.exit(2) + systemErrorExit(2, 'you cannot specify multiple file identifiers. Choose one of id, drivefilename, query.') for user in users: user, drive = buildDriveGAPIObject(user) if not drive: @@ -4546,8 +4460,7 @@ def downloadDriveFile(users): if exportFormat in DOCUMENT_FORMATS_MAP: exportFormats.extend(DOCUMENT_FORMATS_MAP[exportFormat]) else: - print u'ERROR: format must be one of {0}; got {1}'.format(u', '.join(DOCUMENT_FORMATS_MAP), exportFormat) - sys.exit(2) + systemErrorExit(2, 'format must be one of {0}; got {1}'.format(u', '.join(DOCUMENT_FORMATS_MAP), exportFormat)) i += 2 elif myarg == u'targetfolder': targetFolder = os.path.expanduser(sys.argv[i+1]) @@ -4555,14 +4468,11 @@ def downloadDriveFile(users): os.makedirs(targetFolder) i += 2 else: - print u'ERROR: %s is not a valid argument for "gam get drivefile"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam get drivefile"' % sys.argv[i]) if not fileIdSelection[u'query'] and not fileIdSelection[u'fileIds']: - print u'ERROR: you need to specify either id, query or drivefilename in order to determine the file(s) to download' - sys.exit(2) + systemErrorExit(2, 'you need to specify either id, query or drivefilename in order to determine the file(s) to download') if fileIdSelection[u'query'] and fileIdSelection[u'fileIds']: - print u'ERROR: you cannot specify multiple file identifiers. Choose one of id, drivefilename, query.' - sys.exit(2) + systemErrorExit(2, 'you cannot specify multiple file identifiers. Choose one of id, drivefilename, query.') for user in users: user, drive = buildDriveGAPIObject(user) if not drive: @@ -4647,8 +4557,7 @@ def showDriveFileInfo(users): labelsList.append(DRIVEFILE_LABEL_CHOICES_MAP[myarg]) i += 1 else: - print u'ERROR: %s is not a valid argument for "gam show fileinfo"' % myarg - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam show fileinfo"' % myarg) if fieldsList or labelsList: fieldsList.append(u'title') fields = u','.join(set(fieldsList)) @@ -4684,8 +4593,7 @@ def transferSecCals(users): remove_source_user = False i += 1 else: - print u'ERROR: %s is not a valid argument for "gam transfer seccals"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam transfer seccals"' % sys.argv[i]) if remove_source_user: target_user, target_cal = buildCalendarGAPIObject(target_user) if not target_cal: @@ -4712,8 +4620,7 @@ def transferDriveFiles(users): remove_source_user = False i += 1 else: - print u'ERROR: %s is not a valid argument for "gam transfer drive"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam transfer drive"' % sys.argv[i]) target_user, target_drive = buildDriveGAPIObject(target_user) if not target_drive: return @@ -4807,8 +4714,7 @@ def doImap(users): elif sys.argv[4].lower() in false_values: enable = False else: - print u'ERROR: value for "gam imap" must be true or false; got %s' % sys.argv[4] - sys.exit(2) + systemErrorExit(2, 'value for "gam imap" must be true or false; got %s' % sys.argv[4]) body = {u'enabled': enable, u'autoExpunge': True, u'expungeBehavior': u'archive', u'maxFolderSize': 0} i = 5 while i < len(sys.argv): @@ -4822,19 +4728,16 @@ def doImap(users): body[u'expungeBehavior'] = EMAILSETTINGS_IMAP_EXPUNGE_BEHAVIOR_CHOICES_MAP[opt] i += 2 else: - print u'ERROR: value for "gam imap expungebehavior" must be one of %s; got %s' % (u', '.join(EMAILSETTINGS_IMAP_EXPUNGE_BEHAVIOR_CHOICES_MAP), opt) - sys.exit(2) + systemErrorExit(2, 'value for "gam imap expungebehavior" must be one of %s; got %s' % (u', '.join(EMAILSETTINGS_IMAP_EXPUNGE_BEHAVIOR_CHOICES_MAP), opt)) elif myarg == u'maxfoldersize': opt = sys.argv[i+1].lower() if opt in EMAILSETTINGS_IMAP_MAX_FOLDER_SIZE_CHOICES: body[u'maxFolderSize'] = int(opt) i += 2 else: - print u'ERROR: value for "gam imap maxfoldersize" must be one of %s; got %s' % (u'|'.join(EMAILSETTINGS_IMAP_MAX_FOLDER_SIZE_CHOICES), opt) - sys.exit(2) + systemErrorExit(2, 'value for "gam imap maxfoldersize" must be one of %s; got %s' % (u'|'.join(EMAILSETTINGS_IMAP_MAX_FOLDER_SIZE_CHOICES), opt)) else: - print u'ERROR: %s is not a valid argument for "gam imap"' % myarg - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam imap"' % myarg) i = 0 count = len(users) for user in users: @@ -4899,8 +4802,7 @@ def doLicense(users, operation): if old_sku.lower() == u'from': old_sku = sys.argv[i+1] except KeyError: - print u'ERROR: You need to specify the user\'s old SKU as the last argument' - sys.exit(2) + systemErrorExit(2, 'You need to specify the user\'s old SKU as the last argument') _, old_sku = getProductAndSKU(old_sku) print u'Changing user %s from license %s to %s' % (user, _formatSKUIdDisplayName(old_sku), _formatSKUIdDisplayName(skuId)) callGAPI(lic.licenseAssignments(), operation, soft_errors=True, productId=productId, skuId=old_sku, userId=user, body={u'skuId': skuId}) @@ -4911,8 +4813,7 @@ def doPop(users): elif sys.argv[4].lower() in false_values: enable = False else: - print u'ERROR: value for "gam pop" must be true or false; got %s' % sys.argv[4] - sys.exit(2) + systemErrorExit(2, 'value for "gam pop" must be true or false; got %s' % sys.argv[4]) body = {u'accessWindow': [u'disabled', u'allMail'][enable], u'disposition': u'leaveInInbox'} i = 5 while i < len(sys.argv): @@ -4923,21 +4824,18 @@ def doPop(users): body[u'accessWindow'] = EMAILSETTINGS_POP_ENABLE_FOR_CHOICES_MAP[opt] i += 2 else: - print u'ERROR: value for "gam pop for" must be one of %s; got %s' % (u', '.join(EMAILSETTINGS_POP_ENABLE_FOR_CHOICES_MAP), opt) - sys.exit(2) + systemErrorExit(2, 'value for "gam pop for" must be one of %s; got %s' % (u', '.join(EMAILSETTINGS_POP_ENABLE_FOR_CHOICES_MAP), opt)) elif myarg == u'action': opt = sys.argv[i+1].lower() if opt in EMAILSETTINGS_FORWARD_POP_ACTION_CHOICES_MAP: body[u'disposition'] = EMAILSETTINGS_FORWARD_POP_ACTION_CHOICES_MAP[opt] i += 2 else: - print u'ERROR: value for "gam pop action" must be one of %s; got %s' % (u', '.join(EMAILSETTINGS_FORWARD_POP_ACTION_CHOICES_MAP), opt) - sys.exit(2) + systemErrorExit(2, 'value for "gam pop action" must be one of %s; got %s' % (u', '.join(EMAILSETTINGS_FORWARD_POP_ACTION_CHOICES_MAP), opt)) elif myarg == u'confirm': i += 1 else: - print u'ERROR: %s is not a valid argument for "gam pop"' % myarg - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam pop"' % myarg) i = 0 count = len(users) for user in users: @@ -5036,12 +4934,10 @@ def getSendAsAttributes(i, myarg, body, tagReplacements, command): elif sys.argv[i+1].lower() == u'false': body[u'treatAsAlias'] = False else: - print u'ERROR: value for treatasalias must be true or false; got %s' % sys.argv[i+1] - sys.exit(2) + systemErrorExit(2, 'value for treatasalias must be true or false; got %s' % sys.argv[i+1]) i += 2 else: - print u'ERROR: %s is not a valid argument for "gam %s"' % (sys.argv[i], command) - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam %s"' % (sys.argv[i], command)) return i def addUpdateSendAs(users, i, addCmd): @@ -5123,8 +5019,7 @@ def updateSmime(users): make_default = True i += 1 else: - print u'ERROR: %s is not a valid argument to "gam update smime"' % myarg - sys.exit(3) + systemErrorExit(3, '%s is not a valid argument to "gam update smime"' % myarg) if not make_default: print u'Nothing to update for smime.' sys.exit(0) @@ -5137,13 +5032,10 @@ def updateSmime(users): result = callGAPI(gmail.users().settings().sendAs().smimeInfo(), u'list', userId=u'me', sendAsEmail=sendAsEmail, fields=u'smimeInfo(id)') smimes = result.get(u'smimeInfo', []) if len(smimes) == 0: - print u'ERROR: %s has no S/MIME certificates for sendas address %s' % (user, sendAsEmail) - sys.exit(3) + systemErrorExit(3, '%s has no S/MIME certificates for sendas address %s' % (user, sendAsEmail)) elif len(smimes) > 1: - print u'ERROR: %s has more than one S/MIME certificate. Please specify a cert to update:' - for smime in smimes: - print u' %s' % smime[u'id'] - sys.exit(3) + ids = [u' %s\n' % smime[u'id']for smime in smimes] + systemErrorExit(3, u'%s has more than one S/MIME certificate. Please specify a cert to update:\n%s' % (user, ids)) smimeId = smimes[0][u'id'] else: smimeId = smimeIdBase @@ -5163,8 +5055,7 @@ def deleteSmime(users): sendAsEmailBase = sys.argv[i+1] i += 2 else: - print u'ERROR: %s is not a valid argument to "gam delete smime"' % myarg - sys.exit(3) + systemErrorExit(3, '%s is not a valid argument to "gam delete smime"' % myarg) for user in users: user, gmail = buildGmailGAPIObject(user) if not gmail: @@ -5174,13 +5065,11 @@ def deleteSmime(users): result = callGAPI(gmail.users().settings().sendAs().smimeInfo(), u'list', userId=u'me', sendAsEmail=sendAsEmail, fields=u'smimeInfo(id)') smimes = result.get(u'smimeInfo', []) if len(smimes) == 0: - print u'ERROR: %s has no S/MIME certificates for sendas address %s' % (user, sendAsEmail) - sys.exit(3) + systemErrorExit(3, '%s has no S/MIME certificates for sendas address %s' % (user, sendAsEmail)) elif len(smimes) > 1: - print u'ERROR: %s has more than one S/MIME certificate. Please specify a cert to delete:' - for smime in smimes: - print u' %s' % smime[u'id'] - sys.exit(3) + ids = [u' %s' % smime[u'id'] for smime in smimes] + systemErrorExit( + 3, u'%s has more than one S/MIME certificate. Please specify a cert to delete:\n%s' % (user, ids)) smimeId = smimes[0][u'id'] else: smimeId = smimeIdBase @@ -5202,8 +5091,7 @@ def printShowSmime(users, csvFormat): primaryonly = True i += 1 else: - print u'ERROR: %s is not a valid argument for "gam %s smime"' % (myarg, [u'show', u'print'][csvFormat]) - sys.exit(3) + systemErrorExit(3, '%s is not a valid argument for "gam %s smime"' % (myarg, [u'show', u'print'][csvFormat])) i = 0 count = len(users) for user in users: @@ -5247,8 +5135,7 @@ def printShowSendAs(users, csvFormat): formatSig = True i += 1 else: - print u'ERROR: %s is not a valid argument for "gam %s sendas"' % (myarg, [u'show', u'print'][csvFormat]) - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam %s sendas"' % (myarg, [u'show', u'print'][csvFormat])) i = 0 count = len(users) for user in users: @@ -5293,8 +5180,7 @@ def infoSendAs(users): formatSig = True i += 1 else: - print u'ERROR: %s is not a valid argument for "gam info sendas"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam info sendas"' % sys.argv[i]) i = 0 count = len(users) for user in users: @@ -5330,11 +5216,9 @@ def addSmime(users): sendAsEmailBase = sys.argv[i+1] i += 2 else: - print u'ERROR: %s is not a valid argument for "gam add smime"' % myarg - sys.exit(3) + systemErrorExit(3, '%s is not a valid argument for "gam add smime"' % myarg) if u'pkcs12' not in body: - print u'ERROR: you must specify a file to upload' - sys.exit(3) + systemErrorExit(3, 'you must specify a file to upload') i = 0 count = len(users) for user in users: @@ -5363,18 +5247,15 @@ def doLabel(users, i): elif value == u'showifunread': body[u'labelListVisibility'] = u'labelShowIfUnread' else: - print u'ERROR: label_list_visibility must be one of hide, show, show_if_unread; got %s' % sys.argv[i+1] - sys.exit(2) + systemErrorExit(2, 'label_list_visibility must be one of hide, show, show_if_unread; got %s' % sys.argv[i+1]) i += 2 elif myarg == u'messagelistvisibility': body[u'messageListVisibility'] = sys.argv[i+1].lower().replace(u'_', u'') if body[u'messageListVisibility'] not in [u'hide', u'show']: - print u'ERROR: message_list_visibility must be show or hide; got %s' % sys.argv[i+1] - sys.exit(2) + systemErrorExit(2, 'message_list_visibility must be show or hide; got %s' % sys.argv[i+1]) i += 2 else: - print u'ERROR: %s is not a valid argument for this command.' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for this command.' % sys.argv[i]) i = 0 count = len(users) for user in users: @@ -5459,11 +5340,9 @@ def doProcessMessagesOrThreads(users, function, unit=u'messages'): body[u'removeLabelIds'].append(sys.argv[i+1]) i += 2 else: - print u'ERROR: %s is not a valid argument for "gam %s %s"' % (sys.argv[i], function, unit) - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam %s %s"' % (sys.argv[i], function, unit)) if not query: - print u'ERROR: No query specified. You must specify some query!' - sys.exit(2) + systemErrorExit(2, 'No query specified. You must specify some query!') action = PROCESS_MESSAGE_FUNCTION_TO_ACTION_MAP[function] for user in users: user, gmail = buildGmailGAPIObject(user) @@ -5573,8 +5452,7 @@ def showLabels(users): showCounts = True i += 1 else: - print u'ERROR: %s is not a valid argument for "gam show labels"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam show labels"' % sys.argv[i]) for user in users: user, gmail = buildGmailGAPIObject(user) if not gmail: @@ -5606,8 +5484,7 @@ def showGmailProfile(users): todrive = True i += 1 else: - print u'ERROR: %s is not a valid argument for gam show gmailprofile' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for gam show gmailprofile' % sys.argv[i]) csvRows = [] titles = [u'emailAddress'] i = 0 @@ -5641,8 +5518,7 @@ def showGplusProfile(users): todrive = True i += 1 else: - print u'ERROR: %s is not a valid argument for gam show gplusprofile' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for gam show gplusprofile' % sys.argv[i]) csvRows = [] titles = [u'id'] i = 0 @@ -5687,18 +5563,15 @@ def updateLabels(users): elif value == u'showifunread': body[u'labelListVisibility'] = u'labelShowIfUnread' else: - print u'ERROR: label_list_visibility must be hide, show, show_if_unread; got %s' % sys.argv[i+1] - sys.exit(2) + systemErrorExit(2, 'label_list_visibility must be hide, show, show_if_unread; got %s' % sys.argv[i+1]) i += 2 elif myarg == u'messagelistvisibility': body[u'messageListVisibility'] = sys.argv[i+1].lower().replace(u'_', u'') if body[u'messageListVisibility'] not in [u'hide', u'show']: - print u'ERROR: message_list_visibility must be show or hide; got %s' % sys.argv[i+1] - sys.exit(2) + systemErrorExit(2, 'message_list_visibility must be show or hide; got %s' % sys.argv[i+1]) i += 2 else: - print u'ERROR: %s is not a valid argument for "gam update labels"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam update labels"' % sys.argv[i]) for user in users: user, gmail = buildGmailGAPIObject(user) if not gmail: @@ -5729,8 +5602,7 @@ def renameLabels(users): merge = True i += 1 else: - print u'ERROR: %s is not a valid argument for "gam rename label"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam rename label"' % sys.argv[i]) pattern = re.compile(search, re.IGNORECASE) for user in users: user, gmail = buildGmailGAPIObject(user) @@ -5745,8 +5617,7 @@ def renameLabels(users): try: new_label_name = replace % match_result.groups() except TypeError: - print u'ERROR: The number of subfields ({0}) in search "{1}" does not match the number of subfields ({2}) in replace "{3}"'.format(len(match_result.groups()), search, replace.count(u'%s'), replace) - sys.exit(2) + systemErrorExit(2, 'The number of subfields ({0}) in search "{1}" does not match the number of subfields ({2}) in replace "{3}"'.format(len(match_result.groups()), search, replace.count(u'%s'), replace)) print u' Renaming "%s" to "%s"' % (label[u'name'], new_label_name) try: callGAPI(gmail.users().labels(), u'patch', soft_errors=True, throw_reasons=[GAPI_ABORTED], id=label[u'id'], userId=user, body={u'name': new_label_name}) @@ -5882,8 +5753,7 @@ def addFilter(users, i): elif myarg == u'size': body[u'criteria'][u'sizeComparison'] = sys.argv[i+1].lower() if body[u'criteria'][u'sizeComparison'] not in [u'larger', u'smaller']: - print u'ERROR: size must be followed by larger or smaller; got %s' % sys.argv[i+1].lower() - sys.exit(2) + systemErrorExit(2, 'size must be followed by larger or smaller; got %s' % sys.argv[i+1].lower()) body[u'criteria'][myarg] = sys.argv[i+2] i += 3 elif myarg in FILTER_ACTION_CHOICES: @@ -5920,14 +5790,11 @@ def addFilter(users, i): body[u'action'][u'forward'] = sys.argv[i+1] i += 2 else: - print u'ERROR: %s is not a valid argument for "gam filter"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam filter"' % sys.argv[i]) if u'criteria' not in body: - print u'ERROR: you must specify a crtieria <{0}> for "gam filter"'.format(u'|'.join(FILTER_CRITERIA_CHOICES_MAP)) - sys.exit(2) + systemErrorExit(2, 'you must specify a crtieria <{0}> for "gam filter"'.format(u'|'.join(FILTER_CRITERIA_CHOICES_MAP))) if u'action' not in body: - print u'ERROR: you must specify an action <{0}> for "gam filter"'.format(u'|'.join(FILTER_ACTION_CHOICES)) - sys.exit(2) + systemErrorExit(2, 'you must specify an action <{0}> for "gam filter"'.format(u'|'.join(FILTER_ACTION_CHOICES))) if removeLabelIds: body[u'action'][u'removeLabelIds'] = removeLabelIds i = 0 @@ -5987,8 +5854,7 @@ def printShowFilters(users, csvFormat): todrive = True i += 1 else: - print u'ERROR: %s is not a valid argument for "gam %s filter"' % (myarg, [u'show', u'print'][csvFormat]) - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam %s filter"' % (myarg, [u'show', u'print'][csvFormat])) i = 0 count = len(users) for user in users: @@ -6053,8 +5919,7 @@ def doForward(users): elif sys.argv[4].lower() in false_values: enable = False else: - print u'ERROR: value for "gam forward" must be true or false; got %s' % sys.argv[4] - sys.exit(2) + systemErrorExit(2, 'value for "gam forward" must be true or false; got %s' % sys.argv[4]) body = {u'enabled': enable} i = 5 while i < len(sys.argv): @@ -6068,11 +5933,9 @@ def doForward(users): body[u'emailAddress'] = sys.argv[i] i += 1 else: - print u'ERROR: %s is not a valid argument for "gam forward"' % myarg - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam forward"' % myarg) if enable and (not body.get(u'disposition') or not body.get(u'emailAddress')): - print u'ERROR: you must specify an action and a forwarding address for "gam forward' - sys.exit(2) + systemErrorExit(2, 'you must specify an action and a forwarding address for "gam forward') i = 0 count = len(users) for user in users: @@ -6127,8 +5990,7 @@ def printShowForward(users, csvFormat): todrive = True i += 1 else: - print u'ERROR: %s is not a valid argument for "gam %s forward"' % (myarg, [u'show', u'print'][csvFormat]) - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam %s forward"' % (myarg, [u'show', u'print'][csvFormat])) i = 0 count = len(users) for user in users: @@ -6192,8 +6054,7 @@ def printShowForwardingAddresses(users, csvFormat): todrive = True i += 1 else: - print u'ERROR: %s is not a valid argument for "gam %s forwardingaddresses"' % (myarg, [u'show', u'print'][csvFormat]) - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam %s forwardingaddresses"' % (myarg, [u'show', u'print'][csvFormat])) i = 0 count = len(users) for user in users: @@ -6280,8 +6141,7 @@ def getSignature(users): formatSig = True i += 1 else: - print u'ERROR: %s is not a valid argument for "gam show signature"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam show signature"' % sys.argv[i]) i = 0 count = len(users) for user in users: @@ -6301,8 +6161,7 @@ def doVacation(users): elif sys.argv[4].lower() in false_values: enable = False else: - print u'ERROR: value for "gam vacation" must be true or false; got %s' % sys.argv[4] - sys.exit(2) + systemErrorExit(2, 'value for "gam vacation" must be true or false; got %s' % sys.argv[4]) body = {u'enableAutoReply': enable} if enable: responseBodyType = u'responseBodyPlainText' @@ -6342,8 +6201,7 @@ def doVacation(users): body[u'endTime'] = getYYYYMMDD(i+1, returnTimeStamp=True) i += 2 else: - print u'ERROR: %s is not a valid argument for "gam vacation"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam vacation"' % sys.argv[i]) if message: if responseBodyType == u'responseBodyHtml': message = message.replace(u'\r', u'').replace(u'\\n', u'
') @@ -6353,8 +6211,7 @@ def doVacation(users): message = _processTags(tagReplacements, message) body[responseBodyType] = message if not message and not body.get(u'responseSubject'): - print u'ERROR: You must specify a non-blank subject or message!' - sys.exit(2) + systemErrorExit(2, 'You must specify a non-blank subject or message!') i = 0 count = len(users) for user in users: @@ -6376,8 +6233,7 @@ def getVacation(users): formatReply = True i += 1 else: - print u'ERROR: %s is not a valid argument for "gam show vacation"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam show vacation"' % sys.argv[i]) i = 0 count = len(users) for user in users: @@ -6429,8 +6285,7 @@ def doCreateOrUpdateUserSchema(updateCmd): try: body = callGAPI(cd.schemas(), u'get', throw_reasons=[GAPI_NOT_FOUND], customerId=GC_Values[GC_CUSTOMER_ID], schemaKey=schemaKey) except GAPI_notFound: - print u'ERROR: Schema %s does not exist.' % schemaKey - sys.exit(3) + systemErrorExit(3, 'Schema %s does not exist.' % schemaKey) else: # create cmd = u'create' body = {u'schemaName': schemaKey, u'fields': []} @@ -6450,8 +6305,7 @@ def doCreateOrUpdateUserSchema(updateCmd): if myarg == u'type': a_field[u'fieldType'] = sys.argv[i+1].upper() if a_field[u'fieldType'] not in [u'BOOL', u'DOUBLE', u'EMAIL', u'INT64', u'PHONE', u'STRING']: - print u'ERROR: type must be one of bool, double, email, int64, phone, string; got %s' % a_field[u'fieldType'] - sys.exit(2) + systemErrorExit(2, 'type must be one of bool, double, email, int64, phone, string; got %s' % a_field[u'fieldType']) i += 2 elif myarg == u'multivalued': a_field[u'multiValued'] = True @@ -6470,20 +6324,17 @@ def doCreateOrUpdateUserSchema(updateCmd): i += 1 break else: - print u'ERROR: %s is not a valid argument for "gam %s schema"' % (sys.argv[i], cmd) - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam %s schema"' % (sys.argv[i], cmd)) elif updateCmd and myarg == u'deletefield': for n, field in enumerate(body[u'fields']): if field[u'fieldName'].lower() == sys.argv[i+1].lower(): del body[u'fields'][n] break else: - print u'ERROR: field %s not found in schema %s' % (sys.argv[i+1], schemaKey) - sys.exit(3) + systemErrorExit(3, 'field %s not found in schema %s' % (sys.argv[i+1], schemaKey)) i += 2 else: - print u'ERROR: %s is not a valid argument for "gam %s schema"' % (sys.argv[i], cmd) - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam %s schema"' % (sys.argv[i], cmd)) if updateCmd: result = callGAPI(cd.schemas(), u'update', customerId=GC_Values[GC_CUSTOMER_ID], body=body, schemaKey=schemaKey) print u'Updated user schema %s' % result[u'schemaName'] @@ -6515,8 +6366,7 @@ def doPrintShowUserSchemas(csvFormat): todrive = True i += 1 else: - print u'ERROR: %s is not a valid argument for "gam %s schemas"' % (myarg, [u'show', u'print'][csvFormat]) - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam %s schemas"' % (myarg, [u'show', u'print'][csvFormat])) schemas = callGAPI(cd.schemas(), u'list', customerId=GC_Values[GC_CUSTOMER_ID]) if not schemas or u'schemas' not in schemas: return @@ -6581,8 +6431,7 @@ def getUserAttributes(i, cd, updateCmd=False): for citem in body[itemName]: if citem.get(u'primary', False): if not checkSystemId or itemValue.get(u'systemId') == citem.get(u'systemId'): - print u'ERROR: Multiple {0} are marked primary, only one can be primary'.format(itemName) - sys.exit(2) + systemErrorExit(2, 'Multiple {0} are marked primary, only one can be primary'.format(itemName)) body[itemName].append(itemValue) def _splitSchemaNameDotFieldName(sn_fn, fnRequired=True): @@ -6596,8 +6445,7 @@ def getUserAttributes(i, cd, updateCmd=False): schemaName = sn_fn.strip() if schemaName: return (schemaName, None) - print u'ERROR: %s is not a valid custom schema.field name.' % sn_fn - sys.exit(2) + systemErrorExit(2, '%s is not a valid custom schema.field name.' % sn_fn) if updateCmd: body = {} @@ -6641,8 +6489,7 @@ def getUserAttributes(i, cd, updateCmd=False): elif sys.argv[i+1].lower() in false_values: admin_body[u'status'] = False else: - print u'ERROR: admin must be on or off; got %s' % sys.argv[i+1] - sys.exit(2) + systemErrorExit(2, 'admin must be on or off; got %s' % sys.argv[i+1]) i += 2 elif myarg == u'suspended': if sys.argv[i+1].lower() in true_values: @@ -6650,8 +6497,7 @@ def getUserAttributes(i, cd, updateCmd=False): elif sys.argv[i+1].lower() in false_values: body[u'suspended'] = False else: - print u'ERROR: suspended must be on or off; got %s' % sys.argv[i+1] - sys.exit(2) + systemErrorExit(2, 'suspended must be on or off; got %s' % sys.argv[i+1]) i += 2 elif myarg == u'gal': if sys.argv[i+1].lower() in true_values: @@ -6659,8 +6505,7 @@ def getUserAttributes(i, cd, updateCmd=False): elif sys.argv[i+1].lower() in false_values: body[u'includeInGlobalAddressList'] = False else: - print u'ERROR: gal must be on or off; got %s' % sys.argv[i+1] - sys.exit(2) + systemErrorExit(2, 'gal must be on or off; got %s' % sys.argv[i+1]) i += 2 elif myarg in [u'sha', u'sha1', u'sha-1']: body[u'hashFunction'] = u'SHA-1' @@ -6683,8 +6528,7 @@ def getUserAttributes(i, cd, updateCmd=False): elif sys.argv[i+1].lower() in false_values: body[u'changePasswordAtNextLogin'] = False else: - print u'ERROR: changepassword must be on or off; got %s' % sys.argv[i+1] - sys.exit(2) + systemErrorExit(2, 'changepassword must be on or off; got %s' % sys.argv[i+1]) i += 2 elif myarg == u'ipwhitelisted': if sys.argv[i+1].lower() in true_values: @@ -6692,8 +6536,7 @@ def getUserAttributes(i, cd, updateCmd=False): elif sys.argv[i+1].lower() in false_values: body[u'ipWhitelisted'] = False else: - print u'ERROR: ipwhitelisted must be on or off; got %s' % sys.argv[i+1] - sys.exit(2) + systemErrorExit(2, 'ipwhitelisted must be on or off; got %s' % sys.argv[i+1]) i += 2 elif myarg == u'agreedtoterms': if sys.argv[i+1].lower() in true_values: @@ -6701,8 +6544,7 @@ def getUserAttributes(i, cd, updateCmd=False): elif sys.argv[i+1].lower() in false_values: body[u'agreedToTerms'] = False else: - print u'ERROR: agreedtoterms must be on or off; got %s' % sys.argv[i+1] - sys.exit(2) + systemErrorExit(2, 'agreedtoterms must be on or off; got %s' % sys.argv[i+1]) i += 2 elif myarg in [u'org', u'ou']: body[u'orgUnitPath'] = sys.argv[i+1] @@ -6716,8 +6558,7 @@ def getUserAttributes(i, cd, updateCmd=False): continue address = {} if sys.argv[i].lower() != u'type': - print u'ERROR: wrong format for account address details. Expected type got %s' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, 'wrong format for account address details. Expected type got %s' % sys.argv[i]) i = getEntryType(i+1, address, USER_ADDRESS_TYPES) if sys.argv[i].lower() in [u'unstructured', u'formatted']: i += 1 @@ -6755,8 +6596,7 @@ def getUserAttributes(i, cd, updateCmd=False): i += 1 break else: - print u'ERROR: invalid argument (%s) for account address details' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, 'invalid argument (%s) for account address details' % sys.argv[i]) appendItemToBodyList(body, u'addresses', address) elif myarg in [u'emails', u'otheremail', u'otheremails']: i += 1 @@ -6775,17 +6615,14 @@ def getUserAttributes(i, cd, updateCmd=False): continue im = {} if sys.argv[i].lower() != u'type': - print u'ERROR: wrong format for account im details. Expected type got %s' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, 'wrong format for account im details. Expected type got %s' % sys.argv[i]) i = getEntryType(i+1, im, USER_IM_TYPES) if sys.argv[i].lower() != u'protocol': - print u'ERROR: wrong format for account details. Expected protocol got %s' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, 'wrong format for account details. Expected protocol got %s' % sys.argv[i]) i += 1 im[u'protocol'] = sys.argv[i].lower() if im[u'protocol'] not in [u'custom_protocol', u'aim', u'gtalk', u'icq', u'jabber', u'msn', u'net_meeting', u'qq', u'skype', u'yahoo']: - print u'ERROR: protocol must be one of custom_protocol, aim, gtalk, icq, jabber, msn, net_meeting, qq, skype, yahoo; got %s' % im[u'protocol'] - sys.exit(2) + systemErrorExit(2, 'protocol must be one of custom_protocol, aim, gtalk, icq, jabber, msn, net_meeting, qq, skype, yahoo; got %s' % im[u'protocol']) if im[u'protocol'] == u'custom_protocol': i += 1 im[u'customProtocol'] = sys.argv[i] @@ -6845,8 +6682,7 @@ def getUserAttributes(i, cd, updateCmd=False): i += 1 break else: - print u'ERROR: invalid argument (%s) for account organization details' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, 'invalid argument (%s) for account organization details' % sys.argv[i]) appendItemToBodyList(body, u'organizations', organization) elif myarg in [u'phone', u'phones']: i += 1 @@ -6866,8 +6702,7 @@ def getUserAttributes(i, cd, updateCmd=False): i += 1 break else: - print u'ERROR: invalid argument (%s) for account phone details' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, 'invalid argument (%s) for account phone details' % sys.argv[i]) appendItemToBodyList(body, u'phones', phone) elif myarg in [u'relation', u'relations']: i += 1 @@ -6949,8 +6784,7 @@ def getUserAttributes(i, cd, updateCmd=False): i += 1 break else: - print u'ERROR: %s is not a valid argument for user location details. Make sure user location details end with an endlocation argument' - sys.exit(3) + systemErrorExit(3, '%s is not a valid argument for user location details. Make sure user location details end with an endlocation argument') appendItemToBodyList(body, u'locations', location) elif myarg in [u'ssh', u'sshkeys', u'sshpublickeys']: i += 1 @@ -6970,8 +6804,7 @@ def getUserAttributes(i, cd, updateCmd=False): i += 1 break else: - print u'ERROR: %s is not a valid argument for user ssh details. Make sure user ssh details end with an endssh argument' - sys.exit(3) + systemErrorExit(3, '%s is not a valid argument for user ssh details. Make sure user ssh details end with an endssh argument') appendItemToBodyList(body, u'sshPublicKeys', ssh) elif myarg in [u'posix', u'posixaccounts']: i += 1 @@ -6999,8 +6832,7 @@ def getUserAttributes(i, cd, updateCmd=False): elif sys.argv[i+1] in false_values: posix[u'primary'] = False else: - print u'ERROR: primary should be true or false, got %s' % sys.argv[i+1] - sys.exit(3) + systemErrorExit(3, 'primary should be true or false, got %s' % sys.argv[i+1]) i += 2 elif myopt in [u'shell']: posix[u'shell'] = sys.argv[i+1] @@ -7015,13 +6847,11 @@ def getUserAttributes(i, cd, updateCmd=False): i += 1 break else: - print u'ERROR: %s is not a valid argument for user posix details. Make sure user posix details end with an endposix argument' - sys.exit(3) + systemErrorExit(3, '%s is not a valid argument for user posix details. Make sure user posix details end with an endposix argument') appendItemToBodyList(body, u'posixAccounts', posix, checkSystemId=True) elif myarg == u'clearschema': if not updateCmd: - print u'ERROR: %s is not a valid create user argument.' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid create user argument.' % sys.argv[i]) schemaName, fieldName = _splitSchemaNameDotFieldName(sys.argv[i+1], False) up = u'customSchemas' body.setdefault(up, {}) @@ -7052,8 +6882,7 @@ def getUserAttributes(i, cd, updateCmd=False): i += 1 schemaValue[u'type'] = sys.argv[i].lower() if schemaValue[u'type'] not in [u'custom', u'home', u'other', u'work']: - print u'ERROR: wrong type must be one of custom, home, other, work; got %s' % schemaValue[u'type'] - sys.exit(2) + systemErrorExit(2, 'wrong type must be one of custom, home, other, work; got %s' % schemaValue[u'type']) i += 1 if schemaValue[u'type'] == u'custom': schemaValue[u'customType'] = sys.argv[i] @@ -7065,8 +6894,7 @@ def getUserAttributes(i, cd, updateCmd=False): body[up][schemaName][fieldName] = sys.argv[i] i += 1 else: - print u'ERROR: %s is not a valid argument for "gam %s user"' % (sys.argv[i], [u'create', u'update'][updateCmd]) - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam %s user"' % (sys.argv[i], [u'create', u'update'][updateCmd])) if need_password: body[u'password'] = u''.join(random.sample(u'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789~`!@#$%^&*()-=_+:;"\'{}[]\\|', 25)) if u'password' in body and need_to_hash_password: @@ -7199,8 +7027,7 @@ def doCreateProject(login_hint=None): client_secrets_file = GC_Values[GC_CLIENT_SECRETS_JSON] for a_file in [service_account_file, client_secrets_file]: if os.path.exists(a_file): - print u'ERROR: %s already exists. Please delete or rename it before attempting to create another project.' % a_file - sys.exit(5) + systemErrorExit(5, '%s already exists. Please delete or rename it before attempting to create another project.' % a_file) login_hint = getValidateLoginHint(login_hint) login_domain = login_hint[login_hint.find(u'@')+1:] crm, httpObj = getCRMService(login_hint) @@ -7230,8 +7057,7 @@ def doCreateProject(login_hint=None): organization = getorg[u'organizations'][0][u'name'] print u'Your organization name is %s' % organization except (KeyError, IndexError): - print u'ERROR: you have no rights to create projects for your organization and you don\'t seem to be a super admin! Sorry, there\'s nothing more I can do.' - sys.exit(3) + systemErrorExit(3, 'you have no rights to create projects for your organization and you don\'t seem to be a super admin! Sorry, there\'s nothing more I can do.') org_policy = callGAPI(crm.organizations(), u'getIamPolicy', resource=organization, body={}) if u'bindings' not in org_policy: @@ -7349,8 +7175,7 @@ def doGetTeamDriveInfo(users): useDomainAdminAccess = True i += 1 else: - print u'ERROR: %s is not a valid command for "gam show teamdrive"' % sys.argv[i] - sys.exit(3) + systemErrorExit(3, '%s is not a valid command for "gam show teamdrive"' % sys.argv[i]) for user in users: drive = buildGAPIServiceObject(u'drive3', user) if not drive: @@ -7369,8 +7194,7 @@ def doCreateTeamDrive(users): body[u'themeId'] = sys.argv[i+1] i += 2 else: - print u'ERROR: %s is not a valid argument to "gam create teamdrive"' % sys.argv[i] - sys.exit(3) + systemErrorExit(3, '%s is not a valid argument to "gam create teamdrive"' % sys.argv[i]) for user in users: drive = buildGAPIServiceObject(u'drive3', user) if not drive: @@ -7404,12 +7228,9 @@ def doUpdateTeamDrive(users): body[u'colorRgb'] = WEBCOLOR_MAP.get(sys.argv[i+1], sys.argv[i+1]) i += 2 else: - print u'ERROR: %s is not a valid argument for "gam update drivefile"' - sys.exit(3) + systemErrorExit(3, '%s is not a valid argument for "gam update drivefile"') if not body: - print u'ERROR: nothing to update. Need at least a name argument.' - print body - sys.exit(4) + systemErrorExit(4, u'nothing to update. Need at least a name argument.\n%s' % body) for user in users: user, drive = buildDrive3GAPIObject(user) if not drive: @@ -7436,8 +7257,7 @@ def printShowTeamDrives(users, csvFormat): q = sys.argv[i+1] i += 2 else: - print u'ERROR: %s is not a valid argument for "gam print|show teamdrives"' - sys.exit(3) + systemErrorExit(3, '%s is not a valid argument for "gam print|show teamdrives"') tds = [] for user in users: sys.stderr.write(u'Getting Team Drives for %s\n' % user) @@ -7479,8 +7299,7 @@ def validateCollaborators(collaboratorList, cd): for collaborator in collaboratorList.split(u','): collaborator_id = convertEmailAddressToUID(collaborator, cd) if not collaborator_id: - print u'ERROR: failed to get a UID for %s. Please make sure this is a real user.' % collaborator - sys.exit(4) + systemErrorExit(4, 'failed to get a UID for %s. Please make sure this is a real user.' % collaborator) collaborators.append({u'email': collaborator, u'id': collaborator_id}) return collaborators @@ -7504,8 +7323,7 @@ def doCreateVaultMatter(): collaborators.extend(validateCollaborators(sys.argv[i+1], cd)) i += 2 else: - print u'ERROR: %s is not a valid argument to "gam create matter"' % sys.argv[i] - sys.exit(3) + systemErrorExit(3, '%s is not a valid argument to "gam create matter"' % sys.argv[i]) result = callGAPI(v.matters(), u'create', body=body, fields=u'matterId') matterId = result[u'matterId'] print u'Created matter %s' % matterId @@ -7536,8 +7354,7 @@ def doCreateVaultHold(): elif myarg == u'corpus': body[u'corpus'] = sys.argv[i+1].upper() if body[u'corpus'] not in allowed_corpuses: - print u'ERROR: corpus must be one of %s. Got %s' % (u', '.join(allowed_corpuses), sys.argv[i+1]) - sys.exit(3) + systemErrorExit(3, 'corpus must be one of %s. Got %s' % (u', '.join(allowed_corpuses), sys.argv[i+1])) i += 2 elif myarg in [u'accounts', u'users', u'groups']: accounts = sys.argv[i+1].split(u',') @@ -7558,21 +7375,16 @@ def doCreateVaultHold(): elif myarg == u'matter': matterId = convertMatterNameToID(v, sys.argv[i+1]) if not matterId: - print u'ERROR: could not find matter %s' % sys.argv[i+1] - sys.exit(4) + systemErrorExit(4, 'could not find matter %s' % sys.argv[i+1]) i += 2 else: - print u'ERROR: %s is not a valid argument to "gam create hold"' % sys.argv[i] - sys.exit(3) + systemErrorExit(3, '%s is not a valid argument to "gam create hold"' % sys.argv[i]) if not matterId: - print u'ERROR: you must specify a matter for the new hold.' - sys.exit(3) + systemErrorExit(3, 'you must specify a matter for the new hold.') if not body.get(u'name'): - print u'ERROR: you must specify a name for the new hold.' - sys.exit(3) + systemErrorExit(3, 'you must specify a name for the new hold.') if not body.get(u'corpus'): - print u'ERROR: you must specify corpus for the new hold. One of %s' % (u', '.join(allowed_corpuses)) - sys.exit(3) + systemErrorExit(3, 'you must specify corpus for the new hold. One of %s' % (u', '.join(allowed_corpuses))) query_type = u'%sQuery' % body[u'corpus'].lower() body[u'query'][query_type] = {} if body[u'corpus'] == u'DRIVE': @@ -7580,8 +7392,7 @@ def doCreateVaultHold(): try: body[u'query'][query_type] = json.loads(query) except ValueError as e: - print u'Error: {0}, query: {1}'.format(str(e), query) - sys.exit(3) + systemErrorExit(3, '{0}, query: {1}'.format(str(e), query)) elif body[u'corpus'] in [u'GROUPS', u'MAIL']: if query: body[u'query'][query_type] = {u'terms': query} @@ -7607,19 +7418,15 @@ def doDeleteVaultHold(): if myarg == u'matter': matterId = convertMatterNameToID(v, sys.argv[i+1]) if not matterId: - print u'ERROR: could not find matter %s' % sys.argv[i+1] - sys.exit(4) + systemErrorExit(4, 'could not find matter %s' % sys.argv[i+1]) holdId = convertHoldNameToID(v, hold, matterId) if not holdId: - print u'ERROR: could not find hold %s in matter %s' % (sys.argv[3], matterId) - sys.exit(4) + systemErrorExit(4, 'could not find hold %s in matter %s' % (sys.argv[3], matterId)) i += 2 else: - print u'ERROR: %s is not a valid argument to "gam delete hold"' % myarg - sys.exit(3) + systemErrorExit(3, '%s is not a valid argument to "gam delete hold"' % myarg) if not matterId: - print u'ERROR: you must specify a matter for the hold.' - sys.exit(3) + systemErrorExit(3, 'you must specify a matter for the hold.') print u'Deleting hold %s / %s' % (hold, holdId) callGAPI(v.matters().holds(), u'delete', matterId=matterId, holdId=holdId) @@ -7633,19 +7440,15 @@ def doGetVaultHoldInfo(): if myarg == u'matter': matterId = convertMatterNameToID(v, sys.argv[i+1]) if not matterId: - print u'ERROR: could not find matter %s' % sys.argv[i+1] - sys.exit(4) + systemErrorExit(4, 'could not find matter %s' % sys.argv[i+1]) holdId = convertHoldNameToID(v, hold, matterId) if not holdId: - print u'ERROR: could not find hold %s in matter %s' % (hold, matterId) - sys.exit(4) + systemErrorExit(4, 'could not find hold %s in matter %s' % (hold, matterId)) i += 2 else: - print u'ERROR: %s is not a valid argument for "gam info hold"' % myarg - sys.exit(3) + systemErrorExit(3, '%s is not a valid argument for "gam info hold"' % myarg) if not matterId: - print u'ERROR: you must specify a matter for the hold.' - sys.exit(3) + systemErrorExit(3, 'you must specify a matter for the hold.') results = callGAPI(v.matters().holds(), u'get', matterId=matterId, holdId=holdId) cd = buildGAPIObject(u'directory') if u'accounts' in results: @@ -7696,12 +7499,10 @@ def doUpdateVaultHold(): if myarg == u'matter': matterId = convertMatterNameToID(v, sys.argv[i+1]) if not matterId: - print u'ERROR: could not find matter %s' % sys.argv[i+1] - sys.exit(4) + systemErrorExit(4, 'could not find matter %s' % sys.argv[i+1]) holdId = convertHoldNameToID(v, hold, matterId) if not holdId: - print u'ERROR: could not find hold %s in matter %s' % (hold, matterId) - sys.exit(4) + systemErrorExit(4, 'could not find hold %s in matter %s' % (hold, matterId)) i += 2 elif myarg == u'query': query = sys.argv[i+1] @@ -7726,11 +7527,9 @@ def doUpdateVaultHold(): del_accounts = sys.argv[i+1].split(u',') i += 2 else: - print u'ERROR: %s is not a valid argument to "gam update hold"' % myarg - sys.exit(3) + systemErrorExit(3, '%s is not a valid argument to "gam update hold"' % myarg) if not matterId: - print u'ERROR: you must specify a matter for the hold.' - sys.exit(3) + systemErrorExit(3, 'you must specify a matter for the hold.') if query or start_time or end_time or body.get(u'orgUnit'): old_body = callGAPI(v.matters().holds(), u'get', matterId=matterId, holdId=holdId, fields=u'corpus,query,orgUnit') body[u'query'] = old_body[u'query'] @@ -7744,8 +7543,7 @@ def doUpdateVaultHold(): try: body[u'query'][query_type] = json.loads(query) except ValueError as e: - print u'Error: {0}, query: {1}'.format(str(e), query) - sys.exit(3) + systemErrorExit(3, '{0}, query: {1}'.format(str(e), query)) elif body[u'corpus'] in [u'GROUPS', u'MAIL']: if query: body[u'query'][query_type][u'terms'] = query @@ -7771,8 +7569,7 @@ def doUpdateVaultMatter(action=None): v = buildGAPIObject(u'vault') matterId = convertMatterNameToID(v, sys.argv[3]) if not matterId: - print u'ERROR: failed to lookup matter named %s' % sys.argv[3] - sys.exit(4) + systemErrorExit(4, 'failed to lookup matter named %s' % sys.argv[3]) body = {} action_kwargs = {u'body': {}} add_collaborators = [] @@ -7784,8 +7581,7 @@ def doUpdateVaultMatter(action=None): if myarg == u'action': action = sys.argv[i+1].lower() if action not in VAULT_MATTER_ACTIONS: - print u'ERROR: allowed actions are %s, got %s' % (u', '.join(VAULT_MATTER_ACTIONS), action) - sys.exit(3) + systemErrorExit(3, 'allowed actions are %s, got %s' % (u', '.join(VAULT_MATTER_ACTIONS), action)) i += 2 elif myarg == u'name': body[u'name'] = sys.argv[i+1] @@ -7804,8 +7600,7 @@ def doUpdateVaultMatter(action=None): remove_collaborators.extend(validateCollaborators(sys.argv[i+1], cd)) i += 2 else: - print u'ERROR: %s is not a valid argument for "gam update matter"' % sys.argv[i] - sys.exit(3) + systemErrorExit(3, '%s is not a valid argument for "gam update matter"' % sys.argv[i]) if action == u'delete': action_kwargs = {} if body: @@ -7866,8 +7661,7 @@ def getGroupAttrValue(myarg, value, gs_object, gs_body, function): else: value = int(value) except ValueError: - print u'ERROR: %s must be a number ending with M (megabytes), K (kilobytes) or nothing (bytes); got %s' % value - sys.exit(2) + systemErrorExit(2, '%s must be a number ending with M (megabytes), K (kilobytes) or nothing (bytes); got %s' % value) elif params[u'type'] == u'string': if attrib == u'description': value = value.replace(u'\\n', u'\n') @@ -7879,8 +7673,7 @@ def getGroupAttrValue(myarg, value, gs_object, gs_body, function): value = u'false' gs_body[attrib] = value return - print u'ERROR: %s is not a valid argument for "gam %s group"' % (myarg, function) - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam %s group"' % (myarg, function)) def doCreateGroup(): cd = buildGAPIObject(u'directory') @@ -7936,8 +7729,7 @@ def doCreateAlias(): body[u'alias'] = u'%s@%s' % (body[u'alias'], GC_Values[GC_DOMAIN]) target_type = sys.argv[4].lower() if target_type not in [u'user', u'group', u'target']: - print u'ERROR: type of target must be user or group; got %s' % target_type - sys.exit(2) + systemErrorExit(2, 'type of target must be user or group; got %s' % target_type) targetKey = sys.argv[5] if targetKey.find(u'@') == -1: targetKey = u'%s@%s' % (targetKey, GC_Values[GC_DOMAIN]) @@ -7974,8 +7766,7 @@ def doCreateOrg(): body[u'blockInheritance'] = False i += 1 else: - print u'ERROR: %s is not a valid argument for "gam create org"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam create org"' % sys.argv[i]) callGAPI(cd.orgunits(), u'insert', customerId=GC_Values[GC_CUSTOMER_ID], body=body) def _getBuildingAttributes(args, body={}): @@ -8005,8 +7796,7 @@ def _getBuildingAttributes(args, body={}): body[u'floorNames'] = args[i+1].split(u',') i += 2 else: - print u'ERROR: %s is not a valid argument for "gam create|update building"' % myarg - sys.exit(3) + systemErrorExit(3, '%s is not a valid argument for "gam create|update building"' % myarg) return body def doCreateBuilding(): @@ -8064,8 +7854,7 @@ def _getBuildingByNameOrId(cd, which_building): print u'Please specify building name by exact case or by id.' # No matches else: - print u'ERROR: No such building %s' % which_building - sys.exit(3) + systemErrorExit(3, 'No such building %s' % which_building) def _getBuildingNameById(cd, buildingId): if GM_Globals[GM_MAP_BUILDING_ID_TO_NAME] is None: @@ -8108,8 +7897,7 @@ def _getFeatureAttributes(args, body={}): body[u'name'] = args[i+1] i += 2 else: - print u'ERROR: %s is not a valid argument for "gam create|update feature"' - sys.exit(3) + systemErrorExit(3, '%s is not a valid argument for "gam create|update feature"') return body def doCreateFeature(): @@ -8178,8 +7966,7 @@ def _getResourceCalendarAttributes(cd, args, body={}): body[u'userVisibleDescription'] = args[i+1] i += 2 else: - print u'ERROR: %s is not a valid argument for "gam create|update resource"' % args[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam create|update resource"' % args[i]) return body def doCreateResourceCalendar(): @@ -8411,8 +8198,7 @@ def doUpdateGroup(): fields.append(u'status') i += 1 else: - print u'ERROR: %s is not a valid argument for "gam update group clear"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam update group clear"' % sys.argv[i]) if roles: roles = u','.join(sorted(set(roles))) else: @@ -8463,8 +8249,7 @@ def doUpdateGroup(): use_cd_api = True cd_body[u'adminCreated'] = sys.argv[i+1].lower() if cd_body[u'adminCreated'] not in [u'true', u'false']: - print u'ERROR: Value for admincreated must be true or false; got %s' % cd_body[u'adminCreated'] - sys.exit(2) + systemErrorExit(2, 'Value for admincreated must be true or false; got %s' % cd_body[u'adminCreated']) i += 2 else: if not gs: @@ -8501,8 +8286,7 @@ def doUpdateAlias(): alias = sys.argv[3] target_type = sys.argv[4].lower() if target_type not in [u'user', u'group', u'target']: - print u'ERROR: target type must be one of user, group, target; got %s' % target_type - sys.exit(2) + systemErrorExit(2, 'target type must be one of user, group, target; got %s' % target_type) target_email = sys.argv[5] if alias.find(u'@') == -1: alias = u'%s@%s' % (alias, GC_Values[GC_DOMAIN]) @@ -8574,8 +8358,7 @@ def doUpdateCros(): action = u'deprovision' deprovisionReason = u'retiring_device' elif action not in [u'disable', u'reenable']: - print u'ERROR: expected action of deprovision_same_model_replace, deprovision_different_model_replace, deprovision_retiring_device, disable or reenable, got %s' % action - sys.exit(2) + systemErrorExit(2, 'expected action of deprovision_same_model_replace, deprovision_different_model_replace, deprovision_retiring_device, disable or reenable, got %s' % action) action_body = {u'action': action} if deprovisionReason: action_body[u'deprovisionReason'] = deprovisionReason @@ -8584,8 +8367,7 @@ def doUpdateCros(): ack_wipe = True i += 1 else: - print u'ERROR: %s is not a valid argument for "gam update cros"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam update cros"' % sys.argv[i]) i = 0 count = len(devices) if action_body: @@ -8624,12 +8406,10 @@ def doUpdateMobile(): elif body[u'action'].replace(u'_', u'') in [u'accountwipe', u'wipeaccount']: body[u'action'] = u'admin_account_wipe' if body[u'action'] not in [u'admin_remote_wipe', u'admin_account_wipe', u'approve', u'block', u'cancel_remote_wipe_then_activate', u'cancel_remote_wipe_then_block']: - print u'ERROR: action must be one of wipe, wipeaccount, approve, block, cancel_remote_wipe_then_activate, cancel_remote_wipe_then_block; got %s' % body[u'action'] - sys.exit(2) + systemErrorExit(2, 'action must be one of wipe, wipeaccount, approve, block, cancel_remote_wipe_then_activate, cancel_remote_wipe_then_block; got %s' % body[u'action']) i += 2 else: - print u'ERROR: %s is not a valid argument for "gam update mobile"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam update mobile"' % sys.argv[i]) if body: callGAPI(cd.mobiledevices(), u'action', resourceId=resourceId, body=body, customerId=GC_Values[GC_CUSTOMER_ID]) @@ -8686,8 +8466,7 @@ def doUpdateOrg(): body[u'blockInheritance'] = False i += 1 else: - print u'ERROR: %s is not a valid argument for "gam update org"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam update org"' % sys.argv[i]) if orgUnitPath[0] == u'/': # we don't want a / at the beginning for OU updates orgUnitPath = orgUnitPath[1:] callGAPI(cd.orgunits(), u'update', customerId=GC_Values[GC_CUSTOMER_ID], orgUnitPath=orgUnitPath, body=body) @@ -8713,8 +8492,7 @@ def doWhatIs(): try: group = callGAPI(cd.groups(), u'get', throw_reasons=[GAPI_NOT_FOUND, GAPI_BAD_REQUEST], groupKey=email, fields=u'email') except (GAPI_notFound, GAPI_badRequest): - sys.stderr.write(u'%s is not a group either!\n\nDoesn\'t seem to exist!\n\n' % email) - sys.exit(1) + systemErrorExit(1, u'%s is not a group either!\n\nDoesn\'t seem to exist!\n\n' % email) if group[u'email'].lower() == email.lower(): sys.stderr.write(u'%s is a group\n\n' % email) doGetGroupInfo(group_name=email) @@ -8727,8 +8505,7 @@ def convertSKU2ProductId(res, sku, customerId): for subscription in results[u'subscriptions']: if sku == subscription[u'skuId']: return subscription[u'subscriptionId'] - print u'ERROR: could not find subscription for customer %s and SKU %s' % (customerId, sku) - sys.exit(3) + systemErrorExit(3, 'could not find subscription for customer %s and SKU %s' % (customerId, sku)) def doDeleteResoldSubscription(): res = buildGAPIObject(u'reseller') @@ -8798,11 +8575,9 @@ def doUpdateResoldSubscription(): kwargs[u'body'][u'dealCode'] = sys.argv[i+1] i += 2 else: - print u'ERROR: %s is not a valid argument to "gam update resoldsubscription plan"' % planarg - sys.exit(3) + systemErrorExit(3, '%s is not a valid argument to "gam update resoldsubscription plan"' % planarg) else: - print u'ERROR: %s is not a valid argument to "gam update resoldsubscription"' % myarg - sys.exit(3) + systemErrorExit(3, '%s is not a valid argument to "gam update resoldsubscription"' % myarg) result = callGAPI(res.subscriptions(), function, customerId=customerId, subscriptionId=subscriptionId, **kwargs) print u'Updated %s SKU %s subscription:' % (customerId, sku) if result: @@ -8819,8 +8594,7 @@ def doGetResoldSubscriptions(): customerAuthToken = sys.argv[i+1] i += 2 else: - print u'ERROR: %s is not a valid argument for "gam info resoldsubscriptions"' % myarg - sys.exit(3) + systemErrorExit(3, '%s is not a valid argument for "gam info resoldsubscriptions"' % myarg) result = callGAPI(res.subscriptions(), u'list', customerId=customerId, customerAuthToken=customerAuthToken) print_json(None, result) @@ -8848,8 +8622,7 @@ def _getResoldSubscriptionAttr(arg, customerId): elif myarg in [u'customerauthtoken', u'transfertoken']: customerAuthToken = arg[i+1] else: - print u'ERROR: %s is not a valid argument for "gam create resoldsubscription"' % myarg - sys.exit(3) + systemErrorExit(3, '%s is not a valid argument for "gam create resoldsubscription"' % myarg) i += 2 return customerAuthToken, body @@ -8875,8 +8648,7 @@ def _getResoldCustomerAttr(arg): elif myarg in [u'customerauthtoken', u'transfertoken']: customerAuthToken = arg[i+1] else: - print u'ERROR: %s is not a valid argument for "gam %s resoldcustomer"' % (myarg, sys.argv[1]) - sys.exit(3) + systemErrorExit(3, '%s is not a valid argument for "gam %s resoldcustomer"' % (myarg, sys.argv[1])) i += 2 return customerAuthToken, body @@ -8950,8 +8722,7 @@ def doGetUserInfo(user_email=None): elif myarg in [u'nousers', u'groups']: i += 1 else: - print u'ERROR: %s is not a valid argument for "gam info user"' % myarg - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam info user"' % myarg) user = callGAPI(cd.users(), u'get', userKey=user_email, projection=projection, customFieldMask=customFieldMask, viewType=viewType) print u'User: %s' % user[u'primaryEmail'] if u'name' in user and u'givenName' in user[u'name']: @@ -9182,8 +8953,7 @@ def doGetGroupInfo(group_name=None): if myarg == u'schemas': i += 1 else: - print u'ERROR: %s is not a valid argument for "gam info group"' % myarg - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam info group"' % myarg) if group_name[:4].lower() == u'uid:': group_name = group_name[4:] elif group_name.find(u'@') == -1: @@ -9245,8 +9015,7 @@ def doGetAliasInfo(alias_email=None): print u' Alias Email: %s' % alias_email try: if result[u'primaryEmail'].lower() == alias_email.lower(): - print u'Error: %s is a primary user email address, not an alias.' % alias_email - sys.exit(3) + systemErrorExit(3, '%s is a primary user email address, not an alias.' % alias_email) print u' User Email: %s' % result[u'primaryEmail'] except KeyError: print u' Group Email: %s' % result[u'email'] @@ -9352,8 +9121,7 @@ def doGetCrosInfo(): projection = u'FULL' noLists = False else: - print u'ERROR: %s is not a valid argument for "gam info cros fields"' % field - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam info cros fields"' % field) i += 2 elif myarg == u'downloadfile': downloadfile = sys.argv[i+1] @@ -9366,8 +9134,7 @@ def doGetCrosInfo(): os.makedirs(targetFolder) i += 2 else: - print u'ERROR: %s is not a valid argument for "gam info cros"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam info cros"' % sys.argv[i]) if fieldsList: fields = u','.join(set(fieldsList)).replace(u'.', u'/') else: @@ -9487,11 +9254,9 @@ def doUpdateNotification(): ids.append(sys.argv[i+1]) i += 2 else: - print u'ERROR: %s is not a valid argument for "gam update notification"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam update notification"' % sys.argv[i]) if isUnread is None: - print u'ERROR: notifications need to be marked as read or unread.' - sys.exit(2) + systemErrorExit(2, 'notifications need to be marked as read or unread.') if get_all: notifications = callGAPIpages(cd.notifications(), u'list', u'items', customer=GC_Values[GC_CUSTOMER_ID], fields=u'items(notificationId,isUnread),nextPageToken') for noti in notifications: @@ -9520,8 +9285,7 @@ def doDeleteNotification(): ids.append(sys.argv[i+1]) i += 2 else: - print u'ERROR: %s is not a valid argument for "gam delete notification", expected id' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam delete notification", expected id' % sys.argv[i]) if get_all: notifications = callGAPIpages(cd.notifications(), u'list', u'items', customer=GC_Values[GC_CUSTOMER_ID], fields=u'items(notificationId),nextPageToken') for noti in notifications: @@ -9645,8 +9409,7 @@ def doGetNotifications(): if myarg == u'unreadonly': unread_only = True else: - print u'ERROR: %s is not a valid argument for "gam info notification", expected unreadonly' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam info notification", expected unreadonly' % sys.argv[i]) i += 1 notifications = callGAPIpages(cd.notifications(), u'list', u'items', customer=GC_Values[GC_CUSTOMER_ID]) for notification in notifications: @@ -9696,8 +9459,7 @@ def doGetOrgInfo(name=None, return_attrib=None): show_children = True i += 1 else: - print u'ERROR: %s is not a valid argument for "gam info org"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam info org"' % sys.argv[i]) if name == u'/': orgs = callGAPI(cd.orgunits(), u'list', customerId=GC_Values[GC_CUSTOMER_ID], type=u'children', @@ -9820,11 +9582,9 @@ def doDelTokens(users): clientId = commonClientIds(sys.argv[i+1]) i += 2 else: - print u'ERROR: %s is not a valid argument to "gam delete token"' % sys.argv[i] - sys.exit(3) + systemErrorExit(3, '%s is not a valid argument to "gam delete token"' % sys.argv[i]) if not clientId: - print u'ERROR: you must specify a clientid for "gam delete token"' - sys.exit(3) + systemErrorExit(3, 'you must specify a clientid for "gam delete token"') for user in users: try: callGAPI(cd.tokens(), u'get', throw_reasons=[GAPI_NOT_FOUND, GAPI_RESOURCE_NOT_FOUND], userKey=user, clientId=clientId) @@ -9864,8 +9624,7 @@ def printShowTokens(i, entityType, users, csvFormat): users = getUsersToModify(entity_type=entityType, entity=sys.argv[i+1], silent=False) i += 2 else: - print u'ERROR: %s is not a valid argument for "gam %s tokens"' % (myarg, [u'show', u'print'][csvFormat]) - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam %s tokens"' % (myarg, [u'show', u'print'][csvFormat])) if not entityType: users = getUsersToModify(entity_type=u'all', entity=u'users', silent=False) fields = u','.join([u'clientId', u'displayText', u'anonymous', u'nativeApp', u'userKey', u'scopes']) @@ -9959,8 +9718,7 @@ def doUndeleteUser(): orgUnit = sys.argv[i+1] i += 2 else: - print u'ERROR: %s is not a valid argument for "gam undelete user"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam undelete user"' % sys.argv[i]) if user[:4].lower() == u'uid:': user_uid = user[4:] elif user.find(u'@') == -1: @@ -9974,8 +9732,7 @@ def doUndeleteUser(): if str(deleted_user[u'primaryEmail']).lower() == user: matching_users.append(deleted_user) if len(matching_users) < 1: - print u'ERROR: could not find deleted user with that address.' - sys.exit(3) + systemErrorExit(3, 'could not find deleted user with that address.') elif len(matching_users) > 1: print u'ERROR: more than one matching deleted %s user. Please select the correct one to undelete and specify with "gam undelete user uid:"' % user print u'' @@ -10026,8 +9783,7 @@ def doDeleteAlias(alias_email=None): except (GAPI_invalid, GAPI_badRequest): pass except GAPI_notFound: - print u'Error: The alias %s does not exist' % alias_email - sys.exit(4) + systemErrorExit(4, 'The alias %s does not exist' % alias_email) if not is_user or (not is_user and not is_group): callGAPI(cd.groups().aliases(), u'delete', groupKey=alias_email, alias=alias_email) @@ -10300,8 +10056,7 @@ def doPrintUsers(): elif myarg == u'orderby': orderBy = sys.argv[i+1] if orderBy.lower() not in [u'email', u'familyname', u'givenname', u'firstname', u'lastname']: - print u'ERROR: orderby must be one of email, familyName, givenName; got %s' % orderBy - sys.exit(2) + systemErrorExit(2, 'orderby must be one of email, familyName, givenName; got %s' % orderBy) elif orderBy.lower() in [u'familyname', u'lastname']: orderBy = u'familyName' elif orderBy.lower() in [u'givenname', u'firstname']: @@ -10333,8 +10088,7 @@ def doPrintUsers(): if field in USER_ARGUMENT_TO_PROPERTY_MAP: addFieldToCSVfile(field, USER_ARGUMENT_TO_PROPERTY_MAP, fieldsList, fieldsTitles, titles) else: - print u'ERROR: %s is not a valid argument for "gam print users fields"' % field - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam print users fields"' % field) i += 2 elif myarg == u'groups': getGroupFeed = True @@ -10346,8 +10100,7 @@ def doPrintUsers(): email_parts = True i += 1 else: - print u'ERROR: %s is not a valid argument for "gam print users"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam print users"' % sys.argv[i]) if fieldsList: fields = u'nextPageToken,users(%s)' % u','.join(set(fieldsList)).replace(u'.', u'/') else: @@ -10494,8 +10247,7 @@ def doPrintGroups(): addFieldToCSVfile(field, {field: [GROUP_ATTRIBUTES_ARGUMENT_TO_PROPERTY_MAP[field]]}, gsfieldsList, fieldsTitles, titles) gsfieldsList.extend([GROUP_ATTRIBUTES_ARGUMENT_TO_PROPERTY_MAP[field],]) else: - print u'ERROR: %s is not a valid argument for "gam print groups fields"' % field - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam print groups fields"' % field) i += 2 elif myarg in [u'members', u'memberscount']: roles.append(ROLE_MEMBER) @@ -10516,8 +10268,7 @@ def doPrintGroups(): managersCountOnly = True i += 1 else: - print u'ERROR: %s is not a valid argument for "gam print groups"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam print groups"' % sys.argv[i]) cdfields = u','.join(set(cdfieldsList)) if len(gsfieldsList) > 0: getSettings = True @@ -10672,8 +10423,7 @@ def doPrintOrgs(): fields += sys.argv[i+1].split(u',') i += 2 else: - print u'ERROR: %s is not a valid argument for "gam print orgs"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam print orgs"' % sys.argv[i]) sys.stderr.write(u"Retrieving All Organizational Units for your account (may take some time on large domain)...\n") if fields: get_fields = u','.join(fields) @@ -10751,8 +10501,7 @@ def doPrintAliases(): doUsers = True i += 2 else: - print u'ERROR: %s is not a valid argument for "gam print aliases"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam print aliases"' % sys.argv[i]) if doUsers: sys.stderr.write(u"Retrieving All User Aliases for %s organization (may take some time on large domain)...\n" % GC_Values[GC_DOMAIN]) page_message = u'Got %%num_items%% users %%first_item%% - %%last_item%%\n' @@ -10817,8 +10566,7 @@ def doPrintGroupMembers(): groups_to_get = [{u'email': group_email}] i += 2 else: - print u'ERROR: %s is not a valid argument for "gam print group-members"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam print group-members"' % sys.argv[i]) if not groups_to_get: groups_to_get = callGAPIpages(cd.groups(), u'list', u'groups', message_attribute=u'email', customer=customer, domain=usedomain, userKey=usemember, fields=u'nextPageToken,groups(email)') @@ -10887,8 +10635,7 @@ def doPrintVaultMatters(): view = PROJECTION_CHOICES_MAP[myarg] i += 1 else: - print u'ERROR: %s is not a valid argument to "gam print matters"' % myarg - sys.exit(3) + systemErrorExit(3, '%s is not a valid argument to "gam print matters"' % myarg) sys.stderr.write(u'Retrieving all Vault Matters...\n') page_message = u' got %%num_items%% matters...\n' matters = callGAPIpages(v.matters(), u'list', u'matters', page_message=page_message, view=view) @@ -10915,8 +10662,7 @@ def doPrintVaultHolds(): matters = sys.argv[i+1].split(u',') i += 2 else: - print u'ERROR: %s is not a valid a valid argument to "gam print holds"' % myarg - sys.exit(3) + systemErrorExit(3, '%s is not a valid a valid argument to "gam print holds"' % myarg) if not matters: matters_results = callGAPIpages(v.matters(), u'list', u'matters', view=u'BASIC', fields=u'matters(matterId,state),nextPageToken') for matter in matters_results: @@ -10969,8 +10715,7 @@ def doPrintMobileDevices(): orderBy = sys.argv[i+1].lower() allowed_values = [u'deviceid', u'email', u'lastsync', u'model', u'name', u'os', u'status', u'type'] if orderBy.lower() not in allowed_values: - print u'ERROR: orderBy must be one of %s; got %s' % (u', '.join(allowed_values), orderBy) - sys.exit(2) + systemErrorExit(2, 'orderBy must be one of %s; got %s' % (u', '.join(allowed_values), orderBy)) elif orderBy == u'lastsync': orderBy = u'lastSync' elif orderBy == u'deviceid': @@ -10983,8 +10728,7 @@ def doPrintMobileDevices(): projection = PROJECTION_CHOICES_MAP[myarg] i += 1 else: - print u'ERROR: %s is not a valid argument for "gam print mobile"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam print mobile"' % sys.argv[i]) sys.stderr.write(u'Retrieving All Mobile Devices for organization (may take some time for large accounts)...\n') page_message = u'Got %%num_items%% mobile devices...\n' all_mobile = callGAPIpages(cd.mobiledevices(), u'list', u'mobiledevices', page_message=page_message, @@ -11082,8 +10826,7 @@ def doPrintCrosActivity(): delimiter = sys.argv[i+1] i += 2 else: - print u'ERROR: %s is not a valid argument for "gam print crosactivity"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam print crosactivity"' % sys.argv[i]) if not selectActiveTimeRanges and not selectDeviceFiles and not selectRecentUsers: selectActiveTimeRanges = selectRecentUsers = True if selectRecentUsers: @@ -11204,8 +10947,7 @@ def doPrintCrosDevices(): orderBy = sys.argv[i+1].lower().replace(u'_', u'') allowed_values = [u'location', u'user', u'lastsync', u'notes', u'serialnumber', u'status', u'supportenddate'] if orderBy not in allowed_values: - print u'ERROR: orderBy must be one of %s; got %s' % (u', '.join(allowed_values), orderBy) - sys.exit(2) + systemErrorExit(2, 'orderBy must be one of %s; got %s' % (u', '.join(allowed_values), orderBy)) elif orderBy == u'location': orderBy = u'annotatedLocation' elif orderBy == u'user': @@ -11258,12 +11000,10 @@ def doPrintCrosDevices(): selectRecentUsers = True noLists = False else: - print u'ERROR: %s is not a valid argument for "gam print cros fields"' % field - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam print cros fields"' % field) i += 2 else: - print u'ERROR: %s is not a valid argument for "gam print cros"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam print cros"' % sys.argv[i]) if fieldsList: fields = u'nextPageToken,chromeosdevices({0})'.format(u','.join(set(fieldsList))).replace(u'.', u'/') else: @@ -11345,8 +11085,7 @@ def doPrintLicenses(returnFields=None, skus=None): skus = sys.argv[i+1].split(u',') i += 2 else: - print u'ERROR: %s is not a valid argument for "gam print licenses"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam print licenses"' % sys.argv[i]) fields = u'nextPageToken,items(productId,skuId,userId)' else: fields = u'nextPageToken,items({0})'.format(returnFields) @@ -11445,8 +11184,7 @@ def doPrintFeatures(): fieldsList.append(possible_fields[u'feature'+myarg]) i += 1 else: - print u'ERROR: %s is not a valid argument to "gam print features"' % sys.argv[i] - sys.exit(3) + systemErrorExit(3, '%s is not a valid argument to "gam print features"' % sys.argv[i]) if fields: fields = fields % u','.join(fieldsList) features = callGAPIpages(cd.resources().features(), u'list', u'features', @@ -11493,8 +11231,7 @@ def doPrintBuildings(): fieldsList.append(possible_fields[u'building'+myarg]) i += 1 else: - print u'ERROR: %s is not a valid argument to "gam print buildings"' % sys.argv[i] - sys.exit(3) + systemErrorExit(3, '%s is not a valid argument to "gam print buildings"' % sys.argv[i]) if fields: fields = fields % u','.join(fieldsList) buildings = callGAPIpages(cd.resources().buildings(), u'list', u'buildings', @@ -11539,8 +11276,7 @@ def doPrintResourceCalendars(): addFieldToCSVfile(myarg, RESCAL_ARGUMENT_TO_PROPERTY_MAP, fieldsList, fieldsTitles, titles) i += 1 else: - print u'ERROR: %s is not a valid argument for "gam print resources"' % sys.argv[i] - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam print resources"' % sys.argv[i]) if not fieldsList: for field in RESCAL_DFLTFIELDS: addFieldToCSVfile(field, RESCAL_ARGUMENT_TO_PROPERTY_MAP, fieldsList, fieldsTitles, titles) @@ -11719,14 +11455,12 @@ def getUsersToModify(entity_type=None, entity=None, silent=False, member_type=No if not silent: sys.stderr.write(u"done getting %s CrOS devices.\r\n" % len(users)) else: - print u'ERROR: %s is not a valid argument for "gam all"' % entity - sys.exit(3) + systemErrorExit(3, '%s is not a valid argument for "gam all"' % entity) elif entity_type == u'cros': users = entity.replace(u',', u' ').split() entity = u'cros' else: - print u'ERROR: %s is not a valid argument for "gam"' % entity_type - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam"' % entity_type) full_users = list() if entity != u'cros' and not got_uids: for user in users: @@ -11822,9 +11556,7 @@ gam create project client_id = re.sub(r'\.apps\.googleusercontent\.com$', u'', client_id) client_secret = cs_json[u'installed'][u'client_secret'] except (ValueError, IndexError, KeyError): - message = (u'ERROR: the format of your client secrets file:\n\n%s\n\n is ' - 'incorrect. Please recreate the file.') - systemErrorExit(3, message) + systemErrorExit(3, u'the format of your client secrets file:\n\n%s\n\n is incorrect. Please recreate the file.') return (client_id, client_secret) @@ -12196,8 +11928,7 @@ def ProcessGAMCommand(args): f = openFile(filename, mode=u'rbU') csvFile = UnicodeDictReader(f, encoding=encoding) if (i == len(sys.argv)) or (sys.argv[i].lower() != u'gam') or (i+1 == len(sys.argv)): - print u'ERROR: "gam csv " must be followed by a full GAM command...' - sys.exit(3) + systemErrorExit(3, '"gam csv " must be followed by a full GAM command...') i += 1 GAM_argv, subFields = getSubFields(i, csvFile.fieldnames) items = [] @@ -12256,8 +11987,7 @@ def ProcessGAMCommand(args): elif argument in [u'feature']: doCreateFeature() else: - print u'ERROR: %s is not a valid argument for "gam create"' % argument - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam create"' % argument) sys.exit(0) elif command == u'update': argument = sys.argv[2].lower() @@ -12308,8 +12038,7 @@ def ProcessGAMCommand(args): elif argument in [u'feature']: doUpdateFeature() else: - print u'ERROR: %s is not a valid argument for "gam update"' % argument - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam update"' % argument) sys.exit(0) elif command == u'info': argument = sys.argv[2].lower() @@ -12358,16 +12087,14 @@ def ProcessGAMCommand(args): elif argument in [u'building']: doGetBuildingInfo() else: - print u'ERROR: %s is not a valid argument for "gam info"' % argument - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam info"' % argument) sys.exit(0) elif command == u'cancel': argument = sys.argv[2].lower() if argument in [u'guardianinvitation', u'guardianinvitations']: doCancelGuardianInvitation() else: - print u'ERROR: %s is not a valid argument for "gam cancel"' % argument - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam cancel"' % argument) sys.exit(0) elif command == u'delete': argument = sys.argv[2].lower() @@ -12416,8 +12143,7 @@ def ProcessGAMCommand(args): elif argument in [u'feature']: doDeleteFeature() else: - print u'ERROR: %s is not a valid argument for "gam delete"' % argument - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam delete"' % argument) sys.exit(0) elif command == u'undelete': argument = sys.argv[2].lower() @@ -12426,8 +12152,7 @@ def ProcessGAMCommand(args): elif argument in [u'matter', u'vaultmatter']: doUpdateVaultMatter(action=command) else: - print u'ERROR: %s is not a valid argument for "gam undelete"' % argument - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam undelete"' % argument) sys.exit(0) elif command in [u'close', u'reopen']: # close and reopen will have to be split apart if either takes a new argument @@ -12435,8 +12160,7 @@ def ProcessGAMCommand(args): if argument in [u'matter', u'vaultmatter']: doUpdateVaultMatter(action=command) else: - print u'ERROR: %s is not a valid argument for "gam %s"' % (argument, command) - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam %s"' % (argument, command)) sys.exit(0) elif command == u'print': argument = sys.argv[2].lower().replace(u'-', u'') @@ -12495,8 +12219,7 @@ def ProcessGAMCommand(args): elif argument in [u'feature', u'features']: doPrintFeatures() else: - print u'ERROR: %s is not a valid argument for "gam print"' % argument - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam print"' % argument) sys.exit(0) elif command == u'show': argument = sys.argv[2].lower() @@ -12505,8 +12228,7 @@ def ProcessGAMCommand(args): elif argument in [u'guardian', u'guardians']: doPrintShowGuardians(False) else: - print u'ERROR: %s is not a valid argument for "gam show"' % argument - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam show"' % argument) sys.exit(0) elif command in [u'oauth', u'oauth2']: argument = sys.argv[2].lower() @@ -12521,8 +12243,7 @@ def ProcessGAMCommand(args): elif argument in [u'delete', u'revoke']: doDeleteOAuth() else: - print u'ERROR: %s is not a valid argument for "gam oauth"' % argument - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam oauth"' % argument) sys.exit(0) elif command == u'calendar': argument = sys.argv[3].lower() @@ -12541,8 +12262,7 @@ def ProcessGAMCommand(args): elif argument == u'deleteevent': doCalendarDeleteEvent() else: - print u'ERROR: %s is not a valid argument for "gam calendar"' % argument - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam calendar"' % argument) sys.exit(0) elif command == u'printer': if sys.argv[2].lower() == u'register': @@ -12556,8 +12276,7 @@ def ProcessGAMCommand(args): elif argument in [u'del', u'delete', u'remove']: doPrinterDelACL() else: - print u'ERROR: %s is not a valid argument for "gam printer..."' % argument - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam printer..."' % argument) sys.exit(0) elif command == u'printjob': argument = sys.argv[3].lower() @@ -12572,8 +12291,7 @@ def ProcessGAMCommand(args): elif argument == u'resubmit': doPrintJobResubmit() else: - print u'ERROR: %s is not a valid argument for "gam printjob"' % argument - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam printjob"' % argument) sys.exit(0) elif command == u'report': showReport() @@ -12590,8 +12308,7 @@ def ProcessGAMCommand(args): elif argument == u'sync': doSyncCourseParticipants() else: - print u'ERROR: %s is not a valid argument for "gam course"' % argument - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam course"' % argument) sys.exit(0) users = getUsersToModify() command = sys.argv[3].lower() @@ -12608,8 +12325,7 @@ def ProcessGAMCommand(args): elif transferWhat == u'seccals': transferSecCals(users) else: - print u'ERROR: %s is not a valid argument for "gam transfer"' % transferWhat - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam transfer"' % transferWhat) elif command == u'show': showWhat = sys.argv[4].lower() if showWhat in [u'labels', u'label']: @@ -12671,8 +12387,7 @@ def ProcessGAMCommand(args): elif showWhat in [u'teamdriveinfo']: doGetTeamDriveInfo(users) else: - print u'ERROR: %s is not a valid argument for "gam show"' % showWhat - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam show"' % showWhat) elif command == u'print': printWhat = sys.argv[4].lower() if printWhat == u'calendars': @@ -12700,8 +12415,7 @@ def ProcessGAMCommand(args): elif printWhat in [u'teamdrive', u'teamdrives']: printShowTeamDrives(users, True) else: - print u'ERROR: %s is not a valid argument for "gam print"' % printWhat - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam print"' % printWhat) elif command == u'modify': modifyWhat = sys.argv[4].lower() if modifyWhat in [u'message', u'messages']: @@ -12709,8 +12423,7 @@ def ProcessGAMCommand(args): elif modifyWhat in [u'thread', u'threads']: doProcessMessagesOrThreads(users, u'modify', u'threads') else: - print u'ERROR: %s is not a valid argument for "gam modify"' % modifyWhat - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam modify"' % modifyWhat) elif command == u'trash': trashWhat = sys.argv[4].lower() if trashWhat in [u'message', u'messages']: @@ -12718,8 +12431,7 @@ def ProcessGAMCommand(args): elif trashWhat in [u'thread', u'threads']: doProcessMessagesOrThreads(users, u'trash', u'threads') else: - print u'ERROR: %s is not a valid argument for "gam trash"' % trashWhat - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam trash"' % trashWhat) elif command == u'untrash': untrashWhat = sys.argv[4].lower() if untrashWhat in [u'message', u'messages']: @@ -12727,8 +12439,7 @@ def ProcessGAMCommand(args): elif untrashWhat in [u'thread', u'threads']: doProcessMessagesOrThreads(users, u'untrash', u'threads') else: - print u'ERROR: %s is not a valid argument for "gam untrash"' % untrashWhat - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam untrash"' % untrashWhat) elif command in [u'delete', u'del']: delWhat = sys.argv[4].lower() if delWhat == u'delegate': @@ -12772,16 +12483,14 @@ def ProcessGAMCommand(args): elif delWhat == u'teamdrive': doDeleteTeamDrive(users) else: - print u'ERROR: %s is not a valid argument for "gam delete"' % delWhat - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam delete"' % delWhat) elif command in [u'add', u'create']: addWhat = sys.argv[4].lower() if addWhat == u'calendar': if command == u'add': addCalendar(users) else: - print u'ERROR: %s is not implemented for "gam %s"' % (addWhat, command) - sys.exit(2) + systemErrorExit(2, '%s is not implemented for "gam %s"' % (addWhat, command)) elif addWhat == u'drivefile': createDriveFile(users) elif addWhat in [u'license', u'licence']: @@ -12803,8 +12512,7 @@ def ProcessGAMCommand(args): elif addWhat == u'teamdrive': doCreateTeamDrive(users) else: - print u'ERROR: %s is not a valid argument for "gam %s"' % (addWhat, command) - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam %s"' % (addWhat, command)) elif command == u'update': updateWhat = sys.argv[4].lower() if updateWhat == u'calendar': @@ -12834,8 +12542,7 @@ def ProcessGAMCommand(args): elif updateWhat == u'teamdrive': doUpdateTeamDrive(users) else: - print u'ERROR: %s is not a valid argument for "gam update"' % updateWhat - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam update"' % updateWhat) elif command in [u'deprov', u'deprovision']: doDeprovUser(users) elif command == u'get': @@ -12845,15 +12552,13 @@ def ProcessGAMCommand(args): elif getWhat == u'drivefile': downloadDriveFile(users) else: - print u'ERROR: %s is not a valid argument for "gam get"' % getWhat - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam get"' % getWhat) elif command == u'empty': emptyWhat = sys.argv[4].lower() if emptyWhat == u'drivetrash': doEmptyDriveTrash(users) else: - print u'ERROR: %s is not a valid argument for "gam empty"' % emptyWhat - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam empty"' % emptyWhat) elif command == u'info': infoWhat = sys.argv[4].lower() if infoWhat == u'calendar': @@ -12865,15 +12570,13 @@ def ProcessGAMCommand(args): elif infoWhat == u'sendas': infoSendAs(users) else: - print u'ERROR: %s is not a valid argument for "gam info"' % infoWhat - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam info"' % infoWhat) elif command == u'check': checkWhat = sys.argv[4].replace(u'_', '').lower() if checkWhat == u'serviceaccount': doCheckServiceAccount(users) else: - print u'ERROR: %s is not a valid argument for "gam check"' % checkWhat - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam check"' % checkWhat) elif command == u'profile': doProfile(users) elif command == u'imap': @@ -12903,11 +12606,9 @@ def ProcessGAMCommand(args): if watchWhat == u'gmail': watchGmail(users) else: - print u'ERROR: %s is not a valid argument for "gam watch"' % watchWhat - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam watch"' % watchWhat) else: - print u'ERROR: %s is not a valid argument for "gam"' % command - sys.exit(2) + systemErrorExit(2, '%s is not a valid argument for "gam"' % command) except IndexError: showUsage() sys.exit(2) @@ -12953,6 +12654,5 @@ if __name__ == "__main__": freeze_support() win32_unicode_argv() # cleanup sys.argv on Windows if sys.version_info[:2] != (2, 7): - print u'ERROR: GAM requires Python 2.7. You are running %s.%s.%s. Please upgrade your Python version or use one of the binary GAM downloads.' % sys.version_info[:3] - sys.exit(5) + systemErrorExit(5, 'GAM requires Python 2.7. You are running %s.%s.%s. Please upgrade your Python version or use one of the binary GAM downloads.' % sys.version_info[:3]) sys.exit(ProcessGAMCommand(sys.argv))