Skip to content

Commit 9a21cd4

Browse files
committed
Chore: refactor string formatting
1 parent a611754 commit 9a21cd4

File tree

18 files changed

+84
-84
lines changed

18 files changed

+84
-84
lines changed

usr/lib/python3/dist-packages/linuxmusterLinuxclient7/computer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ def readAttributes():
2626
:return: Tuple (success, dict of attributes)
2727
:rtype: tuple
2828
"""
29-
return ldapHelper.searchOne("(sAMAccountName={}$)".format(hostname()))
29+
return ldapHelper.searchOne(f"(sAMAccountName={hostname()}$)")
3030

3131
def isInGroup(groupName):
3232
"""

usr/lib/python3/dist-packages/linuxmusterLinuxclient7/constants.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,12 +35,12 @@
3535
"/usr/sbin/linuxmuster-client-adsso",
3636
"/usr/sbin/linuxmuster-client-adsso-print-logs",
3737
"/etc/systemd/system/linuxmuster-client-adsso.service",
38-
"{}/.config/autostart/linuxmuster-client-adsso-autostart.desktop".format(userTemplateDir),
38+
f"{userTemplateDir}/.config/autostart/linuxmuster-client-adsso-autostart.desktop",
3939
"/etc/cups/client.conf",
4040
"/usr/share/linuxmuster-linuxclient7/templates/linuxmuster-client-adsso.service",
4141
"/usr/share/linuxmuster-linuxclient7/templates/linuxmuster-client-adsso-autostart.desktop",
4242
"/etc/security/pam_mount.conf.xml",
43-
"{}/pam_mount.conf.xml".format(configFileTemplateDir)
43+
f"{configFileTemplateDir}/pam_mount.conf.xml"
4444
]
4545

