Error message cleanup; minor coding cleanup (#689)

* Error message cleanup; minor coding cleanup

* A couple more error cleanups

* Trying to replace ` with \` in query, need two \\ to make one \
This commit is contained in:
Ross Scroggs
2018-02-25 12:24:58 -08:00
committed by Jay Lee
parent 8885bdd5f0
commit b6f7ff7038
2 changed files with 36 additions and 41 deletions

View File

@@ -131,9 +131,9 @@ Named items
<CrOSItem> ::= <CrOSID>|(query:<QueryCrOS>)|(query:orgunitpath:<OrgUnitPath>) <CrOSItem> ::= <CrOSID>|(query:<QueryCrOS>)|(query:orgunitpath:<OrgUnitPath>)
<CustomerID> ::= <String> <CustomerID> ::= <String>
<DomainAlias> ::= <String> <DomainAlias> ::= <String>
<DriveFileACLRole> :: =commenter|editor|organizer|owner|reader|writer <DriveFileACLRole> ::= commenter|editor|organizer|owner|reader|writer
<DriveFileID> ::= <String> <DriveFileID> ::= <String>
<DriveFileURL> :: = https://docs.google.com/a/<DomainName>/document/d/<DriveFileID>/<String> <DriveFileURL> ::= https://docs.google.com/a/<DomainName>/document/d/<DriveFileID>/<String>
<DriveFileItem> ::= <DriveFileID>|<DriveFileURL> <DriveFileItem> ::= <DriveFileID>|<DriveFileURL>
<DriveFileName> ::= <String> <DriveFileName> ::= <String>
<DriveFolderID> ::= <String> <DriveFolderID> ::= <String>
@@ -180,12 +180,12 @@ Named items
<QueryCalendar> ::= <String> <QueryCalendar> ::= <String>
<QueryContact> ::= <String> See: https://developers.google.com/google-apps/contacts/v3/reference#contacts-query-parameters-reference <QueryContact> ::= <String> See: https://developers.google.com/google-apps/contacts/v3/reference#contacts-query-parameters-reference
<QueryCrOS> ::= <String> See: https://support.google.com/chrome/a/answer/1698333?hl=en <QueryCrOS> ::= <String> See: https://support.google.com/chrome/a/answer/1698333?hl=en
<QueryDriveFile> :: = <String> See: https://developers.google.com/drive/v2/web/search-parameters <QueryDriveFile> ::= <String> See: https://developers.google.com/drive/v2/web/search-parameters
<QueryGmail> ::= <String> See: https://support.google.com/mail/answer/7190 <QueryGmail> ::= <String> See: https://support.google.com/mail/answer/7190
<QueryMobile> ::= <String> See: https://support.google.com/a/answer/1408863?hl=en#search <QueryMobile> ::= <String> See: https://support.google.com/a/answer/1408863?hl=en#search
<QueryPrinter> ::= <String> See: https://developers.google.com/cloud-print/docs/appInterfaces#search <QueryPrinter> ::= <String> See: https://developers.google.com/cloud-print/docs/appInterfaces#search
<QueryPrintJob> ::= <String> See: https://developers.google.com/cloud-print/docs/appInterfaces#parameters_3 <QueryPrintJob> ::= <String> See: https://developers.google.com/cloud-print/docs/appInterfaces#parameters_3
<QueryUser> :: = <String> See: https://developers.google.com/admin-sdk/directory/v1/guides/search-users <QueryUser> ::= <String> See: https://developers.google.com/admin-sdk/directory/v1/guides/search-users
<QueryVaultCorpus> ::= <String> See: https://developers.google.com/vault/reference/rest/v1/matters.holds#CorpusQuery <QueryVaultCorpus> ::= <String> See: https://developers.google.com/vault/reference/rest/v1/matters.holds#CorpusQuery
<RequestID> ::= <String> <RequestID> ::= <String>
<ResourceID> ::= <String> <ResourceID> ::= <String>

View File

@@ -242,6 +242,13 @@ def getEmailAddressDomain(emailAddress):
return GC_Values[GC_DOMAIN].lower() return GC_Values[GC_DOMAIN].lower()
return emailAddress[atLoc+1:].lower() return emailAddress[atLoc+1:].lower()
# Split email address unto user and domain
def splitEmailAddress(emailAddress):
atLoc = emailAddress.find(u'@')
if atLoc == -1:
return (emailAddress.lower(), GC_Values[GC_DOMAIN].lower())
return (emailAddress[:atLoc].lower(), emailAddress[atLoc+1:].lower())
# Normalize user/group email address/uid # Normalize user/group email address/uid
# uid:12345abc -> 12345abc # uid:12345abc -> 12345abc
# foo -> foo@domain # foo -> foo@domain
@@ -319,7 +326,7 @@ def readFile(filename, mode=u'rb', continueOnError=False, displayError=True, enc
return None return None
systemErrorExit(6, e) systemErrorExit(6, e)
except (LookupError, UnicodeDecodeError, UnicodeError) as e: except (LookupError, UnicodeDecodeError, UnicodeError) as e:
systemErrorExit(2, u'%s' % e) systemErrorExit(2, str(e))
# #
# Write a file # Write a file
# #
@@ -364,7 +371,7 @@ class UnicodeDictReader(object):
except (csv.Error, StopIteration): except (csv.Error, StopIteration):
self.fieldnames = [] self.fieldnames = []
except LookupError as e: except LookupError as e:
systemErrorExit(2, u'%s' % e) systemErrorExit(2, str(e))
self.numfields = len(self.fieldnames) self.numfields = len(self.fieldnames)
def __iter__(self): def __iter__(self):
@@ -1081,7 +1088,6 @@ def doCheckServiceAccount(users):
if all_scopes_pass: if all_scopes_pass:
print u'\nAll scopes passed!\nService account %s is fully authorized.' % service_account print u'\nAll scopes passed!\nService account %s is fully authorized.' % service_account
return return
else:
user_domain = user[user.find(u'@')+1:] user_domain = user[user.find(u'@')+1:]
scopes_failed = '''Some scopes failed! Please go to: scopes_failed = '''Some scopes failed! Please go to:
@@ -1094,7 +1100,7 @@ and grant Client name:
Access to scopes: Access to scopes:
%s\n''' % (user_domain, service_account, ',\n'.join(all_scopes)) %s\n''' % (user_domain, service_account, ',\n'.join(all_scopes))
systemErrorExit(int(not all_scopes_pass), scopes_failed) systemErrorExit(1, scopes_failed)
# Batch processing request_id fields # Batch processing request_id fields
RI_ENTITY = 0 RI_ENTITY = 0
@@ -2244,8 +2250,7 @@ def doDeleteGuardian():
else: else:
if _cancelGuardianInvitation(croom, studentId, guardianId): if _cancelGuardianInvitation(croom, studentId, guardianId):
return return
stderrErrorMsg(u'%s is not a guardian of %s and no invitation exists.' % (guardianId, studentId)) systemErrorExit(3, '%s is not a guardian of %s and no invitation exists.' % (guardianId, studentId))
sys.exit(3)
def doCreateCourse(): def doCreateCourse():
croom = buildGAPIObject(u'classroom') croom = buildGAPIObject(u'classroom')
@@ -3249,8 +3254,7 @@ def checkCloudPrintResult(result):
except ValueError: except ValueError:
systemErrorExit(3, 'unexpected response: %s' % result) systemErrorExit(3, 'unexpected response: %s' % result)
if not result[u'success']: if not result[u'success']:
systemErrorExit( systemErrorExit(result[u'errorCode'], '%s: %s' % (result[u'errorCode'], result[u'message']))
result[u'errorCode'], '%s: %s' % (result[u'errorCode'], result[u'message']))
def formatACLRule(rule): def formatACLRule(rule):
if rule[u'scope'][u'type'] != u'default': if rule[u'scope'][u'type'] != u'default':
@@ -3915,7 +3919,7 @@ def addDriveFileACL(users):
elif myarg == u'expires': elif myarg == u'expires':
body[u'expirationTime'] = getTimeOrDeltaFromNow(sys.argv[i+1]) body[u'expirationTime'] = getTimeOrDeltaFromNow(sys.argv[i+1])
i += 2 i += 2
elif myarg.replace(u'_', u'') == u'asadmin': elif myarg == u'asadmin':
useDomainAdminAccess = True useDomainAdminAccess = True
i += 1 i += 1
else: else:
@@ -5035,8 +5039,7 @@ def updateSmime(users):
if len(smimes) == 0: if len(smimes) == 0:
systemErrorExit(3, '%s has no S/MIME certificates for sendas address %s' % (user, sendAsEmail)) systemErrorExit(3, '%s has no S/MIME certificates for sendas address %s' % (user, sendAsEmail))
elif len(smimes) > 1: elif len(smimes) > 1:
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, u'\n '.join([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'] smimeId = smimes[0][u'id']
else: else:
smimeId = smimeIdBase smimeId = smimeIdBase
@@ -5068,12 +5071,11 @@ def deleteSmime(users):
if len(smimes) == 0: if len(smimes) == 0:
systemErrorExit(3, '%s has no S/MIME certificates for sendas address %s' % (user, sendAsEmail)) systemErrorExit(3, '%s has no S/MIME certificates for sendas address %s' % (user, sendAsEmail))
elif len(smimes) > 1: elif len(smimes) > 1:
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, u'\n '.join([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'] smimeId = smimes[0][u'id']
else: else:
smimeId = smimeIdBase smimeId = smimeIdBase
print u'Deleting smime id %s for user %s and sendas %s' % (smimeId, user, sendAsEmail)
callGAPI(gmail.users().settings().sendAs().smimeInfo(), u'delete', userId=u'me', sendAsEmail=sendAsEmail, id=smimeId) callGAPI(gmail.users().settings().sendAs().smimeInfo(), u'delete', userId=u'me', sendAsEmail=sendAsEmail, id=smimeId)
def printShowSmime(users, csvFormat): def printShowSmime(users, csvFormat):
@@ -7231,7 +7233,7 @@ def doUpdateTeamDrive(users):
else: else:
systemErrorExit(3, '%s is not a valid argument for "gam <users> update drivefile"') systemErrorExit(3, '%s is not a valid argument for "gam <users> update drivefile"')
if not body: if not body:
systemErrorExit(4, u'nothing to update. Need at least a name argument.\n%s' % body) systemErrorExit(4, 'nothing to update. Need at least a name argument.')
for user in users: for user in users:
user, drive = buildDrive3GAPIObject(user) user, drive = buildDrive3GAPIObject(user)
if not drive: if not drive:
@@ -7848,11 +7850,11 @@ def _getBuildingByNameOrId(cd, which_building):
return buildingId return buildingId
# Multiple name matches # Multiple name matches
if len(ci_matches) > 1: if len(ci_matches) > 1:
print u'ERROR: multiple buildings with same name:' message = u'Multiple buildings with same name:\n'
for building in ci_matches: for building in ci_matches:
print u' Name:%s id:%s' % (building[u'buildingName'], building[u'buildingId']) message += u' Name:%s id:%s\n' % (building[u'buildingName'], building[u'buildingId'])
print message += u'\nPlease specify building name by exact case or by id.'
print u'Please specify building name by exact case or by id.' systemErrorExit(3, message)
# No matches # No matches
else: else:
systemErrorExit(3, 'No such building %s' % which_building) systemErrorExit(3, 'No such building %s' % which_building)
@@ -9429,7 +9431,7 @@ def doGetNotifications():
def orgUnitPathQuery(path): def orgUnitPathQuery(path):
if path != u'/': if path != u'/':
return u"orgUnitPath='{0}'".format(path.replace(u"'", u"\'")) return u"orgUnitPath='{0}'".format(path.replace(u"'", u"\\'"))
return None return None
def getTopLevelOrgId(cd, orgUnitPath): def getTopLevelOrgId(cd, orgUnitPath):
@@ -10113,14 +10115,10 @@ def doPrintUsers():
showDeleted=deleted_only, orderBy=orderBy, sortOrder=sortOrder, viewType=viewType, showDeleted=deleted_only, orderBy=orderBy, sortOrder=sortOrder, viewType=viewType,
query=query, projection=projection, customFieldMask=customFieldMask, maxResults=GC_Values[GC_USER_MAX_RESULTS]) query=query, projection=projection, customFieldMask=customFieldMask, maxResults=GC_Values[GC_USER_MAX_RESULTS])
for user in all_users: for user in all_users:
if email_parts: if email_parts and (u'primaryEmail' in user):
try:
user_email = user[u'primaryEmail'] user_email = user[u'primaryEmail']
if user_email.find(u'@') != -1: if user_email.find(u'@') != -1:
user[u'primaryEmailLocal'] = user_email[:user_email.find(u'@')] user[u'primaryEmailLocal'], user[u'primaryEmailDomain'] = splitEmailAddress(user_email)
user[u'primaryEmailDomain'] = user_email[user_email.find(u'@')+1:]
except KeyError:
pass
addRowTitlesToCSVfile(flatten_json(user), csvRows, titles) addRowTitlesToCSVfile(flatten_json(user), csvRows, titles)
if sortHeaders: if sortHeaders:
sortCSVTitles([u'primaryEmail',], titles) sortCSVTitles([u'primaryEmail',], titles)
@@ -11145,7 +11143,8 @@ def doPrintLicenses(returnFields=None, skus=None):
writeCSVfile(csvRows, titles, u'Licenses', todrive) writeCSVfile(csvRows, titles, u'Licenses', todrive)
RESCAL_DFLTFIELDS = [u'id', u'name', u'email',] RESCAL_DFLTFIELDS = [u'id', u'name', u'email',]
RESCAL_ALLFIELDS = [u'id', u'name', u'email', u'description', u'type', u'buildingid', u'category', u'capacity', u'features', u'floor', u'floorsection', u'generatedresourcename', u'uservisibledescription',] RESCAL_ALLFIELDS = [u'id', u'name', u'email', u'description', u'type', u'buildingid', u'category', u'capacity',
u'features', u'floor', u'floorsection', u'generatedresourcename', u'uservisibledescription',]
RESCAL_ARGUMENT_TO_PROPERTY_MAP = { RESCAL_ARGUMENT_TO_PROPERTY_MAP = {
u'description': [u'resourceDescription'], u'description': [u'resourceDescription'],
@@ -11492,7 +11491,6 @@ def OAuthInfo():
credentials.user_agent = GAM_INFO credentials.user_agent = GAM_INFO
access_token = credentials.access_token access_token = credentials.access_token
print u"\nOAuth File: %s" % GC_Values[GC_OAUTH2_TXT] print u"\nOAuth File: %s" % GC_Values[GC_OAUTH2_TXT]
oa2 = buildGAPIObject(u'oauth2') oa2 = buildGAPIObject(u'oauth2')
token_info = callGAPI(oa2, u'tokeninfo', access_token=access_token) token_info = callGAPI(oa2, u'tokeninfo', access_token=access_token)
print u"Client ID: %s" % token_info[u'issued_to'] print u"Client ID: %s" % token_info[u'issued_to']
@@ -11566,7 +11564,6 @@ gam create project
client_secret = cs_json[u'installed'][u'client_secret'] client_secret = cs_json[u'installed'][u'client_secret']
except (ValueError, IndexError, KeyError): except (ValueError, IndexError, KeyError):
systemErrorExit(3, u'the format of your client secrets file:\n\n%s\n\n is incorrect. Please recreate the file.') 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) return (client_id, client_secret)
class cmd_flags(object): class cmd_flags(object):
@@ -12624,11 +12621,9 @@ def ProcessGAMCommand(args):
except KeyboardInterrupt: except KeyboardInterrupt:
sys.exit(50) sys.exit(50)
except socket.error as e: except socket.error as e:
stderrErrorMsg(e) systemErrorExit(3, str(e))
sys.exit(3)
except MemoryError: except MemoryError:
stderrErrorMsg(MESSAGE_GAM_OUT_OF_MEMORY) systemErrorExit(99, MESSAGE_GAM_OUT_OF_MEMORY)
sys.exit(99)
except SystemExit as e: except SystemExit as e:
GM_Globals[GM_SYSEXITRC] = e.code GM_Globals[GM_SYSEXITRC] = e.code
return GM_Globals[GM_SYSEXITRC] return GM_Globals[GM_SYSEXITRC]