Repository navigation
Expand file tree
/
Copy pathsetup_prettier
More file actions
201 lines (169 loc) · 6.46 KB
/
Copy pathsetup_prettier
File metadata and controls
201 lines (169 loc) · 6.46 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
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
#!/usr/bin/env python3
import json
import os
import subprocess
import sys
from pathlib import Path
def detect_project_type(project_dir):
package_json_path = os.path.join(project_dir, 'package.json')
if os.path.exists(package_json_path):
with open(package_json_path) as f:
try:
data = json.load(f)
dependencies = {**data.get('dependencies', {}), **data.get('devDependencies', {})}
if 'vue' in dependencies:
return 'vue'
elif 'react' in dependencies:
return 'react'
return 'javascript'
except json.JSONDecodeError:
return 'javascript'
return 'javascript'
def detect_package_manager(project_dir):
if os.path.exists(os.path.join(project_dir, 'yarn.lock')):
return 'yarn'
return 'npm'
def run_command(command, project_dir):
try:
subprocess.run(command, shell=True, check=True, cwd=project_dir)
return True
except subprocess.CalledProcessError:
print(f"Error running command: {command}")
return False
def update_or_create_json(filepath, updates):
try:
if os.path.exists(filepath):
with open(filepath) as f:
try:
data = json.load(f)
except json.JSONDecodeError:
data = {}
else:
data = {}
def deep_update(d, u):
for k, v in u.items():
if isinstance(v, dict) and k in d and isinstance(d[k], dict):
deep_update(d[k], v)
else:
d[k] = v
return d
data = deep_update(data, updates)
with open(filepath, 'w') as f:
json.dump(data, f, indent=2, sort_keys=True)
except Exception as e:
print(f"Error updating {filepath}: {str(e)}")
raise
def create_prettier_config(project_dir, project_type):
prettier_config = {
"semi": False,
"tabWidth": 2,
"singleQuote": True,
"printWidth": 80,
"trailingComma": "es5"
}
# Add framework-specific settings
if project_type == 'vue':
prettier_config["vueIndentScriptAndStyle"] = True
update_or_create_json(os.path.join(project_dir, '.prettierrc'), prettier_config)
def update_package_json(project_dir, project_type):
file_patterns = "\"**/*.{js,jsx,ts,tsx"
if project_type == 'vue':
file_patterns += ",vue"
file_patterns += ",css,scss}\""
package_updates = {
"scripts": {
"format": f"prettier --write {file_patterns}",
"format:check": f"prettier --check {file_patterns}",
"prepare": "husky install"
},
"lint-staged": {
"*.{js,jsx,ts,tsx,css,scss}": ["prettier --write"]
}
}
# Add framework-specific patterns
if project_type == 'vue':
package_updates["lint-staged"]["*.vue"] = ["prettier --write"]
elif project_type == 'react':
package_updates["lint-staged"]["*.{jsx,tsx}"] = ["prettier --write"]
update_or_create_json(os.path.join(project_dir, 'package.json'), package_updates)
def create_prettierignore(project_dir):
ignore_content = """dist
build
node_modules
coverage
*.log
"""
with open(os.path.join(project_dir, '.prettierignore'), 'w') as f:
f.write(ignore_content)
def update_eslint_config(project_dir, project_type):
eslint_updates = {
"extends": ["plugin:prettier/recommended"],
"plugins": ["prettier"],
"rules": {
"prettier/prettier": "error"
}
}
# Add framework-specific rules
if project_type == 'vue':
eslint_updates["rules"]["vue/multi-word-component-names"] = ["error", {
"ignores": ["Game", "Play"]
}]
for config_name in ['.eslintrc.json', '.eslintrc.js', '.eslintrc']:
config_file = os.path.join(project_dir, config_name)
if os.path.exists(config_file):
if config_file.endswith('.js'):
print("Please manually add these ESLint configurations:")
print(json.dumps(eslint_updates, indent=2))
return
update_or_create_json(config_file, eslint_updates)
return
update_or_create_json(os.path.join(project_dir, '.eslintrc.json'), {
"env": {
"browser": True,
"es2021": True
},
**eslint_updates
})
def main():
if len(sys.argv) != 2:
print("Usage: setup_prettier <project_directory>")
sys.exit(1)
project_dir = os.path.abspath(sys.argv[1])
if not os.path.exists(project_dir):
print(f"Directory does not exist: {project_dir}")
sys.exit(1)
if not os.path.exists(os.path.join(project_dir, 'package.json')):
print(f"No package.json found in {project_dir}. Is this a Node.js project?")
sys.exit(1)
project_type = detect_project_type(project_dir)
package_manager = detect_package_manager(project_dir)
print(f"Detected project type: {project_type}")
print(f"Detected package manager: {package_manager}")
dependencies = ["prettier", "eslint-plugin-prettier", "husky", "lint-staged"]
# Add framework-specific dependencies
if project_type == 'vue':
dependencies.append("@vue/eslint-config-prettier")
elif project_type == 'react':
dependencies.append("eslint-config-prettier")
install_command = {
'npm': f"npm install --save-dev {' '.join(dependencies)}",
'yarn': f"yarn add --dev {' '.join(dependencies)}"
}[package_manager]
print("Installing dependencies...")
if not run_command(install_command, project_dir):
return
print("Creating/updating configuration files...")
create_prettier_config(project_dir, project_type)
create_prettierignore(project_dir)
update_package_json(project_dir, project_type)
update_eslint_config(project_dir, project_type)
print("Setting up husky...")
prepare_command = 'npm run prepare' if package_manager == 'npm' else 'yarn prepare'
run_command(prepare_command, project_dir)
print("Creating pre-commit hook...")
husky_dir = os.path.join(project_dir, '.husky')
os.makedirs(husky_dir, exist_ok=True)
run_command("npx husky add .husky/pre-commit \"npx lint-staged\"", project_dir)
print("\nPrettier setup complete! You may need to restart your IDE for changes to take effect.")
if __name__ == "__main__":
main()