4646
obsoleteDirectories = [

usr/lib/python3/dist-packages/linuxmusterLinuxclient7/environment.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ def export(keyValuePair):
1010
:return: True or False
1111
:rtype: bool
1212
"""
13-
logging.debug("Saving export '{}' to tmp file".format(keyValuePair))
13+
logging.debug(f"Saving export '{keyValuePair}' to tmp file")
1414

1515
envList = keyValuePair.split("=", 1)
1616
if len(envList) == 2:
@@ -27,7 +27,7 @@ def unset(key):
2727
:return: True or False
2828
:rtype: bool
2929
"""
30-
logging.debug("Saving unset '{}' to tmp file".format(key))
30+
logging.debug(f"Saving unset '{key}' to tmp file")
3131
return _appendToTmpEnvFile("unset", key)
3232

3333
# --------------------
@@ -53,7 +53,7 @@ def _appendToTmpEnvFile(mode, keyValuePair):
5353

5454
try:
5555
with open(tmpEnvironmentFilePath, fileOpenMode) as tmpEnvironmentFile:
56-
tmpEnvironmentFile.write("\n{0} '{1}'".format(mode, keyValuePair))
56+
tmpEnvironmentFile.write(f"\n{mode} '{keyValuePair}'")
5757
return True
5858
except Exception as e:
5959
logging.exception(e)

usr/lib/python3/dist-packages/linuxmusterLinuxclient7/fileHelper.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -81,8 +81,8 @@ def deleteFilesWithExtension(directory, extension):
8181

8282
for file in existingFiles:
8383
if file.endswith(extension):
84-
logging.info("* Deleting {}".format(file))
85-
if not deleteFile("{}/{}".format(directory, file)):
84+
logging.info(f"* Deleting {file}")
85+
if not deleteFile(f"{directory}/{file}"):
8686
logging.error("Failed!")
8787
return False
8888

@@ -121,7 +121,7 @@ def deleteAllInDirectory(directory):
121121

122122
existingFiles=os.listdir(directory)
123123
for file in existingFiles:
124-
fullFilePath = "{}/{}".format(directory, file)
124+
fullFilePath = f"{directory}/{file}"
125125
if os.path.isdir(fullFilePath):
126126
rc = deleteDirectory(fullFilePath)
127127
else:

usr/lib/python3/dist-packages/linuxmusterLinuxclient7/gpo.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -56,15 +56,15 @@ def _findApplicablePolicies():
5656

5757
""" Do this later!
5858
# 1. Domain
59-
rc, domainAdObject = ldapHelper.searchOne("(distinguishedName={})".format(ldapHelper.baseDn()))
59+
rc, domainAdObject = ldapHelper.searchOne(f"(distinguishedName={ldapHelper.baseDn()})")
6060
6161
if not rc:
6262
return False, None
6363
6464
policyDNs.extend(_parseGplinkSring(domainAdObject["gPLink"]))
6565
6666
# 2. OU policies from top to bottom
67-
rc, userAdObject = ldapHelper.searchOne("(sAMAccountName={})".format(user.username()))
67+
rc, userAdObject = ldapHelper.searchOne(f"(sAMAccountName={user.username()})")
6868
6969
if not rc:
7070
return False, None
@@ -77,10 +77,10 @@ def _findApplicablePolicies():
7777
if not rc:
7878
return False, None
7979

80-
policyName = "sophomorix:school:{}".format(schoolName)
80+
policyName = f"sophomorix:school:{schoolName}"
8181

8282
# find policy
83-
rc, policyAdObject = ldapHelper.searchOne("(displayName={})".format(policyName))
83+
rc, policyAdObject = ldapHelper.searchOne(f"(displayName={policyName})")
8484
if not rc:
8585
return False, None
8686

@@ -89,7 +89,7 @@ def _findApplicablePolicies():
8989
return True, policyDnList
9090

9191
def _parsePolicy(policyDn):
92-
logging.info("=== Parsing policy [{0};{1}] ===".format(policyDn[0], policyDn[1]))
92+
logging.info(f"=== Parsing policy [{policyDn[0]};{policyDn[1]}] ===")
9393

9494
""" (not needed because it's currently hardcoded)
9595
# Check if the policy is disabled
@@ -99,7 +99,7 @@ def _parsePolicy(policyDn):
9999
"""
100100

101101
# Find policy in AD
102-
rc, policyAdObject = ldapHelper.searchOne("(distinguishedName={})".format(policyDn[0]))
102+
rc, policyAdObject = ldapHelper.searchOne(f"(distinguishedName={policyDn[0]})")
103103
if not rc:
104104
logging.error("===> Could not find poilcy in AD! ===")
105105
return False
@@ -120,7 +120,7 @@ def _parsePolicy(policyDn):
120120
logging.exception(e)
121121
return False
122122

123-
logging.info("===> Parsed policy [{0};{1}] ===".format(policyDn[0], policyDn[1]))
123+
logging.info(f"===> Parsed policy [{policyDn[0]};{policyDn[1]}] ===")
124124
return allSuccessfull
125125

126126
def _parseXmlFilters(filtersXmlNode):
@@ -153,13 +153,13 @@ def _processFilters(policies):
153153
else:
154154
filtersPassed = True
155155
for filter in policy["filters"]:
156-
logging.debug("Testing filter: {}".format(filter))
156+
logging.debug(f"Testing filter: {filter}")
157157
if filter["bool"] == "AND":
158158
filtersPassed = filtersPassed and _processFilter(filter)
159159
elif filter["bool"] == "OR":
160160
filtersPassed = filtersPassed or _processFilter(filter)
161161
else:
162-
logging.warning("Unknown boolean operation: {}! Assuming condition is false.".format(filter["bool"]))
162+
logging.warning(f"Unknown boolean operation: {filter['bool']}! Assuming condition is false.")
163163
filtersPassed = False
164164

165165
if filtersPassed:
@@ -192,7 +192,7 @@ def _parseXmlPolicy(policyFile):
192192

193193
def _processDrivesPolicy(policyBasepath):
194194
logging.info("== Parsing a drive policy! ==")
195-
policyFile = "{}/User/Preferences/Drives/Drives.xml".format(policyBasepath)
195+
policyFile = f"{policyBasepath}/User/Preferences/Drives/Drives.xml"
196196
shareList = []
197197

198198
rc, tree = _parseXmlPolicy(policyFile)
@@ -235,7 +235,7 @@ def _processDrivesPolicy(policyBasepath):
235235

236236
logging.info("Found shares:")
237237
for drive in shareList:
238-
logging.info("* {:15}| {:5}| {:40}| {:5}".format(drive["label"], drive["letter"], drive["path"], drive["useLetter"]))
238+
logging.info(f"* {drive['label']:15}| {drive['letter']:5}| {drive['path']:40}| {drive['useLetter']:5}")
239239

240240
for drive in shareList:
241241
if drive["useLetter"] == "1":
@@ -252,7 +252,7 @@ def _processDrivesPolicy(policyBasepath):
252252

253253
def _processPrintersPolicy(policyBasepath):
254254
logging.info("== Parsing a printer policy! ==")
255-
policyFile = "{}/User/Preferences/Printers/Printers.xml".format(policyBasepath)
255+
policyFile = f"{policyBasepath}/User/Preferences/Printers/Printers.xml"
256256
printerList = []
257257
# test
258258
rc, tree = _parseXmlPolicy(policyFile)
@@ -300,7 +300,7 @@ def _processPrintersPolicy(policyBasepath):
300300

301301
logging.info("Found printers:")
302302
for printer in printerList:
303-
logging.info("* {0}\t\t| {1}\t| {2}".format(printer["name"], printer["path"], printer["filters"]))
303+
logging.info(f"* {printer['name']}\t\t| {printer['path']}\t| {printer['filters']}")
304304
printers.installPrinter(printer["path"], printer["name"])
305305

306306
logging.info("==> Successfully parsed a printer policy! ==")

usr/lib/python3/dist-packages/linuxmusterLinuxclient7/hooks.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -51,13 +51,13 @@ def runLocalHook(hookType):
5151
:type hookType: hooks.Type
5252
"""
5353
hookDir = _getLocalHookDir(hookType)
54-
logging.info("=== Running local hook on{0} in {1} ===".format(hookType.name, hookDir))
54+
logging.info(f"=== Running local hook on{hookType.name} in {hookDir} ===")
5555
if os.path.exists(hookDir):
5656
_prepareEnvironment()
5757
for fileName in sorted(os.listdir(hookDir)):
5858
filePath = hookDir + "/" + fileName
5959
_runHookScript(filePath)
60-
logging.info("===> Finished running local hook on{0} ===".format(hookType.name))
60+
logging.info(f"===> Finished running local hook on{hookType.name} ===")
6161

6262

6363
def runRemoteHook(hookType):
@@ -67,15 +67,15 @@ def runRemoteHook(hookType):
6767
:param hookType: The type of hook to run
6868
:type hookType: hooks.Type
6969
"""
70-
logging.info("=== Running remote hook on{0} ===".format(hookType.name))
70+
logging.info(f"=== Running remote hook on{hookType.name} ===")
7171
rc, hookScripts = _getRemoteHookScripts(hookType)
7272

7373
if rc:
7474
_prepareEnvironment()
7575
_runHookScript(hookScripts[0])
7676
_runHookScript(hookScripts[1])
7777

78-
logging.info("===> Finished running remote hook on{0} ===".format(hookType.name))
78+
logging.info(f"===> Finished running remote hook on{hookType.name} ===")
7979

8080
def runHook(hookType):
8181
"""
@@ -95,7 +95,7 @@ def getLocalHookScript(hookType):
9595
:return: The path
9696
:rtype: str
9797
"""
98-
return "{0}/on{1}".format(constants.scriptDir,hookType.name)
98+
return f"{constants.scriptDir}/on{hookType.name}"
9999

100100
def shouldHooksBeExecuted(overrideUsername=None):
101101
"""Check if hooks should be executed
@@ -120,7 +120,7 @@ def shouldHooksBeExecuted(overrideUsername=None):
120120
overrideUsername = user.username()
121121

122122
if not user.isUserInAD(overrideUsername):
123-
logging.info("==== {0} is not an AD user, exiting ====".format(user.username()))
123+
logging.info(f"==== {overrideUsername} is not an AD user, exiting ====")
124124
return False
125125

126126
return True
@@ -148,7 +148,7 @@ def _prepareEnvironment():
148148
_writeEnvironment(environment)
149149

150150
def _getLocalHookDir(hookType):
151-
return "{0}/on{1}.d".format(constants.etcBaseDir,hookType.name)
151+
return f"{constants.etcBaseDir}/on{hookType.name}.d"
152152

153153
def _getRemoteHookScripts(hookType):
154154
if not hookType in remoteScriptNames:
@@ -184,7 +184,7 @@ def _getRemoteHookScripts(hookType):
184184
logging.error("Could not execute server hook {} because the sysvol could not be mounted!\n")
185185
return False, None
186186

187-
hookScriptPathTemplate = "{0}/{1}/scripts/{2}/{3}/linux/{4}".format(sysvolPath, domain, school, "{}", scriptName)
187+
hookScriptPathTemplate = f"{sysvolPath}/{domain}/scripts/{school}/{{}}/linux/{scriptName}"
188188

189189
return True, [hookScriptPathTemplate.format("lmn"), hookScriptPathTemplate.format("custom")]
190190

@@ -202,17 +202,17 @@ def _dictsToEnv(dictsAndPrefixes):
202202

203203
def _runHookScript(filePath):
204204
if not os.path.isfile(filePath):
205-
logging.warning("* File {0} should be executed as hook but does not exist!".format(filePath))
205+
logging.warning(f"* File {filePath} should be executed as hook but does not exist!")
206206
return
207207
if not os.access(filePath, os.X_OK):
208-
logging.warning("* File {0} is in hook dir but not executable!".format(filePath))
208+
logging.warning(f"* File {filePath} is in hook dir but not executable!")
209209
return
210210

211-
logging.info("== Executing script {0} ==".format(filePath))
211+
logging.info(f"== Executing script {filePath} ==")
212212

213213
result = subprocess.call([filePath])
214214

215-
logging.info("==> Script {0} finished with exit code {1} ==".format(filePath, result))
215+
logging.info(f"==> Script {filePath} finished with exit code {result} ==")
216216

217217
def _writeEnvironment(environment):
218218
for key in environment:

usr/lib/python3/dist-packages/linuxmusterLinuxclient7/imageHelper.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def prepareForImage(unattended=False):
5454
def _askStep(step, printPlaceholder=True):
5555
if printPlaceholder:
5656
print()
57-
response = input("Do you want to {}? (y/n): ".format(step))
57+
response = input(f"Do you want to {step}? (y/n): ")
5858
result = response in ["y", "Y", "j", "J"]
5959
if result:
6060
print()
@@ -114,7 +114,7 @@ def _checkLoggedInUsers():
114114

115115
for loggedInUser in loggedInUsers:
116116
if user.isUserInAD(loggedInUser):
117-
logging.error("User {} is still logged in, please log out first! Aborting!".format(loggedInUser))
117+
logging.error(f"User {loggedInUser} is still logged in, please log out first! Aborting!")
118118
return False
119119

120120
return True
@@ -169,12 +169,12 @@ def _clearUserHomes(unattended=False):
169169
logging.info("Deleting all user homes now!")
170170
for userHome in userHomes:
171171
if not user.isUserInAD(userHome):
172-
logging.info("* {} [SKIPPED]".format(userHome))
172+
logging.info(f"* {userHome} [SKIPPED]")
173173
continue
174174

175-
logging.info("* {}".format(userHome))
175+
logging.info(f"* {userHome}")
176176
try:
177-
shutil.rmtree("/home/{}".format(userHome))
177+
shutil.rmtree(f"/home/{userHome}")
178178
except Exception as e:
179179
logging.error("* FAILED!")
180180
logging.exception(e)
@@ -188,9 +188,9 @@ def _clearUserHomes(unattended=False):
188188
return True
189189

190190
def _clearPrinters(unattended=False):
191-
print("\nCAUTION! This will delete all printers of {}!".format(constants.templateUser))
191+
print(f"\nCAUTION! This will delete all printers of {constants.templateUser}!")
192192
print("This makes sure that local printers do not conflict with remote printers defined by GPOs.")
193-
if not unattended and not _askStep("remove all local printers of {}".format(constants.templateUser), False):
193+
if not unattended and not _askStep(f"remove all local printers of {constants.templateUser}", False):
194194
return True
195195

196196
if not printers.uninstallAllPrintersOfUser(constants.templateUser):
@@ -213,7 +213,7 @@ def _emptyTrash(unattended=False):
213213
if not unattended and not _askStep("clear the Trash of linuxadmin"):
214214
return True
215215

216-
if not fileHelper.deleteAllInDirectory("/home/{}/.local/share/Trash".format(constants.templateUser)):
216+
if not fileHelper.deleteAllInDirectory(f"/home/{constants.templateUser}/.local/share/Trash"):
217217
return False
218218

219219
return True

usr/lib/python3/dist-packages/linuxmusterLinuxclient7/keytab.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,13 @@ def patchKeytab():
99
:rtype: bool
1010
"""
1111
krb5KeytabFilePath = "/etc/krb5.keytab"
12-
logging.info("Patching {}".format(krb5KeytabFilePath))
12+
logging.info(f"Patching {krb5KeytabFilePath}")
1313
krb5KeytabUtil = Krb5KeytabUtil(krb5KeytabFilePath)
1414

1515
try:
1616
krb5KeytabUtil.read()
1717
except:
18-
logging.error("Error reading {}".format(krb5KeytabFilePath))
18+
logging.error(f"Error reading {krb5KeytabFilePath}")
1919
return False
2020

2121
for entry in krb5KeytabUtil.keytab.entries:
@@ -40,15 +40,15 @@ def patchKeytab():
4040

4141
entry.principal.components[1].data = newData
4242

43-
logging.debug("{} was changed to {}".format(oldData, entry.principal.components[-1].data))
43+
logging.debug(f"{oldData} was changed to {entry.principal.components[-1].data}")
4444

45-
logging.info("Trying to overwrite {}".format(krb5KeytabFilePath))
45+
logging.info(f"Trying to overwrite {krb5KeytabFilePath}")
4646
try:
4747
result = krb5KeytabUtil.write()
4848
except:
4949
result = False
5050

5151
if not result:
52-
logging.error("Error overwriting {}".format(krb5KeytabFilePath))
52+
logging.error(f"Error overwriting {krb5KeytabFilePath}")
5353

5454
return result

usr/lib/python3/dist-packages/linuxmusterLinuxclient7/ldapHelper.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ def serverUrl():
1616
return False, None
1717

1818
serverHostname = networkConfig["serverHostname"]
19-
return 'ldap://{0}'.format(serverHostname)
19+
return f"ldap://{serverHostname}"
2020

2121
def baseDn():
2222
"""
@@ -108,9 +108,9 @@ def isObjectInGroup(objectDn, groupName):
108108
:return: True if it is a member, False otherwise
109109
:rtype: bool
110110
"""
111-
logging.debug("= Testing if object {0} is a member of group {1} =".format(objectDn, groupName))
112-
rc, groupAdObject = searchOne("(&(member:1.2.840.113556.1.4.1941:={0})(sAMAccountName={1}))".format(objectDn, groupName))
113-
logging.debug("=> Result: {} =".format(rc))
111+
logging.debug(f"= Testing if object {objectDn} is a member of group {groupName} =")
112+
rc, groupAdObject = searchOne(f"(&(member:1.2.840.113556.1.4.1941:={objectDn})(sAMAccountName={groupName}))")
113+
logging.debug(f"=> Result: {rc} =")
114114
return rc
115115

116116
# --------------------

usr/lib/python3/dist-packages/linuxmusterLinuxclient7/localUserHelper.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,5 +15,5 @@ def getGroupsOfLocalUser(username):
1515
stringList=[x.decode('utf-8') for x in groups.split(b"\x00")]
1616
return True, stringList
1717
except Exception as e:
18-
logging.warning("Exception when querying groups of user {}, it probaply does not exist".format(username))
18+
logging.warning(f"Exception when querying groups of user {username}, it probably does not exist")
1919
return False, None

0 commit comments

Comments
 (0)