@caioms/pre-git-auto-format 1.2.1 → 1.2.4

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 +28 -28
  2. package/postinstall.js +36 -36
package/package.json CHANGED
@@ -1,30 +1,30 @@
1
1
  {
2
- "name": "@caioms/pre-git-auto-format",
3
- "version": "1.2.1",
4
- "description": "Automatic pre-commit formatting with BiomeJS and lint-staged",
5
- "main": "index.js",
6
- "scripts": {
7
- "postinstall": "node postinstall.js"
8
- },
9
- "files": [
10
- ".lintstagedrc.json",
11
- "postinstall.js"
12
- ],
13
- "keywords": [
14
- "lint-staged",
15
- "husky",
16
- "biome",
17
- "pre-commit",
18
- "formatting",
19
- "git-hooks"
20
- ],
21
- "author": "Caio Marques Silva",
22
- "license": "MIT",
23
- "dependencies": {
24
- "@caioms/biomejs-config": "latest"
25
- },
26
- "peerDependencies": {
27
- "lint-staged": "^15.0.0",
28
- "husky": "^9.0.0"
29
- }
2
+ "name": "@caioms/pre-git-auto-format",
3
+ "version": "1.2.4",
4
+ "description": "Automatic pre-commit formatting with BiomeJS and lint-staged",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "postinstall": "node postinstall.js",
8
+ "prepare": "husky"
9
+ },
10
+ "files": [
11
+ ".lintstagedrc.json",
12
+ "postinstall.js"
13
+ ],
14
+ "keywords": [
15
+ "lint-staged",
16
+ "husky",
17
+ "biome",
18
+ "pre-commit",
19
+ "formatting",
20
+ "git-hooks"
21
+ ],
22
+ "author": "Caio Marques Silva",
23
+ "license": "MIT",
24
+ "dependencies": {},
25
+ "peerDependencies": {
26
+ "husky": "^9.0.0",
27
+ "lint-staged": "^15.0.0",
28
+ "@caioms/biomejs-config": "1.1.5"
29
+ }
30
30
  }
package/postinstall.js CHANGED
@@ -2,9 +2,13 @@ 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');
7
+ function getProjectRoot() {
8
+ const p = process.env.INIT_CWD || process.cwd();
9
+
10
+ return p
11
+ }
8
12
 
9
13
  // Função para verificar se um pacote está instalado
10
14
  function isPackageInstalled(packageName) {
@@ -29,18 +33,6 @@ function installPackage(packageName, isDev = true) {
29
33
  }
30
34
  }
31
35
 
32
- // Função para executar comando
33
- function runCommand(command, description) {
34
- console.log(`⚡ ${description}...`);
35
- try {
36
- execSync(command, { stdio: 'inherit' });
37
- console.log(`✅ ${description} concluído`);
38
- } catch (error) {
39
- console.error(`❌ Erro ao ${description.toLowerCase()}:`, error.message);
40
- throw error;
41
- }
42
- }
43
-
44
36
  // Função para criar/atualizar arquivo
45
37
  function createOrUpdateFile(filePath, content, description) {
46
38
  try {
@@ -61,7 +53,7 @@ function createOrUpdateFile(filePath, content, description) {
61
53
  function copyConfigFile(fileName, description) {
62
54
  try {
63
55
  const sourcePath = path.join(__dirname, fileName);
64
- const targetPath = path.join(process.cwd(), fileName);
56
+ const targetPath = path.join(getProjectRoot(), fileName);
65
57
 
66
58
  if (!fs.existsSync(targetPath)) {
67
59
  const content = fs.readFileSync(sourcePath, 'utf8');
@@ -94,21 +86,35 @@ try {
94
86
  // 3. Copiar configuração do lint-staged
95
87
  copyConfigFile('.lintstagedrc.json', 'Configuração do lint-staged');
96
88
 
97
- // 4. Inicializar husky (cria .husky se não existir)
98
- if (!fs.existsSync('.husky')) {
99
- runCommand('npx husky init', 'Inicializando husky');
100
- } else {
101
- console.log(' Husky está inicializado');
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(', '));
94
+ console.log('ℹ️ Pulando configuração dos git hooks...');
95
+
96
+ // [Manter resto do código de fallback]
97
+ return;
102
98
  }
103
99
 
104
- // 5. Verificar se existe repositório git
105
- if (!fs.existsSync('.git')) {
106
- console.log('⚠️ Repositório git não encontrado. Execute "git init" primeiro.');
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');
107
112
  }
108
113
 
109
114
  // 6. Configurar pre-commit hook
110
- const preCommitPath = path.join('.husky', 'pre-commit');
111
- const preCommitContent = '#!/usr/bin/env sh\n. "$(dirname -- "$0")/_/husky.sh"\n\nnpx lint-staged\n';
115
+ const preCommitPath = path.join(getProjectRoot(), '.husky', 'pre-commit');
116
+ // const preCommitContent = '#!/usr/bin/env sh\n. "$(dirname -- "$0")/_/husky.sh"\n\nnpx lint-staged\n';
117
+ const preCommitContent = 'npx lint-staged';
112
118
 
113
119
  if (!fs.existsSync(preCommitPath)) {
114
120
  createOrUpdateFile(preCommitPath, preCommitContent, 'Hook pre-commit');
@@ -118,20 +124,14 @@ try {
118
124
  } catch (error) {
119
125
  // Ignora erro de chmod no Windows
120
126
  }
121
- } else {
122
- // Verificar se já contém o comando lint-staged
123
- const existingContent = fs.readFileSync(preCommitPath, 'utf8');
124
- if (!existingContent.includes('npx lint-staged')) {
125
- // Adicionar ao final do arquivo existente
126
- const updatedContent = existingContent.trim() + '\n\nnpx lint-staged\n';
127
- createOrUpdateFile(preCommitPath, updatedContent, 'Hook pre-commit (atualizado)');
128
- } else {
129
- console.log('ℹ️ Hook pre-commit já contém lint-staged - nenhuma alteração necessária');
130
- }
131
127
  }
128
+ else {
129
+ // Always overwrite the content
130
+ createOrUpdateFile(preCommitPath, preCommitContent, 'Hook pre-commit (updated)');
131
+ }
132
132
 
133
133
  // 7. Verificar package.json para adicionar scripts úteis (opcional)
134
- const packageJsonPath = path.join(process.cwd(), 'package.json');
134
+ const packageJsonPath = path.join(getProjectRoot(), 'package.json');
135
135
  if (fs.existsSync(packageJsonPath)) {
136
136
  try {
137
137
  const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));