How to get Jenkins pending build id in python - django

views.py
here i can get the all information of build of jenkins job which is currently running. but when user runs or triggers same job again it will make queue on jenkins but as a pending build.
so i get the build id of currently running job and not of pending jenkins build. Actualy i want build id of pending build.
try:
print "in try.."
jenkinsStream = urllib2.urlopen( "http://10.211.213.138:8080/job/TE-mobius/lastBuild/api/json?pretty=true" )
print "after fetching url"
except urllib2.HTTPError, e:
print "URL Error: " + str(e.code)
print " (job name [" + jobName + "] probably wrong)"
try:
print "Before loading json"
buildStatusJson = json.load( jenkinsStream )
print "After loading json"
except:
print "Failed to parse json"
print "before while.."
print buildStatusJson["building"]
#print "[" + jobName + "] duration: " + str(buildStatusJson["duration"])
print buildStatusJson.has_key( "result" )
if buildStatusJson.has_key( "result" )==True:
print "in if"
print "[" + jobname + "] duration: " + str(buildStatusJson["duration"])
print "[" + jobname + "] building: " + str(buildStatusJson["building"])
print "[" + jobname + "] timestamp: " + str(buildStatusJson["timestamp"])
print "[" + jobname + "] url: " + str(buildStatusJson["url"])
print "[" + jobname + "] result: " + str(buildStatusJson["result"])
print "[" + jobname + "] build number: " + str(buildStatusJson["number"])
print "[" + jobname + "] JobName: " + str(buildStatusJson["fullDisplayName"])

There's an API endpoint at http://10.211.213.138:8080/job/TE-mobius/api/json?pretty=true that has a nextBuildNumber key.
It also has
"queueItem" : {
"blocked" : false,
"buildable" : true,
"id" : 119,
"inQueueSince" : 1401783373284,
"params" : "",
"stuck" : false,
"task" : {
"name" : "YourJobName",
"url" : "http://jenkins/job/YourJobName/"
},
"url" : "queue/item/119/",
"why" : "Waiting for next available executor",
"buildableStartMilliseconds" : 1401783373290,
"pending" : false
}
with some basic information about that pending build. Some of the build information you're trying to print in your code won't exist in Jenkins until the build has started.
Unfortunately, this will only let you get the build number of the next pending build. If you have a parameterised build and multiple builds in the queue for one job, I'm not aware of any way to get the build numbers of the other pending builds. You might have to write a plugin if you need to get those.

Related

Possible encoding issue between PS and C++

