@caioms/pre-git-auto-format 1.2.3 → 1.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/package.json +4 -5
  2. package/postinstall.js +28 -67
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@caioms/pre-git-auto-format",
3
- "version": "1.2.3",
3
+ "version": "1.2.5",
4
4
  "description": "Automatic pre-commit formatting with BiomeJS and lint-staged",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -21,11 +21,10 @@
21
21
  ],
22
22
  "author": "Caio Marques Silva",
23
23
  "license": "MIT",
24
- "dependencies": {
25
- "@caioms/biomejs-config": "^1.1.1"
26
- },
24
+ "dependencies": {},
27
25
  "peerDependencies": {
28
26
  "husky": "^9.0.0",
29
- "lint-staged": "^15.0.0"
27
+ "lint-staged": "^15.0.0",
28
+ "@caioms/biomejs-config": "latest"
30
29
  }
31
30
  }
package/postinstall.js CHANGED
@@ -2,19 +2,12 @@ const fs = require('fs');
2
2
  const path = require('path');
3
3
  const { execSync } = require('child_process');
4
4
 
5
- const YOUR_PACKAGE_NAME = '@caioms/pre-git-auto-format';
5
+ console.log('🚀 Configurando formatação automática pré-commit...\n')
6
6
 
7
- console.log('🚀 Configurando formatação automática pré-commit...\n');
8
-
9
- // Função para atualizar o pacote biome para a versão mais recente
10
- function updateBiomeConfig() {
11
- console.log('⚡ Verificando atualizações do @caioms/biomejs-config...');
12
- try {
13
- execSync('npm install @caioms/biomejs-config@latest', { stdio: 'inherit' });
14
- console.log('✅ @caioms/biomejs-config atualizado para a versão mais recente');
15
- } catch (error) {
16
- console.log('ℹ️ Usando versão atual do @caioms/biomejs-config');
17
- }
7
+ function getProjectRoot() {
8
+ const p = process.env.INIT_CWD || process.cwd();
9
+
10
+ return p
18
11
  }
19
12
 
20
13
  // Função para verificar se um pacote está instalado
@@ -40,18 +33,6 @@ function installPackage(packageName, isDev = true) {
40
33
  }
41
34
  }
42
35
 
43
- // Função para executar comando
44
- function runCommand(command, description) {
45
- console.log(`⚡ ${description}...`);
46
- try {
47
- execSync(command, { stdio: 'inherit' });
48
- console.log(`✅ ${description} concluído`);
49
- } catch (error) {
50
- console.error(`❌ Erro ao ${description.toLowerCase()}:`, error.message);
51
- throw error;
52
- }
53
- }
54
-
55
36
  // Função para criar/atualizar arquivo
