-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathactions.py
224 lines (198 loc) · 7.15 KB
/
actions.py
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
from __future__ import annotations
import argparse
import os
import glob
import sys
import shutil
from typing import Any, NoReturn
# This is to make sure it can still finds its references.
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
class MaintenanceActions:
def __init__(self):
pass
def remove_logs(self, **kwargs: Any) -> None:
"""Remove all .log files from specified directories."""
directories = ["logs/debug", "logs/engine", "logs/gameplay", "logs/graphics", "logs/misc", "logs/ursina"]
for directory in directories:
log_files = glob.glob(os.path.join(directory, "*.log"))
for log_file in log_files:
try:
os.remove(log_file)
print(f"Removed {log_file}") # noqa
except Exception as e:
print(f"Failed to remove {log_file}: {e}") # noqa
def remove_pycache(self, **kwargs) -> NoReturn:
"""
Recursively remove all __pycache__ directories from the given base directory.
:param base_dir: The base directory to start the search.
"""
counter: int = 0
for root, dirs, files in os.walk(os.getcwd()):
for dir_name in dirs:
if dir_name == "__pycache__":
counter += 1
dir_path = os.path.join(root, dir_name)
shutil.rmtree(dir_path)
print(f"Removed {counter} __pycache__ directories.") # noqa
def generate_classes(self, **kwargs) -> NoReturn:
import os
# List of all civics with their names
civics = [
"IndividualRights",
"FreeMarket",
"RepresentativeDemocracy",
"SocialWelfare",
"CivilLiberties",
"GlobalCooperation",
"PatrioticEducation",
"CulturalPreservation",
"EconomicNationalism",
"MilitaryStrength",
"NationalSovereignty",
"NationalUnity",
"CollectiveOwnership",
"WorkersRights",
"UniversalHealthcare",
"FreeEducation",
"SocialEquality",
"StatePlanning",
"TotalitarianControl",
"StatePropaganda",
"Militarization",
"CorporateState",
"NationalPurity",
"LeaderWorship",
"ClassAbolition",
"CommunalLiving",
"CentralizedEconomy",
"ProletarianDictatorship",
"CollectivizedAgriculture",
"InternationalSolidarity",
"PrivateProperty",
"Entrepreneurship",
"FreeTrade",
"MinimalRegulation",
"CapitalAccumulation",
"MarketCompetition",
"ElectoralProcess",
"RuleOfLaw",
"SeparationOfPowers",
"HumanRights",
"ParticipatoryGovernance",
"TransparentGovernment",
"HereditaryRule",
"DivineRight",
"NobilitySystem",
"FeudalObligations",
"CentralizedAuthority",
"RoyalPatronage",
"ReligiousLaw",
"ClericalRule",
"MoralPolicing",
"FaithBasedEducation",
"DivineGovernance",
"ReligiousUnity",
"AutocraticRule",
"StateSurveillance",
"Censorship",
"Repression",
"Propaganda",
"CentralizedPower",
"EliteRule",
"EconomicControl",
"LimitedParticipation",
"WealthAccumulation",
"ExclusiveNetworks",
"PoliticalManipulation",
"SelfGovernance",
"MutualAid",
"DirectAction",
"Decentralization",
"VoluntaryAssociations",
"Autonomy",
"CorporateInfluence",
"LobbyingPower",
"BusinessPrivileges",
"EconomicFocus",
"RegulatoryCapture",
"CorporateGovernance",
"ForcedLabor",
"OwnershipRights",
"LaborExploitation",
"SocialHierarchy",
"Oppression",
"EconomicDependence",
"ReligiousDiscipline",
"MoralPurity",
"CommunitySurveillance",
"SimplifiedLiving",
"ReligiousGovernance",
"MoralLegislation",
"ExpertGovernance",
"ScientificManagement",
"InnovationFocus",
"DataDrivenPolicy",
"EfficientAdministration",
"Meritocracy",
"ReasonAndLogic",
"ScientificInquiry",
"SecularGovernance",
"EducationReform",
"EvidenceBasedPolicy",
"PhilosophicalDiscourse",
"CooperativeGovernance",
"SharedSovereignty",
"EconomicIntegration",
"CulturalExchange",
"CollectiveSecurity",
"UnifiedPolicy",
]
# Function to convert camel case to snake case
def camel_to_snake(name):
return "".join(["_" + i.lower() if i.isupper() else i for i in name]).lstrip("_")
# Directory to create files in
directory = "openciv/gameplay/cultures/core"
# Ensure the directory exists
os.makedirs(directory, exist_ok=True)
# Template for the civic class
template = """from openciv.gameplay.culture import Civic
from openciv.engine.managers.i18n import _t
class {civic}(Civic):
def __init__(self, *args, **kwargs):
super().__init__(
key="core.culture.civics.{civic_key}",
name=_t("content.culture.civics.core.{civic_key}.name"),
description=_t("content.culture.civics.core.{civic_key}.description"),
*args,
**kwargs,
)
"""
# Create an empty Python file for each civic using the template
for civic in civics:
civic_snake_case = camel_to_snake(civic)
filename = f"{directory}/{civic_snake_case}.py"
with open(filename, "w") as file:
file.write(template.format(civic=civic, civic_key=civic_snake_case))
print("Civic files have been created with the template.") # noqa
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Maintenance actions script")
parser.add_argument("function_name", type=str, help="The name of the function to call")
known_args, unknown_args = parser.parse_known_args()
kwargs = {}
for arg in unknown_args:
if arg.startswith("--"):
key, value = arg.split("=")
key = key.lstrip("--")
kwargs[key] = value
return known_args, kwargs
def main() -> None:
known_args, kwargs = parse_args()
action_name = known_args.function_name
actions = MaintenanceActions()
if hasattr(actions, action_name):
method = getattr(actions, action_name)
method(**kwargs)
else:
print(f"Function {action_name} not found.") # noqa
if __name__ == "__main__":
main()