I have a C++ program written using Qt that I'm using as a front end to create AD accounts. Essentially I launch an elevated process that executes PowerShell commands within an elevated PowerShell session. I can create the accounts fine but when I attempt to pull membership from a pre-existing user to copy it over to the new one it fails. I need to understand why it's failing and resolve the issue, any help is greatly appreciated. It fails with the following error:
Get-ADUser : Cannot validate argument on parameter 'Identity'. The argument is null. Provide a valid value for the
argument, and then try running the command again.
At line:2 char:28
+ "}); $groups = (Get-ADUser $tmpusr -Properties MemberOf).MemberOf; $u ...
+ ~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-ADUser], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.GetADUser
The $tmpusr variable is just the value of duser.template_user which is pulled from a QComboBox and is deffinetly not null because it outputs correctly and shows the selected template account. In C++ it's just data added to a struct member:
duser.set_groups_command = "$tmpusr = (Get-ADUser -Filter {Name -like " "\"" + duser.template_user + "\"" "}); "
"$groups = (Get-ADUser $tmpusr -Properties MemberOf).MemberOf; "
"$usr = " "\"" + duser.sam_name + "\"" + "; "
"Foreach ($group in $groups) {Add-ADGroupMember -Identity (Get-ADGroup $group).name -Members $usr} ";
If I strip the C++ and run the same command within PowerShell it executes fine:
$tmpusr = (Get-ADUser -Filter {Name -like "Example User"}); $groups = (Get-ADUser $tmpusr -Properties MemberOf).MemberOf; $usr = "TestUser"; Foreach ($group in $groups) {Add-ADGroupMember -Identity (Get-ADGroup $group).name -Members $usr}
The purpose of the command is to determine which groups "Example User" belongs to and then to add "TestUser" to the same groups. Again, creating the user works fine. That is done with:
duser.complete_command = p + "New-ADUser -Name " + "\"" + duser.employe_name +"\"" + " -GivenName " + "\"" + duser.given_name + "\""
+ " -Surname " + "\"" + duser.surname + "\"" + " -AccountPassword $sec " + " -UserPrincipalName " + "\"" + duser.userpname + "\""
" -DisplayName " + "\"" + duser.display_name + "\"" + " -EmailAddress " + "\"" + duser.email_address + "\"" + " -SamAccountName " +
"\"" + duser.sam_name + "\"" + " -Enabled " + duser.is_enabled;
You'll note the existence of "p" which is another QString created earlier on to convert to a secure string. The only other component is the function that elevates and executes:
void MainWindow::elevate_and_execute(QString param)
{
QProcess *process = new QProcess();
QStringList params = QStringList();
params = QStringList({"-Command", QString("Start-Process -Verb runAs powershell; "), param});
process->startDetached("powershell", params);
process->waitForFinished();
process->terminate();
}
I was able to resolve the issue. I found that when I pulled the so called template user from the QComboBox it contained a carriage return. I had written the logs to a text file and found it was pushing it to the next line; so the $tmpusr was broken. I was able to resolve the issue by modifying the duser.template_user variable when it's initially filled by stripping that "\r" out with remove(QChar('\r'))

find snapshots whose volumes are deleted

I am trying to find out how many snapshots are there whose volumes are deleted. In this scenario there is a volume v-fffff whose snapshot is available but volume is deleted. I dont know how can I find it. Below is the code
volList=[{"VolumeId":"vol-sss","State":"in-use"},{"VolumeId":"vol-defghi","State":"available"},{"VolumeId":"vol-sfjfrf","State":"in-use"}]
snapList=[{"VolumeId":"vol-sss","snap-id":"sna-1356"},{"VolumeId":"vol-sss","snap-id":"sna-asd"},{"VolumeId":"vol-defghi","snap-id":"snap-1256"},{"VolumeId":"vol-defghi","snap-id":"snap-11"},{"VolumeId":"vol-sfjfrf","snap-id":"snap-456"},{"VolumeId":"v-fffff","snap-id":"snap-123"}]
for snap in snapList:
for vol in volList:
if snap['VolumeId'] == vol['VolumeId']:
print "match volume id :" + snap['VolumeId'] + " state " + vol['State'] + " snap-id : " + snap['snap-id']
else:
print "not match volume id :" + snap['VolumeId'] + " state not found" + " snap-id : " + snap['snap-id']
I found the solution. Indexing was the solution for such scenario
volList=[{"VolumeId":"vol-sss","State":"in-use"},{"VolumeId":"vol-defghi","State":"available"},{"VolumeId":"vol-sfjfrf","State":"in-use"}]
snapList=[{"VolumeId":"vol-sss","snap-id":"sna-1356"},{"VolumeId":"vol-sss","snap-id":"sna-asd"},{"VolumeId":"vol-defghi","snap-id":"snap-1256"},{"VolumeId":"vol-defghi","snap-id":"snap-11"},{"VolumeId":"vol-sfjfrf","snap-id":"snap-456"},{"VolumeId":"v-fffff","snap-id":"snap-123"}]
print len(snapList)
volIdList=[]
for ids in volList:
volIdList.append(ids['VolumeId'])
mainSnap=[]
for snap in snapList:
try:
if (volIdList.index(snap['VolumeId'])< 0):
print " not match volume id :" + snap['VolumeId']
else:
for v in volList:
if v['VolumeId']==snap['VolumeId']:
print "match volume id :" + snap['VolumeId'] + " " + v['State'] + " " + snap['snap-id']
except ValueError:
print " state not found " + snap['VolumeId'] + " " + snap['snap-id']

