Advertisement
Guest User

Untitled

a guest
Aug 17th, 2024
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.13 KB | Source Code | 0 0
  1.  
  2. import os
  3. import re
  4. import time
  5. import shutil
  6. from jira import JIRA, JIRAError
  7. from datetime import datetime
  8. import pytz
  9.  
  10. # Set up JIRA connection options for the server
  11. jira_options = {'server': 'INSERT_SERVER_HERE'}
  12. # Authenticate using your JIRA token (replace 'INSERT_TOKEN_HERE' with your actual token)
  13. jira = JIRA(options=jira_options, token_auth='INSERT_TOKEN_HERE')
  14.  
  15. # Define the base directory where folders will be created
  16. base_dir = r"INSERT_PATH_HERE"
  17.  
  18. # Paths to the template PSD files that will be copied to the 'Source Files' subfolder
  19. template_dir = r'INSERT_PATH_HERE'
  20. template_1 = os.path.join(template_dir, "1.psd")
  21. template_2 = os.path.join(template_dir, "2.psd")
  22. template_3 = os.path.join(template_dir, "3.psd")
  23.  
  24. # Define your JIRA username
  25. username = 'INSERT_USERNAME_HERE'
  26.  
  27. # Function to sanitize folder names by replacing invalid characters with an underscore
  28. def sanitize_folder_name(name):
  29.     # Replace any characters that are not allowed in Windows folder names
  30.     return re.sub(r'[\\/*?:"<>|]', "_", name)
  31.  
  32. # Main function to create folders for JIRA tickets
  33. def create_ticket_folders():
  34.     print("Attempting to fetch open tickets...")
  35.     try:
  36.         # Fetch all open issues assigned to the user from JIRA
  37.         issues = jira.search_issues(f'assignee={username} AND status = "Open"')
  38.         print(f"Found {len(issues)} open tickets.")
  39.     except JIRAError as e:
  40.         # Handle error if the connection to JIRA fails
  41.         print(f"Failed to fetch issues from JIRA: {e}")
  42.         return
  43.    
  44.     for issue in issues:
  45.         ticket_number = issue.key  # Get the ticket number (e.g., ABC-1234)
  46.         prefix = ticket_number.split('-')[0]  # Get the prefix (e.g., ABC)
  47.         assigner = issue.fields.reporter.name  # Get the assigner's name
  48.         project_title = issue.fields.summary  # Get the project title (summary field)
  49.  
  50.         # Sanitize the project title to ensure it's a valid folder name
  51.         sanitized_project_title = sanitize_folder_name(project_title)
  52.        
  53.         # Get the ticket's creation date and format it into year and month
  54.         created_date = datetime.strptime(issue.fields.created[:10], '%Y-%m-%d')
  55.         year_folder = created_date.strftime('%Y')
  56.         month_folder = created_date.strftime('%B')
  57.  
  58.         # Create the year folder if it doesn't exist
  59.         year_folder_path = os.path.join(base_dir, year_folder)
  60.         if not os.path.exists(year_folder_path):
  61.             os.makedirs(year_folder_path, exist_ok=True)
  62.  
  63.         # Create the month folder within the year folder if it doesn't exist
  64.         month_folder_path = os.path.join(year_folder_path, month_folder)
  65.         if not os.path.exists(month_folder_path):
  66.             os.makedirs(month_folder_path, exist_ok=True)
  67.  
  68.         # Construct the full folder name including the ticket number and sanitized project title
  69.         folder_name = f"{ticket_number} - {sanitized_project_title}"
  70.         ticket_folder = os.path.join(month_folder_path, folder_name)
  71.        
  72.         if not os.path.exists(ticket_folder):
  73.             # Create the ticket folder if it doesn't exist
  74.             os.makedirs(ticket_folder, exist_ok=True)
  75.  
  76.             # Determine subfolders and template PSD file based on the assigner and ticket prefix
  77.             if assigner == 'username' or prefix == 'ABC':
  78.                 subfolders = ['Final Assets', 'Source Files', 'Raw Renders']
  79.                 psd_template = template_1
  80.             elif prefix == 'DEF':
  81.                 subfolders = ['Sony Final Assets', 'Microsoft Final Assets', 'Source Files']
  82.                 psd_template = template_2
  83.             else:
  84.                 subfolders = ['Final Assets', 'Source Files']
  85.                 psd_template = template_3
  86.            
  87.             # Create each subfolder and copy the appropriate PSD template into the 'Source Files' folder
  88.             for subfolder in subfolders:
  89.                 path = os.path.join(ticket_folder, subfolder)
  90.                 os.makedirs(path, exist_ok=True)
  91.                
  92.                 # Copy the PSD template to the 'Source Files' subfolder and rename it to the ticket number
  93.                 if subfolder == 'Source Files':
  94.                     psd_dest_path = os.path.join(path, f"{ticket_number}.psd")
  95.                     # Check if the file already exists to avoid overwriting
  96.                     if not os.path.exists(psd_dest_path):
  97.                         shutil.copy(psd_template, psd_dest_path)
  98.                         print(f"Copied {psd_template} to {psd_dest_path}")
  99.                     else:
  100.                         print(f"File {psd_dest_path} already exists. Skipping copy to avoid overwriting.")
  101.            
  102.             # Create a .md file with the project details from the JIRA ticket
  103.             md_file_path = os.path.join(ticket_folder, f"{ticket_number}.md")
  104.             # Check if the .md file already exists to avoid overwriting
  105.             if not os.path.exists(md_file_path):
  106.                 project_details = issue.fields.description or "No project details provided."
  107.                 with open(md_file_path, 'w', encoding='utf-8') as md_file:
  108.                     md_file.write(project_details)
  109.                     print(f"Created {md_file_path} with project details.")
  110.             else:
  111.                 print(f"Markdown file {md_file_path} already exists. Skipping creation to avoid overwriting.")
  112.            
  113.             print(f"Created folders for {ticket_number} under {year_folder}/{month_folder} with subfolders: {subfolders}")
  114.  
  115. # Run the function once when the script is executed
  116. if __name__ == "__main__":
  117.     create_ticket_folders()
  118.  
  119.     # The following code is commented out to allow the script to run only once per invocation.
  120.     # You can uncomment it if you want to revert back to continuous running mode.
  121.    
  122.     # def run_continuously():
  123.     #     try:
  124.     #         print("Running... Press Ctrl+C to stop. Script will run again in 60 minutes.")
  125.     #         while True:
  126.     #             create_ticket_folders()
  127.     #             time.sleep(3600)
  128.     #     except KeyboardInterrupt:
  129.     #         print("Script stopped by user.")
  130.    
  131.     # run_continuously()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement