-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbranch
More file actions
executable file
·146 lines (123 loc) · 5.08 KB
/
branch
File metadata and controls
executable file
·146 lines (123 loc) · 5.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#!/usr/bin/env python3
#ddev-generated
#annertech-ddev
## Description: Create a git branch from a Teamwork url/id
## Usage: branch
## Example: ddev branch
## Aliases: branch, br
# Given a Teamwork url or ID, and optional name, creates a new branch
#
# Prompts for a Teamwork url/id if none provided, and then for an optional branch name.
#
# Given the following url and string:
#
# - https://projects.YOURCOMPANY.com/app/tasks/17360561
# - qa_rework
#
# the script will create a git branch with the following name:
#
# 202409_T-17360561__new_branching_patterns
#
# Where:
#
# - 17360561 is the Teamwork card identifier
# - 2024 is the year
# - 09 is the current month
# - new_branching_patterns is the description provided
#
# Can be called like:
#
# ddev branch
# ddev branch https://projects.YOURCOMPANY.com/app/tasks/17360561 "example task"
# ddev branch https://projects.YOURCOMPANY.com/app/tasks/17360561
# ddev branch 17360561
# ddev branch 17360561 example_task
import sys
from urllib.parse import urlparse
from operator import attrgetter
import datetime
import subprocess
import random
# Function to extract the ID from the URL or use the provided ID directly
def extract_id(input_value):
if input_value.isdigit():
return input_value # If it's purely numeric, treat it as the ID directly
else:
fragment, path = attrgetter('fragment', 'path')(urlparse(input_value))
card_path = fragment if path == '/' and fragment else path
return card_path.split('/')[-1] if card_path.split('/')[-1].isdigit() else None
# Get current year and month
current_year = datetime.datetime.now().year
current_month = datetime.datetime.now().month
# Branches that should not be used as a base for new branches
FORBIDDEN_BASE_BRANCHES = ['dev', 'develop', 'development', 'stage', 'staging']
# Branches that should remind user to pull before branching
PULL_REMINDER_BRANCHES = ['main', 'master']
# Warning quotes for forbidden branch attempts
WARNING_QUOTES = [
"And you call yourself a Rocket Scientist!",
"Are you on drugs?",
"Your mind just hasn't been the same since the electro-shock, has it?",
"Just what do you think you're doing Dave?",
"It can only be attributed to human error.",
"That's something I cannot allow to happen.",
"Take a stress pill and think things over.",
"This mission is too important for me to allow you to jeopardize it.",
]
# Function to get the current git branch
def get_current_branch():
try:
result = subprocess.run(["git", "rev-parse", "--abbrev-ref", "HEAD"],
capture_output=True, text=True, check=True)
return result.stdout.strip()
except subprocess.CalledProcessError:
return None
# Main script
def main():
# Check if the URL/ID is provided as a command-line argument
if len(sys.argv) > 1:
input_value = sys.argv[1]
else:
# Ask for the URL/ID if not provided
input_value = input("Enter the URL or ID: ").strip()
# Validate the ID from the URL or use it directly if it's an ID
task_id = extract_id(input_value)
if not task_id:
print("Error: No valid URL or ID provided.")
sys.exit(1)
# Check if the custom text is provided as a command-line argument
if len(sys.argv) > 2:
custom_text = sys.argv[2]
else:
# Prompt for custom text if not provided
custom_text = input("Enter task description: ").strip()
# Replace spaces with hyphens and make the text Git-friendly
custom_text = custom_text.replace(" ", "-")
# Create the branch name in the format YEAR/MONTH/ID-description (without the extra dash if no description)
if custom_text:
branch_name = f"{current_year}{current_month:02}_T-{task_id}__{custom_text}"
else:
branch_name = f"{current_year}{current_month:02}_T-{task_id}"
# Ensure only valid characters are in the branch name
branch_name = "".join(c for c in branch_name if c.isalnum() or c in ['-', '_', '.'])
# Check if current branch is a forbidden base branch
current_branch = get_current_branch()
if current_branch and current_branch in FORBIDDEN_BASE_BRANCHES:
print(random.choice(WARNING_QUOTES))
print(f"You are on '{current_branch}' which should not be used as a base branch.")
print(f"If you are sure about the catastrophic consequences of your action then proceed manually:")
print(f" git checkout -b {branch_name}")
sys.exit(1)
# Remind user to pull from origin when on main/master
if current_branch and current_branch in PULL_REMINDER_BRANCHES:
print(f"\033[1mReminder: Make sure you have pulled the latest changes from origin/{current_branch}\033[0m")
# Print the branch name
print(f"Creating new Git branch: {branch_name}")
# Execute git command to create and switch to the new branch
try:
subprocess.run(["git", "checkout", "-b", branch_name], check=True)
print(f"Successfully created and switched to branch '{branch_name}'")
except subprocess.CalledProcessError as e:
print(f"Error creating the branch: {e}")
if __name__ == "__main__":
main()