How to get the email addresses from PR_TRANSPORT_MESSAGE_HEADERS with VBA

How can I get the email addresses from PR_TRANSPORT_MESSAGE_HEADERS using VBA?
I have been trying some regular expressions but I never worked with it and I am having some problems.
I need to retrieve the email address from "To:" and "From:" and "CC:"
The macro below gets bigger every time I want to investigate a new mail item property. I add the new property or properties, comment out those I do not need today, select a few relevant emails and run the macro. I can then examine the desktop file “DemoExplorer.txt” at my leisure.
I have added all the “non-standard” properties that seem relevant to your requirement. Most seem duplicate of “standard properties”. The only one that seems useful is the “To:” line of PR_TRANSPORT_MESSAGE_HEADERS. The email addresses have been stripped out of the standard To property but they are present in the “To:” line.
Hope this helps.
Public Sub DemoExplorer()
' Outputs selected properties of selected emails to a file.
' ??????? No record of when originally coded
' 22Oct16 Output to desktop file rather than Immediate Window.
' Various New properties added as necessary
' Technique for locating desktop from answer by Kyle:
' http://stackoverflow.com/a/17551579/973283
' Source of PropertyAccessor information:
' https://www.slipstick.com/developer/read-mapi-properties-exposed-outlooks-object-model/
' Needs reference to Microsoft Scripting Runtime if "TextStream"
' and "FileSystemObject" are to be recognised
Dim AttachCount As Long
Dim AttachType As Long
Dim FileOut As TextStream
Dim Fso As FileSystemObject
Dim Exp As Outlook.Explorer
Dim InxA As Long
Dim InxR As Long
Dim ItemCrnt As MailItem
Dim NumSelected As Long
Dim Path As String
Dim PropAccess As Outlook.propertyAccessor
Path = CreateObject("WScript.Shell").SpecialFolders("Desktop")
Set Fso = CreateObject("Scripting.FileSystemObject")
Set FileOut = Fso.CreateTextFile(Path & "\DemoExplorer.txt", True)
Set Exp = Outlook.Application.ActiveExplorer
NumSelected = Exp.Selection.Count
If NumSelected = 0 Then
Debug.Print "No emails selected"
Else
For Each ItemCrnt In Exp.Selection
With ItemCrnt
FileOut.WriteLine "--------------------------"
FileOut.WriteLine "From (Sender): " & .Sender
FileOut.WriteLine "From (Sender name): " & .SenderName
FileOut.WriteLine "From (Sender email address): " & .SenderEmailAddress
FileOut.WriteLine "Subject: " & CStr(.Subject)
FileOut.WriteLine "Received: " & Format(.ReceivedTime, "dMMMyy h:mm:ss")
FileOut.WriteLine "To: " & .To
FileOut.WriteLine "CC: " & .CC
FileOut.WriteLine "Recipients: " & .Recipients(1)
For InxR = 2 To .Recipients.Count
FileOut.WriteLine Space(12) & .Recipients(InxR)
Next
'FileOut.WriteLine "Text: " & Replace(Replace(Replace(.Body, vbLf, "{lf}"), vbCr, "{cr}"), vbTab, "{tb}")
'FileOut.WriteLine "Html: " & Replace(Replace(Replace(.HtmlBody, vbLf, "{lf}"), vbCr, "{cr}"), vbTab, "{tb}")
'AttachCount = .Attachments.Count
'FileOut.WriteLine "Number of attachments: " & AttachCount
'For InxA = 1 To AttachCount
' AttachType = .Attachments(InxA).Type
' FileOut.WriteLine "Attachment " & InxA
' FileOut.Write " Attachment type: "
' Select Case AttachType
' Case olByValue
' FileOut.WriteLine "By value"
' Case olEmbeddeditem
' FileOut.WriteLine "Embedded item"
' Case olByReference
' FileOut.WriteLine "By reference"
' Case olOLE
' FileOut.WriteLine "OLE"
' Case Else
' FileOut.WriteLine "Unknown " & AttachType
' End Select
' ' I recall PathName giving an error for some types
' On Error Resume Next
' FileOut.WriteLine " Path: " & .Attachments(InxA).PathName
' On Error GoTo 0
' FileOut.WriteLine " File name: " & .Attachments(InxA).FileName
' FileOut.WriteLine " Display name: " & .Attachments(InxA).DisplayName
' ' I do not recall every seeing a parent but it is listed as a property
' ' but for some attachment types it gives an error
' On Error Resume Next
' FileOut.WriteLine " Parent: " & .Attachments(InxA).Parent
' On Error GoTo 0
' FileOut.WriteLine " Position: " & .Attachments(InxA).Position
'Next
Set PropAccess = .propertyAccessor
FileOut.WriteLine "PR_RECEIVED_BY_NAME: " & _
PropAccess.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x0040001E")
FileOut.WriteLine "PR_SENT_REPRESENTING_NAME: " & _
PropAccess.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x0042001E")
FileOut.WriteLine "PR_REPLY_RECIPIENT_NAMES: " & _
PropAccess.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x0050001E")
FileOut.WriteLine "PR_SENT_REPRESENTING_EMAIL_ADDRESS: " & _
PropAccess.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x0065001E")
FileOut.WriteLine "PR_RECEIVED_BY_EMAIL_ADDRESS: " & _
PropAccess.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x0076001E")
FileOut.WriteLine "PR_TRANSPORT_MESSAGE_HEADERS:" & vbLf & _
PropAccess.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x007D001E")
FileOut.WriteLine "PR_SENDER_NAME: " & _
PropAccess.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x0C1A001E")
FileOut.WriteLine "PR_SENDER_EMAIL_ADDRESS: " & _
PropAccess.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x0C1F001E")
FileOut.WriteLine "PR_DISPLAY_BCC: " & _
PropAccess.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x0E02001E")
FileOut.WriteLine "PR_DISPLAY_CC: " & _
PropAccess.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x0E03001E")
FileOut.WriteLine "PR_DISPLAY_TO: " & _
PropAccess.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x0E04001E")
Set PropAccess = Nothing
End With
Next
End If
FileOut.Close
End Sub