56
37
  function createOrUpdateFile(filePath, content, description) {
57
38
  try {
@@ -72,7 +53,7 @@ function createOrUpdateFile(filePath, content, description) {
72
53
  function copyConfigFile(fileName, description) {
73
54
  try {
74
55
  const sourcePath = path.join(__dirname, fileName);
75
- const targetPath = path.join(process.cwd(), fileName);
56
+ const targetPath = path.join(getProjectRoot(), fileName);
76
57
 
77
58
  if (!fs.existsSync(targetPath)) {
78
59
  const content = fs.readFileSync(sourcePath, 'utf8');
@@ -88,9 +69,6 @@ function copyConfigFile(fileName, description) {
88
69
  }
89
70
 
90
71
  try {
91
- // 0. Atualizar pacote do biome para versão mais recente
92
- updateBiomeConfig();
93
-
94
72
  // 1. Verificar e instalar lint-staged
95
73
  if (!isPackageInstalled('lint-staged')) {
96
74
  installPackage('lint-staged');
@@ -108,39 +86,33 @@ try {
108
86
  // 3. Copiar configuração do lint-staged
109
87
  copyConfigFile('.lintstagedrc.json', 'Configuração do lint-staged');
110
88
 
111
- // 4. Inicializar husky (cria .husky se não existir)
112
- if (!fs.existsSync('.husky')) {
113
- runCommand('npx husky init', 'Inicializando husky');
114
- } else {
115
- console.log(' Husky está inicializado');
116
- }
117
-
118
- // 5. Verificar se existe repositório git
119
- if (!fs.existsSync('.git')) {
120
- console.log('⚠️ Repositório git não encontrado. Execute "git init" primeiro.');
89
+ const gitPath = path.join(getProjectRoot(), '.git');
90
+
91
+ if (!fs.existsSync(gitPath)) {
92
+ console.log('\n⚠️ ATENÇÃO: Repositório git não encontrado em:', gitPath);
93
+ console.log('ℹ️ Conteúdo do diretório:', fs.readdirSync(getProjectRoot()).join(', '));
121
94
  console.log('ℹ️ Pulando configuração dos git hooks...');
122
95
 
123
- // Ainda configura lint-staged para uso manual
124
- console.log('✅ lint-staged configurado (use "npx lint-staged" manualmente)');
125
-
126
- // Pula configuração do husky e git hooks
127
- console.log('\n🎉 Configuração parcial concluída!');
128
- console.log('\n📋 O que foi configurado:');
129
- console.log(' • BiomeJS (via @caioms/biomejs-config)');
130
- console.log(' • lint-staged (para uso manual)');
131
- console.log('\n⚡ Para ativar os git hooks:');
132
- console.log(' 1. Execute "git init" no seu projeto');
133
- console.log(' 2. Execute "npx husky init"');
134
- console.log(' 3. Execute "echo \'npx lint-staged\' > .husky/pre-commit"');
135
- console.log('\n🔧 Scripts disponíveis:');
136
- console.log(' • npm run lint - Verificar código');
137
- console.log(' • npm run format - Formatar código');
138
- console.log(' • npx lint-staged - Formatar arquivos staged');
96
+ // [Manter resto do código de fallback]
139
97
  return;
140
98
  }
141
99
 
100
+ // Agora sabemos que .git existe, podemos inicializar o husky com segurança
101
+ if (!fs.existsSync(path.join(getProjectRoot(), '.husky'))) {
102
+ console.log('⚡ Inicializando husky...');
103
+ try {
104
+ execSync('npx husky init', { stdio: 'inherit', cwd: getProjectRoot() });
105
+ console.log('✅ Husky inicializado com sucesso');
106
+ } catch (error) {
107
+ console.error('❌ Falha ao inicializar husky:', error.message);
108
+ console.log('ℹ️ Tente executar manualmente: npx husky init');
109
+ }
110
+ } else {
111
+ console.log('✅ Husky já está inicializado');
112
+ }
113
+
142
114
  // 6. Configurar pre-commit hook
143
- const preCommitPath = path.join('.husky', 'pre-commit');
115
+ const preCommitPath = path.join(getProjectRoot(), '.husky', 'pre-commit');
144
116
  // const preCommitContent = '#!/usr/bin/env sh\n. "$(dirname -- "$0")/_/husky.sh"\n\nnpx lint-staged\n';
145
117
  const preCommitContent = 'npx lint-staged';
146
118
 
@@ -153,24 +125,13 @@ try {
153
125
  // Ignora erro de chmod no Windows
154
126
  }
155
127
  }
156
- // else {
157
- // // Verificar se já contém o comando lint-staged
158
- // const existingContent = fs.readFileSync(preCommitPath, 'utf8');
159
- // if (!existingContent.includes('npx lint-staged')) {
160
- // // Adicionar ao final do arquivo existente
161
- // const updatedContent = existingContent.trim() + '\n\nnpx lint-staged\n';
162
- // createOrUpdateFile(preCommitPath, updatedContent, 'Hook pre-commit (atualizado)');
163
- // } else {
164
- // console.log('ℹ️ Hook pre-commit já contém lint-staged - nenhuma alteração necessária');
165
- // }
166
- // }
167
128
  else {
168
129
  // Always overwrite the content
169
130
  createOrUpdateFile(preCommitPath, preCommitContent, 'Hook pre-commit (updated)');
170
131
  }
171
132
 
172
133
  // 7. Verificar package.json para adicionar scripts úteis (opcional)
173
- const packageJsonPath = path.join(process.cwd(), 'package.json');
134
+ const packageJsonPath = path.join(getProjectRoot(), 'package.json');
174
135
  if (fs.existsSync(packageJsonPath)) {
175
136
  try {
176
137
  const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));