Accessing data required out of for loop in python and store the data at specific location

I am using a for loop for getting data from the user in command prompt using python 2.7. Then storing the data in a text file in certain format. I am looking for a method to get the data from the user and store it in a list and use it where required.
for Input_Number in range(Number_Of_Inputs):
Input_Number = Input_Number+1
GUI_Parameter = str(raw_input("Please enter input parameter " + str(Input_Number) + " :"))
GUI_Parameter_Name = str(raw_input("Enter the GUI name for the parameter " + str(Input_Number) + " :"))
Store_GUI_Parameter(Opened_File, GUI_Parameter, GUI_Parameter_Name)
I would like to use this data to store it in a specific location in a text file according to required syntax. The above code stores the data in the text file. But the problem is it doesn't store it at the required place.
def Store_GUI_Parameter(Opened_File, GUI_Parameter, GUI_Parameter_Name):
GUI_Description = "| " + '"'+ GUI_Parameter_Name + '"' + " |$" + GUI_Parameter.title() + " |"
Write_Data(Opened_File, GUI_Description)
print "GUI parameters written to NDF file"
return
The data storage is done using the above function...
I tried this, but unfortunately this also is not working
GUI_Parameter= []
GUI_Parameter_Name = []
for Input_Number in range(Number_Of_Inputs):
Input_Number = Input_Number+1
GUI_Parameter[Input_Number] = str(raw_input("Please enter input parameter " + str(Input_Number) + " :"))
GUI_Parameter_Name[Input_Number] = str(raw_input("Enter the GUI name for the parameter " + str(Input_Number) + " :"))
Using it outside the loop in the same function...
GUI_Description(Opened_File, GUI_Parameter_Name[Input_Number], GUI_Parameter[Input_Number])
The function implementation:
def GUI_Description(Opened_File, GUI_Parameter_Name[Input_Number], GUI_Parameter[Input_Number]):
Iteration = 0
while Iteration < Input_Number:
Iteration += 1
GUI_Description = "| " + '"'+ GUI_Parameter_Name[Input_Number] + '"' + " |$" + GUI_Parameter[Input_Number].title() + " |"
Write_Data(Opened_File, GUI_Description)
print "GUI parameters written to NDF file"
return
But it shows syntax error at the def GUI_Description
C:\Users\padmanab\Desktop>python CtoN.py File "CtoN.py", line 173
def GUI_Description(Opened_File, GUI_Parameter_Name[Input_Number], GUI_Parameter[Input_Number]):
^ SyntaxError: invalid syntax
The syntax error in the function GUI_Description is caused by your input arguments. 'GUI_Parameter_Name[Input_Number]' is not a valid input argument. Since your function requires both 'GUI_Parameter_Name' and 'Input_Number' they should be separate input arguments. The code snippet below would solve this syntax error:
def GUI_Description(Opened_File, Input_Number, GUI_Parameter_Name, GUI_Parameter):
...
The code below will give an 'index out of range' error since the lists 'GUI_Parameter' and 'GUI_Parameter_Name' have zero length.
GUI_Parameter= []
GUI_Parameter_Name = []
Number_Of_Inputs = 1
for Input_Number in range(Number_Of_Inputs):
Input_Number = Input_Number+1
GUI_Parameter[Input_Number] = str(raw_input("Please enter input parameter " + str(Input_Number) + " :"))
GUI_Parameter_Name[Input_Number] = str(raw_input("Enter the GUI name for the parameter " + str(Input_Number) + " :"))
If you want to add items to the arrays you should append them:
GUI_Parameter.append(raw_input())

Find and later delete zombie informatica objects

Is there a easy way to identify and clean unused informatica artifacts?
Context: In one of the projects, there are lot of zombie sessions / mappings etc, the creators have long gone.
I want to do the following:
List/Delete all sessions that are not associated with a workflow.
List/Delete all mappings that are not used in any session/wf.
List/Delete all source/target that were not used in any mapping.
List/Delete all workflows that were not run in the past one year.
Someone mentioned about using : Designer > Tools > Queries . I can't express the above 1/2/3/4 with the option given, can anyone shed some light?
Note:
I’m not looking for click one by one and find dependencies.
I’m not looking for download the whole plant as xml and search dependencies
one by one
As this is not easily achievable with PowerCenter itself, I tried to come up with some simple tool to solve it. For the full description and download link please go to this page.
Below you'll find the code published as requested in comments: Find and later delete zombie informatica objects
Feel free to use, share and improve :) Any code review will be also much appreciated.
import subprocess
import os
from subprocess import *
import platform
import sys
import getpass
import configparser
#global variables declarations
currentDir=''
pmrepPath=''
domainFile=''
def connect_to_repo(Repository,Domain,User,Host,Port, UserSecurityDomain):
#password = raw_input("Enter password for Repository: " + Repository + ", User: " + User)
password = getpass.getpass()
print "\nConnecting..."
if Domain != '':
RepoCommand="pmrep connect -r "+Repository+" -d "+Domain+" -n "+User + " -x " + password #+" -X DOMAIN_PWD"
else:
RepoCommand="pmrep connect -r "+Repository+" -n "+User + " -x " + password + " -h " + Host + " -o " + Port
if UserSecurityDomain != '':
RepoCommand += " -s " + UserSecurityDomain
RepoCommand=RepoCommand.rstrip()
p=subprocess.Popen(RepoCommand,stderr=subprocess.PIPE,stdin=subprocess.PIPE,stdout=subprocess.PIPE,shell=True)
out,err=p.communicate()
if p.returncode or err:
print "Connection Failed"
print err.strip()
print out.strip()
sys.stdout.flush()
sys.stdin.flush()
else:
print "Connection Successful"
sys.stdout.flush()
sys.stdin.flush()
return p.returncode
def execute_pmrep_command(command, output_file_name, start_line, end_line, line_prefix):
if len(line_prefix)>0: line_prefix+=' '
out=open(output_file_name,'a')
return_code=subprocess.Popen(command,stdin=subprocess.PIPE,stdout=subprocess.PIPE,shell=True)
output,error=return_code.communicate()
for line in output.split('\r\n')[start_line:end_line]:
out.writelines(line_prefix + line + '\n')
out.close()
return
def check_platform():
global domainFile
global currentDir
global pmrepPath
global platForm
platForm=platform.system()
print "Platform recognized : "+platForm
## if not os.getenv('INFA_HOME', 'C:\\Informatica\\9.5.1'):
## print "INFA_HOME env_variable not set in your "+platForm+" platform."
## print "Please set INFA_HOME and continue."
## raw_input()
## sys.exit(0)
if not os.getenv('INFA_DOMAINS_FILE'):
print "INFA_DOMAINS_FILE env_variable not set in your "+platForm+" platform."
print "Please set INFA_DOMAINS_FILE and continue."
raw_input()
sys.exit(0)
## elif not os.getenv('DOMAIN_PWD', 'vic'):
## print "DOMAIN_PWD env variable not set in your "+platForm+" platform."
## print "Please set DOMAIN_PWD and continue."
## raw_input()
## sys.exit(0)
## else:
## if platForm == 'Windows':
## pmrepPath=os.getenv('INFA_HOME').strip()+"\clients\PowerCenterClient\client\\bin"
## elif platForm == 'Linux':
## pmrepPath=os.getenv('INFA_HOME').strip()+"/server/bin"
## currentDir=os.getcwd()
## domainFile=os.getenv('INFA_DOMAINS_FILE','C:\\Informatica\\9.5.1\\domains.infa').strip()
config = configparser.RawConfigParser()
config.optionxform = lambda option: option
config.read('InfaRepo_ListUnusedObjects.cfg')
infaDir = config.get('Common', 'infaDir').strip()
Repository = config.get('Common', 'Repository').strip()
Domain = config.get('Common', 'Domain').strip()
Host = config.get('Common', 'Host').strip()
Port = config.get('Common', 'Port').strip()
Folder = config.get('Common', 'Folder').strip()
User = config.get('Common', 'User').strip()
UserSecurityDomain = config.get('Common', 'UserSecurityDomain').strip()
objectTypeList = config.get('Common', 'objectTypeList').split(',')
if Domain != '':
print 'Domain provided, will be used to connect.'
else:
print 'Domain not provided, Host and Port will be used to connect.'
for i in range(len(objectTypeList)):
objectTypeList[i]=objectTypeList[i].strip()
currentDir=os.getcwd()
outputDir=currentDir+'\\UnusedObjectsReport'
###objectTypeList = ['mapplet', 'mapping', 'session', 'source', 'target', 'worklet']
##
##objectTypeList = ['target']
pmrepPath=infaDir.strip()+"\clients\PowerCenterClient\client\\bin"
os.chdir(pmrepPath)
outFile = outputDir + "\ListOfUnusedObjects.txt"
if not os.path.exists(os.path.dirname(outFile)):
os.makedirs(os.path.dirname(outFile))
print 'Output file: ' + outFile
open(outFile,'w').writelines("Domain : "+Domain+"\nRepository : "+Repository+"\nUserName : "+User+"\n")
open(outFile,'a').writelines("***************************"+"\n")
open(outFile,'a').writelines("LIST OF UNUSED OBJECTS:\n")
outBatchFile = outputDir + "\DeleteUnusedObjects.bat"
tempDir = outputDir + "\\temp"
if not os.path.exists(outputDir):
os.makedirs(outputDir)
if not os.path.exists(tempDir):
os.makedirs(tempDir)
for tempFile in os.listdir(tempDir):
os.remove(os.path.join(tempDir, tempFile))
print 'Output batch file: ' + outBatchFile
if Domain != '':
RepoCommand="pmrep connect -r "+Repository+" -d "+Domain+" -n "+User
else:
RepoCommand="pmrep connect -r "+Repository+" -n "+User + " -h " + Host + " -o " + Port
if UserSecurityDomain != '':
RepoCommand += " -s " + UserSecurityDomain
open(outBatchFile,'w').writelines(pmrepPath+"\\"+RepoCommand+"\n")
objectTypeCounter=0
return_code=connect_to_repo(Repository,Domain,User,Host,Port,UserSecurityDomain)
objDepDict={}
error = False
errorList = []
#check if repository connection is successfull
if return_code==0:
for objectType in objectTypeList:
objectTypeCounter+=1
print "Step {0} of {1}: {2}".format(objectTypeCounter, len(objectTypeList), objectType)
objectFile = tempDir + "\\" + objectType + ".txt"
open(objectFile,'w').writelines("")
objectDepFile = tempDir + "\\" + objectType + "_dep.txt"
open(objectDepFile,'w').writelines("")
execute_pmrep_command("pmrep listobjects -f " + Folder + " -o " + objectType, objectFile, 8, -4, '')
objectList=open(objectFile).readlines()
objectCounter=0
if len(objectList) == 0:
print '\tNo {0}s found'.format(objectType)
elif objectList[0][:3] == ' [[':
error=True
for line in objectList:
errorList += [line.replace('\n','')]
break
for line in objectList:
objectCounter+=1
fields=line.split(' ')
if len(fields) == 2:
objectType=fields[0]
objectName=fields[1][:-1]
else:
objectType=fields[0]
objectName=fields[2][:-1]
#if the object is non-reusable, it obviously is in some workflow, so skipp it
if fields[1] == 'non-reusable':
print "\t{0} {1} of {2}: {3} is not a reusable {4} - skipping".format(objectType, objectCounter, len(objectList), objectName, objectType)
continue
command = "pmrep listobjectdependencies -f " + Folder + " -n " + objectName + " -o " + objectType + " -p parents"
#print "Getting object dependencies for " + objectType + " " + objectName
print "\t{0} {1} of {2}: {3}".format(objectType, objectCounter, len(objectList), objectName)
execute_pmrep_command(command, objectDepFile, 8, -6, objectName)
#find unused objects
for fileLine in open(objectDepFile,'r').readlines():
line = fileLine.split(' ')
if len(line) == 3:
Name = line[0]
ParentType = line[1]
ParentName = line[2]
else:
Name = line[0]
ParentType = line[1]
ParentName = line[3]
try:
objDepDict[objectType + ': ' + Name]+=[ParentType + ' ' + ParentName]
except:
objDepDict[objectType + ': ' + Name]=[ParentType + ' ' + ParentName]
found = False
for objectKey in objDepDict.iterkeys():
objectType, objName = objectKey.replace(' ','').split(':')
if len(objDepDict[objectKey]) <= 1:
if not found:
print '\n'
print 'Following unused objects have been found:'
found = True
print '\t{0}: {1}'.format(objectType, objName)
open(outFile,'a').writelines('{0}: {1}\n'.format(objectType, objName))
open(outBatchFile,'a').writelines("rem {0}\\pmrep deleteobject -f {1} -o {2} -n {3}\n".format(pmrepPath, Folder, objectType, objName))
execute_pmrep_command('pmrep cleanup', 'log.txt', 0, 0, '')
open(outBatchFile,'a').writelines(pmrepPath+'\\pmrep cleanup' + '\n')
if not error:
if not found:
print 'No unused objects found.'
print '\nDone.'
print 'Output file: ' + outFile
print 'Output batch file: ' + outBatchFile
else:
print 'Following errors occured:'
for e in errorList:
print '\t', e
#wait for key press
print '\nHit Enter to quit...'
raw_input()
#End of program