@gilbert_oliveira/commit-wizard 2.12.2-canary.1 → 2.12.3-canary.2
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.
- package/README.md +2 -0
- package/dist/commit-wizard.js +85 -65
- package/package.json +4 -2
- package/src/bin/commit-wizard.ts +12 -11
- package/src/cache/analysis.ts +210 -0
- package/src/commands/commit.ts +410 -0
- package/src/commands/init.ts +17 -0
- package/src/commands/version.ts +5 -0
- package/src/commitlint/index.ts +253 -0
- package/src/config/index.ts +25 -0
- package/src/core/cache.ts +13 -209
- package/src/core/index.ts +3 -385
- package/src/core/openai.ts +18 -465
- package/src/core/smart-split.ts +7 -722
- package/src/git/diff-filter.ts +118 -0
- package/src/pipeline/enforce.ts +152 -0
- package/src/pipeline/generate.ts +116 -0
- package/src/pipeline/split.ts +737 -0
- package/src/pipeline/types.ts +26 -0
- package/src/prompt/builder.ts +61 -0
- package/src/prompt/system.ts +69 -0
- package/src/prompt/templates.ts +172 -0
- package/src/prompt/types.ts +4 -0
- package/src/providers/factory.ts +18 -0
- package/src/providers/openai.ts +367 -0
- package/src/providers/types.ts +11 -0
- package/src/types/clack.d.ts +49 -4
- package/src/ui/format.ts +33 -0
- package/src/ui/index.ts +9 -5
- package/src/ui/smart-split.ts +1 -1
- package/src/ui/spinner.ts +23 -0
- package/src/ui/theme.ts +17 -0
- package/src/utils/args.ts +16 -8
- package/src/utils/hash.ts +9 -0
- package/src/utils/version.ts +11 -6
package/README.md
CHANGED
|
@@ -55,6 +55,8 @@ commit-wizard --yes # Aceitar automaticamente
|
|
|
55
55
|
commit-wizard --smart-split # Smart Split com IA
|
|
56
56
|
commit-wizard --split # Split manual por arquivo
|
|
57
57
|
commit-wizard --dry-run # Visualizar sem commitar
|
|
58
|
+
commit-wizard --validate # Habilitar validação com commitlint
|
|
59
|
+
commit-wizard --init-commitlint # Criar configuração padrão do commitlint
|
|
58
60
|
```
|
|
59
61
|
|
|
60
62
|
## ⚙️ Configuração
|
package/dist/commit-wizard.js
CHANGED
|
@@ -1,22 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`).filter(
|
|
4
|
-
`).filter(
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
${n}
|
|
12
|
-
|
|
13
|
-
Diff:
|
|
14
|
-
\`\`\`
|
|
15
|
-
${a}
|
|
16
|
-
\`\`\`
|
|
17
|
-
|
|
18
|
-
Mensagem:`}function He(e,t){let o={pt:{conventional:`- Use formato: tipo(escopo): descri\xE7\xE3o
|
|
19
|
-
- Tipos v\xE1lidos: feat, fix, docs, style, refactor, test, chore, build, ci
|
|
2
|
+
var Et=Object.defineProperty;var x=(e,t)=>()=>(e&&(t=e(e=0)),t);var k=(e,t)=>{for(var i in t)Et(e,i,{get:t[i],enumerable:!0})};import fi from"path";import{fileURLToPath as gi}from"url";var f=x(()=>{"use strict"});import{existsSync as Te,readFileSync as Oe}from"fs";import{join as ze}from"path";function Ge(e){let t;try{t=ze(process.cwd(),".commit-wizardrc")}catch{t="/tmp/.commit-wizardrc"}let i=ze(process.env.HOME||process.env.USERPROFILE||"/tmp",".commit-wizardrc"),o={...Rt};try{if(Te(i)){let n=Oe(i,"utf-8"),r=JSON.parse(n);o=Le(o,r)}}catch{console.warn("\u26A0\uFE0F Erro ao ler configura\xE7\xE3o global: Erro desconhecido")}let s=e||t;try{if(Te(s)){let n=Oe(s,"utf-8"),r=JSON.parse(n);o=Le(o,r)}}catch{console.warn("\u26A0\uFE0F Erro ao ler .commit-wizardrc: Erro desconhecido")}return o.openai.apiKey=process.env.OPENAI_API_KEY,process.env.COMMIT_WIZARD_DEBUG,process.env.COMMIT_WIZARD_DRY_RUN==="true"&&(o.dryRun=!0),o}function Le(e,t){return{...e,...t,openai:{...e.openai,...t.openai},smartSplit:{...e.smartSplit,...t.smartSplit},cache:{...e.cache,...t.cache},commitlint:{...e.commitlint,...t.commitlint}}}function De(e){let t=[];return ke.includes(e.provider)||t.push(`provider deve ser um dos suportados: ${ke.join(", ")}`),e.openai.apiKey||t.push("OPENAI_API_KEY n\xE3o encontrada nas vari\xE1veis de ambiente"),(e.openai.maxTokens<10||e.openai.maxTokens>4e3)&&t.push("maxTokens deve estar entre 10 e 4000"),(e.openai.temperature<0||e.openai.temperature>2)&&t.push("temperature deve estar entre 0 e 2"),["pt","en","es","fr","de","it","ja","ko","zh"].includes(e.language)||t.push("language deve ser um idioma suportado (pt, en, es, fr, de, it, ja, ko, zh)"),["conventional","simple","detailed"].includes(e.commitStyle)||t.push("commitStyle deve ser conventional, simple ou detailed"),e.smartSplit.minGroupSize<1&&t.push("smartSplit.minGroupSize deve ser pelo menos 1"),(e.smartSplit.maxGroups<1||e.smartSplit.maxGroups>10)&&t.push("smartSplit.maxGroups deve estar entre 1 e 10"),(e.smartSplit.confidenceThreshold<0||e.smartSplit.confidenceThreshold>1)&&t.push("smartSplit.confidenceThreshold deve estar entre 0 e 1"),e.cache.ttl<1&&t.push("cache.ttl deve ser pelo menos 1 minuto"),e.cache.maxSize<1&&t.push("cache.maxSize deve ser pelo menos 1"),t}var Rt,ke,_e=x(()=>{"use strict";f();Rt={provider:"openai",openai:{model:"gpt-4o",maxTokens:150,temperature:.7,timeout:3e4,retries:2},language:"pt",commitStyle:"conventional",autoCommit:!1,splitCommits:!1,dryRun:!1,smartSplit:{enabled:!0,minGroupSize:1,maxGroups:5,confidenceThreshold:.7},cache:{enabled:!0,ttl:60,maxSize:100},commitlint:{enabled:!0}};ke=["openai"]});var R={};k(R,{escapeShellArg:()=>N,executeCommit:()=>F,executeFileCommit:()=>G,getDiffStats:()=>ie,getFileDiff:()=>Ft,getGitStatus:()=>te,isGitRepository:()=>ee});import{execSync as M}from"child_process";function N(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function ee(){try{return M("git rev-parse --git-dir",{stdio:"ignore"}),!0}catch{return!1}}function te(){try{let t=M("git diff --cached --name-only",{encoding:"utf-8",stdio:"pipe"}).trim().split(`
|
|
3
|
+
`).filter(o=>o.length>0),i=t.length>0?M("git diff --cached",{encoding:"utf-8",stdio:"pipe"}):"";return{hasStaged:t.length>0,stagedFiles:t,diff:i.trim()}}catch(e){throw new Error(`Erro ao obter status do Git: ${e instanceof Error?e.message:"Erro desconhecido"}`)}}function Ft(e){try{return M(`git diff --cached -- "${e}"`,{encoding:"utf-8",stdio:"pipe"})}catch(t){throw new Error(`Erro ao obter diff do arquivo ${e}: ${t instanceof Error?t.message:"Erro desconhecido"}`)}}function F(e){try{let t=N(e);return M(`git commit -m ${t}`,{stdio:"pipe"}),{success:!0,hash:M("git rev-parse HEAD",{encoding:"utf-8",stdio:"pipe"}).trim(),message:e}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Erro desconhecido ao executar commit"}}}function G(e,t){try{let i=N(t),o=N(e);return M(`git commit ${o} -m ${i}`,{stdio:"pipe"}),{success:!0,hash:M("git rev-parse HEAD",{encoding:"utf-8",stdio:"pipe"}).trim(),message:t}}catch(i){return{success:!1,error:i instanceof Error?i.message:"Erro desconhecido ao executar commit do arquivo"}}}function ie(){try{let t=M("git diff --cached --numstat",{encoding:"utf-8",stdio:"pipe"}).trim().split(`
|
|
4
|
+
`).filter(s=>s.length>0),i=0,o=0;return t.forEach(s=>{let[n,r]=s.split(" ");n&&n!=="-"&&(i+=parseInt(n)||0),r&&r!=="-"&&(o+=parseInt(r)||0)}),{added:i,removed:o,files:t.length}}catch{return{added:0,removed:0,files:0}}}var A=x(()=>{"use strict";f()});function Ue(e,t){if(!t)return{message:e,enforced:!1,violations:[]};let i=e.split(`
|
|
5
|
+
`),o=i[0]??"",s=i.slice(1).join(`
|
|
6
|
+
`),n=!1,r=[];if(t.headerMaxLength!=null&&o.length>t.headerMaxLength){let u=t.headerMaxLength;r.push(`header excedeu ${u} caracteres (${o.length})`);let c=o.match(/^(\w+(?:\([^)]*\))?:\s*)([\s\S]*)/);if(c){let a=c[1],l=c[2],p=u-a.length;o=p>0?a+l.substring(0,p):o.substring(0,u)}else o=o.substring(0,u);n=!0}if(t.subjectFullStop){let{condition:u,value:c}=t.subjectFullStop,a=c??".";u==="never"&&o.endsWith(a)?(o=o.slice(0,-a.length),r.push("ponto final removido do subject"),n=!0):u==="always"&&!o.endsWith(a)&&(o=o+a,r.push("ponto final adicionado ao subject"),n=!0)}if(t.subjectCase){let{condition:u,cases:c}=t.subjectCase,a=It(o);if(u==="always"&&c.length>0){let l=c[0],p=Ne(o,l);p!==o&&(r.push(`subject convertido para ${l}`),o=p,n=!0)}else if(u==="never"&&a){for(let l of c)if(Pt(a,l)){let p=Ne(o,"lower-case");p!==o&&(r.push(`subject case corrigido (${l} n\xE3o permitido)`),o=p,n=!0);break}}}return{message:s?`${o}
|
|
7
|
+
${s}`:o,enforced:n,violations:r}}function It(e){let t=e.match(/^\w+(?:\([^)]*\))?:\s*([\s\S]*)/);return t?t[1]??e:e}function Ne(e,t){let i=e.match(/^(\w+(?:\([^)]*\))?:\s*)([\s\S]*)/);if(!i)return qe(e,t);let o=i[1],s=i[2];return o+qe(s,t)}function qe(e,t){switch(t){case"lower-case":return e.toLowerCase();case"upper-case":return e.toUpperCase();case"sentence-case":return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase();case"start-case":return e.replace(/\b\w/g,i=>i.toUpperCase());default:return e}}function Pt(e,t){switch(t){case"upper-case":return e===e.toUpperCase()&&e!==e.toLowerCase();case"lower-case":return e===e.toLowerCase();case"sentence-case":return e.charAt(0)===e.charAt(0).toUpperCase()&&e.slice(1)===e.slice(1).toLowerCase();case"start-case":return e.split(" ").every(i=>i.length===0||i[0]===i[0]?.toUpperCase());default:return!1}}var Ve=x(()=>{"use strict";f()});function Be(e,t,i){let o=t==="pt",s=[];if(e==="conventional"){s.push(o?"- Use formato: tipo(escopo): descri\xE7\xE3o":"- Use format: type(scope): description");let n=i.typeEnum?.join(", ")??D;s.push(o?`- Tipos v\xE1lidos: ${n}`:`- Valid types: ${n}`);let r=i.headerMaxLength??72;s.push(o?`- OBRIGAT\xD3RIO: primeira linha deve ter no m\xE1ximo ${r} caracteres (regra header-max-length do commitlint)`:`- REQUIRED: first line must not exceed ${r} characters (commitlint header-max-length rule)`);let m=i.typeEnum?.[0]??"feat",u=`${m}(auth): adicionar valida\xE7\xE3o de email`,c=`${m}(auth): add email validation`;if(o&&u.length<=r?s.push(`- Exemplo: "${u}"`):!o&&c.length<=r&&s.push(`- Example: "${c}"`),i.subjectCase){let{condition:a,cases:l}=i.subjectCase,p=l.join(", ");a==="never"?s.push(o?`- Subject nunca em: ${p}`:`- Subject must never be: ${p}`):a==="always"&&s.push(o?`- Subject deve estar em: ${p}`:`- Subject must be in: ${p}`)}if(i.subjectFullStop){let{condition:a,value:l}=i.subjectFullStop,p=l??".";a==="never"?s.push(o?`- N\xE3o termine o subject com "${p}"`:`- Do not end subject with "${p}"`):a==="always"&&s.push(o?`- Termine o subject com "${p}"`:`- End subject with "${p}"`)}i.bodyLeadingBlank===!0&&s.push(o?"- Adicione uma linha em branco entre o header e o body":"- Add a blank line between header and body"),i.scopeEnum&&i.scopeEnum.length>0&&s.push(o?`- Escopos permitidos: ${i.scopeEnum.join(", ")}`:`- Allowed scopes: ${i.scopeEnum.join(", ")}`)}else if(e==="simple"){let n=i.headerMaxLength??50;o?(s.push("- Use formato simples e direto"),s.push("- Comece com verbo no infinitivo"),s.push('- Exemplo: "corrigir valida\xE7\xE3o de formul\xE1rio"'),s.push(`- M\xE1ximo ${n} caracteres`)):(s.push("- Use simple and direct format"),s.push("- Start with imperative verb"),s.push('- Example: "fix form validation"'),s.push(`- Maximum ${n} characters`))}else{let n=i.headerMaxLength??72;o?(s.push(`- Primeira linha: resumo em at\xE9 ${n} caracteres`),s.push("- Se necess\xE1rio, adicione corpo explicativo"),s.push("- Use presente do indicativo"),s.push("- Seja descritivo mas conciso")):(s.push(`- First line: summary under ${n} characters`),s.push("- Add explanatory body if needed"),s.push("- Use imperative mood"),s.push("- Be descriptive but concise"))}return s.join(`
|
|
8
|
+
`)}function Je(e,t){let i={pt:{conventional:`- Use formato: tipo(escopo): descri\xE7\xE3o
|
|
9
|
+
- Tipos v\xE1lidos: ${D}
|
|
20
10
|
- Exemplo: "feat(auth): adicionar valida\xE7\xE3o de email"
|
|
21
11
|
- Mantenha a primeira linha com at\xE9 50 caracteres`,simple:`- Use formato simples e direto
|
|
22
12
|
- Comece com verbo no infinitivo
|
|
@@ -25,7 +15,7 @@ Mensagem:`}function He(e,t){let o={pt:{conventional:`- Use formato: tipo(escopo)
|
|
|
25
15
|
- Se necess\xE1rio, adicione corpo explicativo
|
|
26
16
|
- Use presente do indicativo
|
|
27
17
|
- Seja descritivo mas conciso`},en:{conventional:`- Use format: type(scope): description
|
|
28
|
-
- Valid types:
|
|
18
|
+
- Valid types: ${D}
|
|
29
19
|
- Example: "feat(auth): add email validation"
|
|
30
20
|
- Keep first line under 50 characters`,simple:`- Use simple and direct format
|
|
31
21
|
- Start with imperative verb
|
|
@@ -33,27 +23,47 @@ Mensagem:`}function He(e,t){let o={pt:{conventional:`- Use formato: tipo(escopo)
|
|
|
33
23
|
- Maximum 50 characters`,detailed:`- First line: summary under 50 characters
|
|
34
24
|
- Add explanatory body if needed
|
|
35
25
|
- Use imperative mood
|
|
36
|
-
- Be descriptive but concise`}},
|
|
26
|
+
- Be descriptive but concise`}},o=t==="pt"?"pt":"en";return i[o][e]||i[o].conventional}var D,oe=x(()=>{"use strict";f();D="feat, fix, docs, style, refactor, test, chore, build, ci"});function ne(e,t){if(!t)return null;let i=e.language==="pt",o=[];if(e.commitStyle==="conventional"){let n=t.typeEnum?.join(", ")??D;o.push(i?"- Formato: tipo(escopo): descri\xE7\xE3o":"- Format: type(scope): description"),o.push(i?`- Tipos permitidos: ${n}`:`- Allowed types: ${n}`)}if(t.headerMaxLength!=null){let n=t.headerMaxLength;o.push(i?`- CR\xCDTICO: o header (primeira linha) N\xC3O PODE exceder ${n} caracteres. Conte os caracteres antes de responder.`:`- CRITICAL: the header (first line) MUST NOT exceed ${n} characters. Count characters before responding.`)}if(t.scopeEnum&&t.scopeEnum.length>0&&o.push(i?`- Escopos permitidos: ${t.scopeEnum.join(", ")}`:`- Allowed scopes: ${t.scopeEnum.join(", ")}`),t.subjectCase){let{condition:n,cases:r}=t.subjectCase,m=r.join(", ");n==="never"?o.push(i?`- Subject nunca em: ${m}`:`- Subject must never be: ${m}`):n==="always"&&o.push(i?`- Subject deve estar em: ${m}`:`- Subject must be in: ${m}`)}if(t.subjectFullStop){let{condition:n,value:r}=t.subjectFullStop,m=r??".";n==="never"&&o.push(i?`- N\xE3o termine o subject com "${m}"`:`- Do not end subject with "${m}"`)}return o.length===0?null:`${i?"Voc\xEA \xE9 um gerador de mensagens de commit. Siga ESTRITAMENTE as seguintes regras do commitlint do projeto. Responda APENAS com a mensagem de commit, sem explica\xE7\xF5es adicionais.":"You are a commit message generator. STRICTLY follow the project commitlint rules below. Respond with ONLY the commit message, no additional explanation."}
|
|
27
|
+
|
|
28
|
+
${o.join(`
|
|
29
|
+
`)}`}var se=x(()=>{"use strict";f();oe()});function He(e,t,i,o){let s=t.language==="pt"?"portugu\xEAs":"english",n=o!=null?Be(t.commitStyle,t.language,o):Je(t.commitStyle,t.language),r=i.length>10?`${i.length} arquivos: ${i.slice(0,5).join(", ")}...`:i.join(", ");return`Gere mensagem de commit em ${s} (${t.commitStyle}).
|
|
30
|
+
|
|
31
|
+
Arquivos: ${r}
|
|
32
|
+
|
|
33
|
+
${n}
|
|
34
|
+
|
|
35
|
+
Diff:
|
|
36
|
+
\`\`\`
|
|
37
|
+
${e}
|
|
38
|
+
\`\`\`
|
|
39
|
+
|
|
40
|
+
Mensagem:`}function We(e,t,i,o){return{user:He(e,t,i,o),system:ne(t,o)}}var re=x(()=>{"use strict";f();oe();se()});function q(e){return e?Tt.some(t=>t.test(e)):!1}function Ke(e){if(!e)return!1;let t=e.lastIndexOf(".");if(t===-1)return!1;let i=e.substring(t).toLowerCase();return Ot.includes(i)}function Ye(e,t){if(!e)return"";let i=new Set(t.filter(n=>!q(n)&&!Ke(n))),o=e.split(/(?=^diff --git )/m).filter(n=>n.trim()),s=[];for(let n of o){let r=n.match(/^diff --git a\/(.*?) b\/(.*?)$/m);if(!r)continue;let m=r[1],c=r[2]||m;if(!(t.length>0?i.has(c)||i.has(m):!q(c)&&!Ke(c)))continue;let l=n.split(`
|
|
41
|
+
`);if(l.length>1e3){let p=l.slice(0,1e3);p.push(`... (diff truncado: ${l.length-1e3} linhas omitidas)`),s.push(p.join(`
|
|
42
|
+
`))}else s.push(n)}return s.join("")}var Tt,Ot,ae=x(()=>{"use strict";f();Tt=[/package-lock\.json$/,/yarn\.lock$/,/pnpm-lock\.yaml$/,/bun\.lockb$/,/composer\.lock$/,/Gemfile\.lock$/,/Cargo\.lock$/,/poetry\.lock$/,/go\.sum$/,/requirements(\.txt)?\.lock$/,/\.min\.js$/,/\.min\.css$/,/\.map$/,/^dist\//,/^build\//,/^node_modules\//,/\/node_modules\//],Ot=[".png",".jpg",".jpeg",".gif",".webp",".svg",".ico",".bmp",".tiff",".woff",".woff2",".ttf",".eot",".otf",".mp4",".mp3",".webm",".avi",".mov",".wav",".ogg",".pdf",".zip",".tar",".gz",".bz2",".7z",".rar",".exe",".dll",".so",".dylib",".bin",".class",".pyc",".db",".sqlite",".sqlite3"]});function Xe(e,t){if(e.length<=t)return e;let i=e.split(/(?=^diff --git)/m).filter(c=>c.trim()),o=[],s=[];i.forEach(c=>{let a=c.match(/^diff --git a\/(.*?) b\//m),l=a?a[1]:"";q(l)?s.push(c):o.push(c)});let n="",r=t;for(let c of o)if(c.length<=r)n+=c,r-=c.length;else if(r>200){n+=c.substring(0,r-50),r=t-n.length;break}else break;if(!n&&s.length>0&&r>0)for(let c of s)if(c.length<=r)n+=c,r-=c.length;else if(r>200){n+=c.substring(0,r-50),r=t-n.length;break}else break;let m=`
|
|
43
|
+
... (diff otimizado para focar em mudan\xE7as principais)`;if(r>200&&s.length>0){let c=`
|
|
44
|
+
|
|
45
|
+
... (${s.length} arquivo(s) de depend\xEAncias/build omitido(s): ${s.map(l=>{let p=l.match(/^diff --git a\/(.*?) b\//);return p?p[1]:""}).filter(Boolean).join(", ")})`,a=r-m.length;c.length<a&&(n+=c)}return n.trim()!==e.trim()?n+m:n}function Qe(e){let t={feat:/^(feat|feature)(\([^)]+\))?:/i,fix:/^(fix|bugfix)(\([^)]+\))?:/i,docs:/^(docs|documentation)(\([^)]+\))?:/i,style:/^(style|format)(\([^)]+\))?:/i,refactor:/^(refactor|refactoring)(\([^)]+\))?:/i,test:/^(test|testing)(\([^)]+\))?:/i,chore:/^(chore|maintenance)(\([^)]+\))?:/i,build:/^(build|ci)(\([^)]+\))?:/i,ci:/^(ci|continuous-integration)(\([^)]+\))?:/i};for(let[i,o]of Object.entries(t))if(o.test(e))return i;return null}function Ze(e,t){let i=e.toLowerCase(),o=t.join(" ").toLowerCase();return o.includes("test")||o.includes("spec")||i.includes("test(")?"test":o.includes("readme")||o.includes(".md")||o.includes("docs")?"docs":o.includes("package.json")||o.includes("dockerfile")||o.includes(".yml")||o.includes(".yaml")||o.includes("webpack")||o.includes("tsconfig")?"build":o.includes(".css")||o.includes(".scss")||i.includes("style")||i.includes("format")?"style":i.includes("fix")||i.includes("bug")||i.includes("error")||i.includes("issue")?"fix":i.includes("add")||i.includes("new")||i.includes("create")||i.includes("implement")?"feat":i.includes("refactor")||i.includes("restructure")||i.includes("rename")?"refactor":"chore"}function et(e){if(e.startsWith("```")){let t=e.match(/^```[^\n`]*\n([\s\S]*?)\n\s*```([\s\S]*)$/);if(t){let i=t[1].trim(),o=t[2].trim();e=o?`${i}
|
|
37
46
|
|
|
38
|
-
${
|
|
39
|
-
Mensagem: "${e.message}"`,"\u{1F4AD} Sugest\xE3o de Commit");let t=await
|
|
47
|
+
${o}`:i}else e.match(/^```[\s\S]*```$/)&&(e=e.replace(/^```(?:plaintext|javascript|typescript|python|java|html|css|json|xml|yaml|yml|bash|shell|text)?\s*/,"").replace(/\s*```$/,""))}return e=e.trim(),e}var U,ce=x(()=>{"use strict";f();re();se();ae();U=class{constructor(t){this.config=t}async generate(t,i){if(!this.config.openai.apiKey)throw new Error("Chave da OpenAI n\xE3o encontrada. Configure OPENAI_API_KEY nas vari\xE1veis de ambiente.");let o=[];i&&o.push({role:"system",content:i}),o.push({role:"user",content:t});let s=new AbortController,n=setTimeout(()=>s.abort(),this.config.openai.timeout);try{let r=await fetch("https://api.openai.com/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${this.config.openai.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({model:this.config.openai.model,messages:o,max_tokens:Math.min(this.config.openai.maxTokens,150),temperature:this.config.openai.temperature}),signal:s.signal});if(!r.ok){let c=await r.json().catch(()=>({}));throw new Error(`Erro da OpenAI (${r.status}): ${c.error?.message||"Erro desconhecido"}`)}let u=(await r.json()).choices?.[0]?.message?.content?.trim();if(!u)throw new Error("OpenAI retornou resposta vazia");return u}finally{clearTimeout(n)}}}});function tt(e){switch(e.provider){case"openai":return new U(e);default:{let t=e.provider;throw new Error(`Provider '${t}' n\xE3o suportado`)}}}var it=x(()=>{"use strict";f();ce()});import{createHash as zt}from"crypto";function ot(e){return zt("sha256").update(e).digest("hex")}var nt=x(()=>{"use strict";f()});var rt={};k(rt,{clearCommitCache:()=>kt,generateCommit:()=>V});function st(e,t,i){return ot(`${e}::${t}::${i}`)}async function V(e){let{diff:t,files:i,config:o,rules:s,maxRetries:n=3}=e,r=Ye(t,i),m=Xe(r||t,Lt);if(o.cache.enabled){let h=st(m,o.language,o.commitStyle),v=me.get(h);if(v)return v}let{user:u,system:c}=We(m,o,i,s),a=tt(o),l=0,p="";for(;l<n;)try{let h=await a.generate(u,c),v=et(h),g=Ue(v,s),E=Qe(g.message)||Ze(t,i),w={success:!0,message:g.message,type:E,enforced:g.enforced,retries:l};if(o.cache.enabled){let S=st(m,o.language,o.commitStyle);me.set(S,w)}return w}catch(h){p=h instanceof Error?h.message:"Erro desconhecido",l++,l<n&&await new Promise(v=>setTimeout(v,Math.pow(2,l-1)*1e3))}return{success:!1,enforced:!1,retries:l,error:`Falha ap\xF3s ${n} tentativas. \xDAltimo erro: ${p}`}}function kt(){me.clear()}var Lt,me,le=x(()=>{"use strict";f();Ve();it();re();ce();ae();nt();Lt=6e3,me=new Map});var fe={};k(fe,{askContinueCommits:()=>pe,confirmCommit:()=>qt,copyToClipboard:()=>W,editCommitMessage:()=>H,selectFilesForCommit:()=>ue,showCancellation:()=>O,showCommitPreview:()=>J,showCommitResult:()=>$});import{text as Gt,select as Dt,confirm as B,log as I,note as at,cancel as _t,isCancel as T}from"@clack/prompts";import Nt from"clipboardy";async function J(e){at(`Tipo: ${e.type}
|
|
48
|
+
Mensagem: "${e.message}"`,"\u{1F4AD} Sugest\xE3o de Commit");let t=await Dt({message:"O que voc\xEA gostaria de fazer?",options:[{value:"commit",label:"\u2705 Fazer commit com esta mensagem",hint:"Executar git commit imediatamente"},{value:"edit",label:"\u270F\uFE0F Editar mensagem",hint:"Modificar a mensagem antes de commitar"},{value:"copy",label:"\u{1F4CB} Copiar para clipboard",hint:"Copiar mensagem e sair sem commitar"},{value:"cancel",label:"\u274C Cancelar",hint:"Sair sem fazer nada"}]});return T(t)?{action:"cancel"}:{action:t}}async function H(e,t){let i=t??72,o=await Gt({message:"Edite a mensagem do commit:",initialValue:e,placeholder:"Digite a mensagem do commit...",validate:n=>{if(!n||n.trim().length===0)return"A mensagem n\xE3o pode estar vazia";let r=n.split(`
|
|
49
|
+
`)[0].length;if(r>i)return`Header muito longo: ${r}/${i} caracteres`}});if(T(o))return{action:"cancel"};let s=await B({message:`Confirma a mensagem editada: "${o}"?`});return T(s)||!s?{action:"cancel"}:{action:"commit",message:o}}async function W(e){try{return await Nt.write(e),I.success("\u2705 Mensagem copiada para a \xE1rea de transfer\xEAncia!"),!0}catch(t){return I.error(`\u274C Erro ao copiar: ${t instanceof Error?t.message:"Erro desconhecido"}`),!1}}async function qt(e){at(`"${e}"`,"\u{1F680} Confirmar Commit");let t=await B({message:"Executar o commit agora?"});return T(t)?!1:t}function $(e,t,i){e&&t?(I.success("\u2705 Commit realizado com sucesso!"),I.info(`\u{1F517} Hash: ${t.substring(0,8)}`)):I.error(`\u274C Erro ao realizar commit: ${i||"Erro desconhecido"}`)}async function ue(e){I.info("\u{1F4CB} Modo Split: Selecione os arquivos para este commit");let t=[];for(let i of e){let o=await B({message:`Incluir "${i}" neste commit?`});if(T(o))break;o&&t.push(i)}return t}async function pe(e){if(e.length===0)return!1;I.info(`\u{1F4C4} Arquivos restantes: ${e.join(", ")}`);let t=await B({message:"Gerar commit para os arquivos restantes?"});return T(t)?!1:t}function O(){_t("Opera\xE7\xE3o cancelada pelo usu\xE1rio")}var _=x(()=>{"use strict";f()});var ut={};k(ut,{chooseSplitMode:()=>ge,confirmGroupCommit:()=>Bt,showSmartSplitGroups:()=>Vt,showSmartSplitProgress:()=>Jt});import{select as mt,confirm as Ut,log as ct,note as lt,isCancel as de}from"@clack/prompts";async function ge(){let e=await mt({message:"Como voc\xEA gostaria de organizar os commits?",options:[{value:"smart",label:"\u{1F9E0} Smart Split (Recomendado)",hint:"IA analisa contexto e agrupa automaticamente"},{value:"manual",label:"\u270B Split Manual",hint:"Voc\xEA escolhe arquivos manualmente"},{value:"cancel",label:"\u274C Cancelar",hint:"Voltar ao modo normal"}]});return de(e)?{action:"cancel"}:e==="manual"?{action:"manual"}:e==="smart"?{action:"proceed"}:{action:"cancel"}}async function Vt(e){lt(`Identificamos ${e.length} grupo(s) l\xF3gico(s) para seus commits:
|
|
40
50
|
|
|
41
|
-
`+e.map((o
|
|
42
|
-
\u{1F4C4} ${
|
|
43
|
-
\u{1F4A1} ${
|
|
44
|
-
\u{1F3AF} Confian\xE7a: ${Math.round(
|
|
51
|
+
`+e.map((i,o)=>`${o+1}. **${i.name}**
|
|
52
|
+
\u{1F4C4} ${i.files.join(", ")}
|
|
53
|
+
\u{1F4A1} ${i.description}
|
|
54
|
+
\u{1F3AF} Confian\xE7a: ${Math.round(i.confidence*100)}%`).join(`
|
|
45
55
|
|
|
46
|
-
`),"\u{1F9E0} An\xE1lise de Contexto");let t=await
|
|
56
|
+
`),"\u{1F9E0} An\xE1lise de Contexto");let t=await mt({message:"O que voc\xEA gostaria de fazer?",options:[{value:"proceed",label:"\u2705 Prosseguir com esta organiza\xE7\xE3o",hint:"Usar os grupos como sugeridos pela IA"},{value:"manual",label:"\u270B Fazer split manual",hint:"Escolher arquivos manualmente"},{value:"cancel",label:"\u274C Cancelar",hint:"Voltar ao modo normal"}]});return de(t)?{action:"cancel"}:t==="proceed"?{action:"proceed",groups:e}:{action:t}}async function Bt(e,t){lt(`**Grupo:** ${e.name}
|
|
47
57
|
**Arquivos:** ${e.files.join(", ")}
|
|
48
|
-
**Mensagem:** "${t}"`,"\u{1F680} Confirmar Commit do Grupo");let
|
|
49
|
-
... (diff truncado)`:t,
|
|
58
|
+
**Mensagem:** "${t}"`,"\u{1F680} Confirmar Commit do Grupo");let i=await Ut({message:`Fazer commit para "${e.name}"?`});return de(i)?!1:i}function Jt(e,t,i){let o=Math.round(e/t*100),s="\u2588".repeat(Math.floor(o/10))+"\u2591".repeat(10-Math.floor(o/10));ct.info(`\u{1F504} Progresso: [${s}] ${o}% (${e}/${t})`),ct.info(`\u{1F4CB} Processando: ${i}`)}var he=x(()=>{"use strict";f()});import Ht from"crypto";function ft(e){pt=new ye(e)}function dt(){return pt}function gt(e,t){let i=dt();return i?i.get(e,t):{hit:!1}}function ht(e,t,i){let o=dt();o&&o.set(e,t,i)}var ye,pt,be=x(()=>{"use strict";f();ye=class{cache=new Map;config;constructor(t){this.config=t}generateHash(t,i){let o={files:t.sort(),diff:i.substring(0,1e3),model:this.config.openai.model,temperature:this.config.openai.temperature};return Ht.createHash("md5").update(JSON.stringify(o)).digest("hex")}get(t,i){if(!this.config.cache.enabled)return{hit:!1};let o=this.generateHash(t,i),s=this.cache.get(o);if(!s)return{hit:!1};let n=Date.now(),r=this.config.cache.ttl*60*1e3;return n-s.timestamp>r?(this.cache.delete(o),{hit:!1}):{hit:!0,groups:s.groups}}set(t,i,o){if(!this.config.cache.enabled||(this.cache.size>=this.config.cache.maxSize&&this.cleanup(),this.cache.size>=this.config.cache.maxSize))return;let s=this.generateHash(t,i),n={groups:o,timestamp:Date.now(),hash:s};this.cache.set(s,n)}cleanup(){let t=Date.now(),i=this.config.cache.ttl*60*1e3;for(let[o,s]of this.cache.entries())t-s.timestamp>i&&this.cache.delete(o);if(this.cache.size>=this.config.cache.maxSize){let s=Array.from(this.cache.entries()).sort((n,r)=>n[1].timestamp-r[1].timestamp).slice(0,Math.ceil(this.config.cache.maxSize*.5));for(let[n]of s)this.cache.delete(n)}}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,maxSize:this.config.cache.maxSize,enabled:this.config.cache.enabled}}},pt=null});import{log as C,spinner as Wt}from"@clack/prompts";function Kt(e,t){let o=t.length>8e3?t.substring(0,8e3)+`
|
|
59
|
+
... (diff truncado)`:t,s=e.length,n=e.reduce((m,u)=>{let c=u.split(".").pop()||"sem-extensao";return m[c]=(m[c]||0)+1,m},{}),r=Object.entries(n).map(([m,u])=>`${m}: ${u}`).join(", ");return`Analise os arquivos modificados e agrupe em commits l\xF3gicos.
|
|
50
60
|
|
|
51
|
-
ARQUIVOS (${
|
|
52
|
-
TIPOS: ${
|
|
61
|
+
ARQUIVOS (${s}): ${e.join(", ")}
|
|
62
|
+
TIPOS: ${r}
|
|
53
63
|
|
|
54
64
|
DIFF RESUMIDO:
|
|
55
65
|
\`\`\`
|
|
56
|
-
${
|
|
66
|
+
${o}
|
|
57
67
|
\`\`\`
|
|
58
68
|
|
|
59
69
|
Agrupe arquivos relacionados. M\xE1ximo 5 grupos. Responda em JSON:
|
|
@@ -67,10 +77,10 @@ Agrupe arquivos relacionados. M\xE1ximo 5 grupos. Responda em JSON:
|
|
|
67
77
|
"confidence": 0.8
|
|
68
78
|
}
|
|
69
79
|
]
|
|
70
|
-
}`}function
|
|
80
|
+
}`}function Yt(e){let t=e.reduce((o,s)=>{let n=s.split("/").slice(0,-1).join("/")||"root";return o[n]||(o[n]=[]),o[n].push(s),o},{});return`Agrupe estes arquivos em commits l\xF3gicos baseado nos diret\xF3rios:
|
|
71
81
|
|
|
72
82
|
ARQUIVOS POR DIRET\xD3RIO:
|
|
73
|
-
${Object.entries(t).map(([
|
|
83
|
+
${Object.entries(t).map(([o,s])=>`${o}: ${s.length} arquivo(s)`).join(`
|
|
74
84
|
`)}
|
|
75
85
|
|
|
76
86
|
LISTA COMPLETA: ${e.join(", ")}
|
|
@@ -86,48 +96,56 @@ Agrupe por funcionalidade relacionada. M\xE1ximo 5 grupos. JSON:
|
|
|
86
96
|
"confidence": 0.7
|
|
87
97
|
}
|
|
88
98
|
]
|
|
89
|
-
}`}async function
|
|
90
|
-
... (diff truncado)`:
|
|
91
|
-
... (conte\xFAdo truncado)`:
|
|
99
|
+
}`}async function Xt(e,t,i){try{if(!i.openai.apiKey)return{success:!1,error:"Chave da OpenAI n\xE3o encontrada"};let o=gt(e,t);if(o.hit&&o.groups)return{success:!0,groups:o.groups};let n=t.length>6e3,r=n?Yt(e):Kt(e,t);n&&console.warn(`\u26A0\uFE0F Diff muito grande (${t.length} chars), usando an\xE1lise baseada em nomes de arquivos`);let m=await fetch("https://api.openai.com/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${i.openai.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({model:i.openai.model,messages:[{role:"user",content:r}],max_tokens:800,temperature:.3})});if(!m.ok){let g=await m.json().catch(()=>({}));return{success:!1,error:`Erro da OpenAI (${m.status}): ${g.error?.message||"Erro desconhecido"}`}}let c=(await m.json()).choices?.[0]?.message?.content?.trim();if(!c)return{success:!1,error:"OpenAI retornou resposta vazia"};let a=c.match(/\{[\s\S]*\}/);if(!a)return{success:!1,error:"Resposta da OpenAI n\xE3o cont\xE9m JSON v\xE1lido"};let l=JSON.parse(a[0]);if(!l.groups||!Array.isArray(l.groups))return{success:!1,error:"Formato de resposta inv\xE1lido da OpenAI"};let p=l.groups.flatMap(g=>g.files||[]),h=e.filter(g=>!p.includes(g));h.length>0&&(l.groups[0].files=[...l.groups[0].files||[],...h]);let v=l.groups.map(g=>({id:g.id||`group-${Math.random().toString(36).substr(2,9)}`,name:g.name||"Grupo sem nome",description:g.description||"Sem descri\xE7\xE3o",files:g.files||[],diff:"",confidence:g.confidence||.5}));return ht(e,t,v),{success:!0,groups:v}}catch(o){return{success:!1,error:`Erro ao analisar contexto: ${o instanceof Error?o.message:"Erro desconhecido"}`}}}async function Qt(e){let{getFileDiff:t}=await Promise.resolve().then(()=>(A(),R)),i=e.files.map(n=>{try{let r=t(n),m=4e3;return r.length>m?r.substring(0,m)+`
|
|
100
|
+
... (diff truncado)`:r}catch{return""}}).filter(n=>n.length>0);if(i.length===0&&e.files.length>0){let{execSync:n}=await import("child_process"),r=e.files.filter(u=>{try{return n(`test -f "${u}"`,{stdio:"ignore"}),n(`git status --porcelain -- "${u}"`,{encoding:"utf-8",stdio:"pipe"}).trim().startsWith("??")}catch{return!1}});if(r.length>0)return r.map(u=>{try{let c=n(`cat "${u}"`,{encoding:"utf-8",stdio:"pipe"}),a=2e3,l=c.length>a?c.substring(0,a)+`
|
|
101
|
+
... (conte\xFAdo truncado)`:c;return`diff --git a/${u} b/${u}
|
|
92
102
|
new file mode 100644
|
|
93
103
|
index 0000000..${Math.random().toString(36).substr(2,7)}
|
|
94
104
|
--- /dev/null
|
|
95
|
-
+++ b/${
|
|
96
|
-
@@ -0,0 +1,${
|
|
105
|
+
+++ b/${u}
|
|
106
|
+
@@ -0,0 +1,${l.split(`
|
|
97
107
|
`).length} @@
|
|
98
|
-
${
|
|
99
|
-
`).map(
|
|
100
|
-
`)}`}catch{return""}}).filter(
|
|
101
|
-
`);let
|
|
102
|
-
`).includes(
|
|
103
|
-
... (conte\xFAdo truncado)`:
|
|
108
|
+
${l.split(`
|
|
109
|
+
`).map(p=>`+${p}`).join(`
|
|
110
|
+
`)}`}catch{return""}}).filter(u=>u.length>0).join(`
|
|
111
|
+
`);let m=e.files.filter(u=>{try{return n(`test -f "${u}"`,{stdio:"ignore"}),n("git diff --cached --name-only",{encoding:"utf-8",stdio:"pipe"}).trim().split(`
|
|
112
|
+
`).includes(u)}catch{return!1}});if(m.length>0)return m.map(u=>{try{let c=n(`cat "${u}"`,{encoding:"utf-8",stdio:"pipe"}),a=2e3,l=c.length>a?c.substring(0,a)+`
|
|
113
|
+
... (conte\xFAdo truncado)`:c;return`diff --git a/${u} b/${u}
|
|
104
114
|
index 0000000..${Math.random().toString(36).substr(2,7)} 100644
|
|
105
|
-
--- a/${
|
|
106
|
-
+++ b/${
|
|
107
|
-
@@ -1 +1,${
|
|
115
|
+
--- a/${u}
|
|
116
|
+
+++ b/${u}
|
|
117
|
+
@@ -1 +1,${l.split(`
|
|
108
118
|
`).length} @@
|
|
109
|
-
${
|
|
110
|
-
`).map(
|
|
111
|
-
`)}`}catch{return""}}).filter(
|
|
112
|
-
`)}let i
|
|
113
|
-
`),
|
|
114
|
-
... (diff total truncado)`:
|
|
115
|
-
\u{1F504} Processando grupo ${
|
|
116
|
-
`)
|
|
119
|
+
${l.split(`
|
|
120
|
+
`).map(p=>`+${p}`).join(`
|
|
121
|
+
`)}`}catch{return""}}).filter(u=>u.length>0).join(`
|
|
122
|
+
`)}let o=i.join(`
|
|
123
|
+
`),s=8e3;return o.length>s?o.substring(0,s)+`
|
|
124
|
+
... (diff total truncado)`:o}async function Ce(e,t,i,o){i.silent||C.info("\u{1F9E0} Modo Smart Split ativado - Agrupando arquivos por contexto");let s=i.silent?null:Wt();s&&s.start("Analisando contexto das mudan\xE7as...");let n=await Xt(e.stagedFiles,e.diff,t);if(s&&(n.success?s.stop("An\xE1lise conclu\xEDda"):s.stop("Falha na an\xE1lise de contexto")),!n.success){i.silent||C.error(`\u274C Erro na an\xE1lise de contexto: ${n.error}`);return}if(!n.groups||n.groups.length===0){i.silent||C.error("\u274C Nenhum grupo foi criado pela an\xE1lise");return}if(i.silent||(C.success(`\u2705 ${n.groups.length} grupo(s) identificado(s):`),n.groups.forEach((r,m)=>{C.info(` ${m+1}. ${r.name} (${r.files.length} arquivo(s))`),C.info(` \u{1F4C4} ${r.files.join(", ")}`)})),!i.yes&&!i.silent){let{showSmartSplitGroups:r}=await Promise.resolve().then(()=>(he(),ut)),m=await r(n.groups);if(m.action==="cancel"){i.silent||C.info("\u274C Opera\xE7\xE3o cancelada pelo usu\xE1rio");return}if(m.action==="manual"){let u={...i,split:!0,smartSplit:!1},{runCommitCommand:c}=await Promise.resolve().then(()=>(xe(),bt));await c(u);return}}for(let r=0;r<n.groups.length;r++){let m=n.groups[r];if(!m){i.silent||C.error(`\u274C Grupo ${r+1} \xE9 undefined`);continue}i.silent||C.info(`
|
|
125
|
+
\u{1F504} Processando grupo ${r+1}/${n.groups.length}: ${m.name}`);let u=await Qt(m);if(!u){i.silent||(C.warn(`\u26A0\uFE0F Nenhum diff encontrado para o grupo: ${m.name}`),C.info(` \u{1F4C4} Arquivos: ${m.files.join(", ")}`),C.info(" \u{1F4A1} Poss\xEDvel causa: arquivos novos, deletados/recriados, ou sem mudan\xE7as"));continue}i.silent||C.info(`\u{1F916} Gerando commit para: ${m.name}`);let{generateCommit:c}=await Promise.resolve().then(()=>(le(),rt)),a=await c({diff:u,files:m.files,config:t,rules:o});if(!a.success||!a.message){i.silent||C.error(`\u274C Erro ao gerar commit para ${m.name}: ${a.error}`);continue}let l={message:a.message,type:a.type??"chore",confidence:.8};if(t.dryRun){i.silent||(C.info(`\u{1F50D} Dry Run - Grupo: ${m.name}`),C.info(`\u{1F4C4} Arquivos: ${m.files.join(", ")}`),C.info(`\u{1F4AD} Mensagem: "${l.message}"`));continue}if(i.yes){let{executeFileCommit:p}=await Promise.resolve().then(()=>(A(),R)),h;if(m.files.length===1&&m.files[0])h=p(m.files[0],l.message||"");else{let{execSync:v}=await import("child_process"),{escapeShellArg:g}=await Promise.resolve().then(()=>(A(),R));try{let P=m.files.map(S=>g(S)).join(" "),E=g(l.message||"");v(`git commit ${P} -m ${E}`,{stdio:"pipe"}),h={success:!0,hash:v("git rev-parse HEAD",{encoding:"utf-8",stdio:"pipe"}).trim(),message:l.message||""}}catch(P){h={success:!1,error:P instanceof Error?P.message:"Erro desconhecido ao executar commit"}}}$(h.success,h.hash,h.error)}else{let{showCommitPreview:p,editCommitMessage:h,copyToClipboard:v,showCancellation:g}=await Promise.resolve().then(()=>(_(),fe));switch((await p(l)).action){case"commit":{let{executeFileCommit:E}=await Promise.resolve().then(()=>(A(),R)),w,S=l.message||"Atualiza\xE7\xE3o de arquivos";if(m.files.length===1&&m.files[0])w=E(m.files[0],S);else{let{execSync:z}=await import("child_process"),{escapeShellArg:L}=await Promise.resolve().then(()=>(A(),R));try{let j=m.files.map(Q=>L(Q)).join(" "),X=L(S);z(`git commit ${j} -m ${X}`,{stdio:"pipe"}),w={success:!0,hash:z("git rev-parse HEAD",{encoding:"utf-8",stdio:"pipe"}).trim(),message:S}}catch(j){w={success:!1,error:j instanceof Error?j.message:"Erro desconhecido ao executar commit"}}}$(w.success,w.hash,w.error);break}case"edit":{let E=await h(l.message);if(E.action==="commit"&&E.message){let{executeFileCommit:w}=await Promise.resolve().then(()=>(A(),R)),S;if(m.files.length===1&&m.files[0])S=w(m.files[0],E.message||"");else{let{execSync:z}=await import("child_process"),{escapeShellArg:L}=await Promise.resolve().then(()=>(A(),R));try{let j=m.files.map(Q=>L(Q)).join(" "),X=L(E.message||"");z(`git commit ${j} -m ${X}`,{stdio:"pipe"}),S={success:!0,hash:z("git rev-parse HEAD",{encoding:"utf-8",stdio:"pipe"}).trim(),message:E.message||""}}catch(j){S={success:!1,error:j instanceof Error?j.message:"Erro desconhecido ao executar commit"}}}$(S.success,S.hash,S.error)}break}case"copy":{await v(l.message),i.silent||C.info("\u{1F3AF} Mensagem copiada para clipboard");break}case"cancel":{g();return}}}if(r<n.groups.length-1&&!i.yes){let{askContinueCommits:p}=await Promise.resolve().then(()=>(_(),fe)),h=n.groups.slice(r+1).filter(g=>g!==void 0).map(g=>g.name);if(!await p(h))break}}i.silent||C.success("\u2705 Smart Split conclu\xEDdo!")}var yt=x(()=>{"use strict";f();be();_()});import{existsSync as we,writeFileSync as Zt,readFileSync as ei}from"fs";import{join as K,extname as ti,basename as ii}from"path";import{spawnSync as Se}from"child_process";function ve(e){let t={},i=e?.rules??{},o=i["type-enum"];Array.isArray(o)&&Array.isArray(o[2])&&(t.typeEnum=o[2]);let s=i["header-max-length"];Array.isArray(s)&&typeof s[2]=="number"&&(t.headerMaxLength=s[2]);let n=i["subject-case"];if(Array.isArray(n)){let[c,a,l]=n;Array.isArray(l)?t.subjectCase={severity:c,condition:a,cases:l}:typeof l=="string"&&(t.subjectCase={severity:c,condition:a,cases:[l]})}let r=i["subject-full-stop"];if(Array.isArray(r)){let[c,a,l]=r;t.subjectFullStop={severity:c,condition:a,value:l??"."}}let m=i["body-leading-blank"];Array.isArray(m)&&(t.bodyLeadingBlank=m[1]==="always");let u=i["scope-enum"];return Array.isArray(u)&&Array.isArray(u[2])&&(t.scopeEnum=u[2]),t}function Ct(e){try{let t=ti(e).toLowerCase(),i=ii(e);if(t===".json"||t===""&&i===".commitlintrc")try{let o=ei(e,"utf-8"),s=JSON.parse(o);return ve(s)}catch{return null}if(t===".js"||t===".mjs"||t===".cjs"){let o=["import { pathToFileURL } from 'url';",`const mod = await import(pathToFileURL(${JSON.stringify(e)}).href);`,"const cfg = mod.default ?? mod;","process.stdout.write(JSON.stringify(cfg));"].join(`
|
|
126
|
+
`),s=Se(process.execPath,["--input-type=module"],{input:o,encoding:"utf-8",timeout:5e3});if(s.status===0&&s.stdout)try{let m=JSON.parse(s.stdout);return ve(m)}catch{}let n=["try {",` const c = require(${JSON.stringify(e)});`," process.stdout.write(JSON.stringify(c.default ?? c));","} catch (e) {"," process.exit(1);","}"].join(`
|
|
127
|
+
`),r=Se(process.execPath,["-e",n],{encoding:"utf-8",timeout:5e3});if(r.status===0&&r.stdout)try{let m=JSON.parse(r.stdout);return ve(m)}catch{}}return null}catch{return null}}function $e(e){let t=e||process.cwd();for(let i of oi){let o=K(t,i);if(we(o))return o}return null}function Ee(e){let t=e||process.cwd(),i=K(t,"node_modules",".bin","commitlint");return we(i)}function xt(e,t){let i=t||process.cwd(),o=K(i,"node_modules",".bin","commitlint"),s=Se(o,[],{input:e,encoding:"utf-8",cwd:i});if(s.status===0)return{valid:!0,errors:[],warnings:[]};let r=((s.stdout||"")+(s.stderr||"")).split(`
|
|
128
|
+
`),m=[],u=[];for(let c of r){let a=c.trim();a&&(a.startsWith("\u2716")||a.includes("[error]")?m.push(a):(a.startsWith("\u26A0")||a.includes("[warning]"))&&u.push(a))}if(m.length===0&&s.status!==0){let c=r.map(a=>a.trim()).filter(a=>!(!a.length||a.startsWith("\u29D7")||a.startsWith("\u2714")||a.startsWith("at ")||a.startsWith("file:///")||a.match(/^[^:]+\.(?:js|ts|mjs|cjs):\d+$/)||a==="^"||a==="throw err;"||a.startsWith("Node.js v")));m.push(...c)}return{valid:!1,errors:m,warnings:u}}function vt(e){let t=e||process.cwd(),i=K(t,"commitlint.config.js");if(we(i))throw new Error("commitlint.config.js j\xE1 existe neste diret\xF3rio. Remova-o antes de continuar.");Zt(i,`export default {
|
|
129
|
+
extends: ['@commitlint/config-conventional'],
|
|
130
|
+
};
|
|
131
|
+
`,"utf-8")}var oi,Ae=x(()=>{"use strict";f();oi=["commitlint.config.js","commitlint.config.ts","commitlint.config.mjs","commitlint.config.cjs",".commitlintrc",".commitlintrc.js",".commitlintrc.json",".commitlintrc.yml",".commitlintrc.yaml"]});var bt={};k(bt,{main:()=>si,runCommitCommand:()=>Y});import{log as d}from"@clack/prompts";function ni(e,t){return!t.commitlint.enabled||!Ee()?!1:e.validate?!0:$e()!==null}function je(e,t){let i=xt(e);return i.valid?(t||d.success("\u2705 Mensagem validada pelo commitlint!"),!0):(d.error("\u274C A mensagem n\xE3o passou na valida\xE7\xE3o do commitlint:"),i.errors.forEach(o=>d.error(` ${o}`)),i.warnings.length>0&&i.warnings.forEach(o=>d.info(` \u26A0\uFE0F ${o}`)),!1)}async function Y(e={silent:!1,yes:!1,auto:!1,split:!1,smartSplit:!1,dryRun:!1,help:!1,version:!1,validate:!1,initCommitlint:!1}){e.silent||d.info("\u{1F680} Commit Wizard iniciado!"),ee()||(d.error("\u274C N\xE3o foi encontrado um reposit\xF3rio Git neste diret\xF3rio."),e.silent||d.info("\u{1F4A1} Execute o comando em um diret\xF3rio com reposit\xF3rio Git inicializado."),process.exit(1)),e.silent||d.info("\u2699\uFE0F Carregando configura\xE7\xE3o...");let t=Ge();ft(t),e.split&&(t.splitCommits=!0),e.dryRun&&(t.dryRun=!0);let i=De(t);i.length>0&&(d.error("\u274C Erros na configura\xE7\xE3o:"),i.forEach(a=>d.error(` \u2022 ${a}`)),process.exit(1)),e.silent||d.success(`\u2705 Configura\xE7\xE3o carregada (modelo: ${t.openai.model}, idioma: ${t.language})`);let o=ni(e,t);e.silent||(e.validate&&!Ee()?d.info("\u26A0\uFE0F --validate especificado mas commitlint n\xE3o est\xE1 instalado. Valida\xE7\xE3o ignorada."):o&&d.info("\u{1F50D} Valida\xE7\xE3o commitlint ativa"));let s=$e(),n=s?Ct(s):null;e.silent||d.info("\u{1F4CB} Verificando arquivos staged...");let r=te();r.hasStaged||(d.warn("\u26A0\uFE0F Nenhum arquivo foi encontrado no stage."),e.silent||d.info("\u{1F4A1} Use `git add <arquivo>` para adicionar arquivos ao stage antes de gerar o commit."),process.exit(0));let m=ie();if(e.silent||(d.success(`\u2705 Encontrados ${r.stagedFiles.length} arquivo(s) staged:`),r.stagedFiles.forEach(a=>d.info(` \u{1F4C4} ${a}`)),d.info(`\u{1F4CA} Estat\xEDsticas: +${m.added} -${m.removed} linhas`)),t.splitCommits||e.smartSplit){if(e.yes)return await Ce(r,t,e,n);switch((await ge()).action){case"proceed":return await Ce(r,t,e,n);case"manual":return await ri(r,t,e,n);case"cancel":O();return}}e.silent||d.info("\u{1F916} Gerando mensagem de commit com IA...");let u=await V({diff:r.diff,files:r.stagedFiles,config:t,rules:n});(!u.success||!u.message)&&(d.error(`\u274C Erro ao gerar commit: ${u.error}`),process.exit(1)),e.silent||d.success("\u2728 Mensagem de commit gerada!");let c={message:u.message,type:u.type??"chore",confidence:.8};if(t.dryRun){d.info("\u{1F50D} Modo Dry Run - Mensagem gerada:"),d.info(`"${c.message}"`),d.info("\u{1F4A1} Execute sem --dry-run para fazer o commit");return}if(e.yes){o&&(je(c.message,e.silent)||process.exit(1));let a=F(c.message);$(a.success,a.hash,a.error);return}for(;;)switch((await J(c)).action){case"commit":{if(o&&!je(c.message,e.silent))break;let l=F(c.message);$(l.success,l.hash,l.error);return}case"edit":{let l=await H(c.message);if(l.action==="cancel"){O();return}if(l.action==="commit"&&l.message){if(o&&!je(l.message,e.silent))break;let p=F(l.message);$(p.success,p.hash,p.error);return}break}case"copy":{await W(c.message),e.silent||d.info('\u{1F3AF} Voc\xEA pode usar a mensagem copiada com: git commit -m "mensagem"');return}case"cancel":{O();return}}}async function ri(e,t,i,o){i.silent||d.info("\u{1F504} Modo Split ativado - Commits separados por arquivo");let s=[...e.stagedFiles];for(;s.length>0;){let n=i.yes?[s[0]]:await ue(s);if(n.length===0){i.silent||d.info("\u274C Nenhum arquivo selecionado");break}let{getFileDiff:r}=await Promise.resolve().then(()=>(A(),R)),m=n.filter(a=>a!==void 0).map(a=>{try{return r(a)}catch(l){return d.error(`\u274C Erro ao obter diff do arquivo ${a}: ${l instanceof Error?l.message:"Erro desconhecido"}`),""}}).filter(a=>a.length>0).join(`
|
|
132
|
+
`);if(!m){i.silent||d.warn("\u26A0\uFE0F Nenhum diff encontrado para os arquivos selecionados"),s=s.filter(a=>!n.includes(a));continue}i.silent||d.info(`\u{1F916} Gerando commit para: ${n.join(", ")}`);let u=await V({diff:m,files:n.filter(a=>a!==void 0),config:t,rules:o});if(!u.success||!u.message){d.error(`\u274C Erro ao gerar commit: ${u.error}`),s=s.filter(a=>!n.includes(a));continue}let c={message:u.message,type:u.type??"chore",confidence:.8};if(t.dryRun){d.info(`\u{1F50D} Dry Run - Mensagem para ${n.join(", ")}:`),d.info(`"${c.message}"`),s=s.filter(a=>!n.includes(a));continue}if(i.yes){let a=n.length===1&&n[0]?await G(n[0],c.message):await F(c.message);$(a.success,a.hash,a.error)}else{let a=await J(c);if(a.action==="commit"){let l=n.length===1&&n[0]?await G(n[0],c.message):await F(c.message);$(l.success,l.hash,l.error)}else if(a.action==="edit"){let l=await H(c.message);if(l.action==="commit"&&l.message){let p=n.length===1&&n[0]?await G(n[0],l.message):await F(l.message);$(p.success,p.hash,p.error)}}else if(a.action==="copy")await W(c.message),i.silent||d.info("\u{1F3AF} Mensagem copiada para clipboard");else if(a.action==="cancel"){O();return}}if(s=s.filter(a=>!n.includes(a)),s.length>0&&!i.yes&&!await pe(s))break}i.silent||d.success("\u2705 Modo Split conclu\xEDdo!")}var si,xe=x(()=>{"use strict";f();_e();A();le();_();he();yt();be();Ae();si=Y});f();import{intro as ai,outro as ci,log as mi}from"@clack/prompts";f();f();import{readFileSync as At}from"fs";import{join as Z,dirname as jt}from"path";import{fileURLToPath as Mt}from"url";function Re(){try{let e=Mt(import.meta.url),t=jt(e),i=[Z(t,"..","package.json"),Z(t,"..","..","package.json"),Z(process.cwd(),"package.json")];for(let o of i)try{let s=At(o,"utf-8"),n=JSON.parse(s);if(n.name==="@gilbert_oliveira/commit-wizard")return n.version}catch{continue}throw new Error("Package.json n\xE3o encontrado")}catch{return console.warn("\u26A0\uFE0F N\xE3o foi poss\xEDvel ler a vers\xE3o do package.json, usando vers\xE3o padr\xE3o"),"0.0.0"}}function Fe(e){return{silent:e.includes("--silent")||e.includes("-s"),yes:e.includes("--yes")||e.includes("-y"),auto:e.includes("--auto")||e.includes("-a"),split:e.includes("--split"),smartSplit:e.includes("--smart-split"),dryRun:e.includes("--dry-run")||e.includes("-n"),help:e.includes("--help")||e.includes("-h"),version:e.includes("--version")||e.includes("-v"),validate:e.includes("--validate"),initCommitlint:e.includes("--init-commitlint")}}function Ie(){console.log(`
|
|
117
133
|
\u{1F9D9}\u200D\u2642\uFE0F Commit Wizard - Gerador inteligente de mensagens de commit
|
|
118
134
|
|
|
119
135
|
USAGE:
|
|
120
136
|
commit-wizard [OPTIONS]
|
|
121
137
|
|
|
122
138
|
OPTIONS:
|
|
123
|
-
-s, --silent
|
|
124
|
-
-y, --yes
|
|
125
|
-
-a, --auto
|
|
126
|
-
--split
|
|
127
|
-
--smart-split
|
|
128
|
-
-n, --dry-run
|
|
129
|
-
|
|
130
|
-
-
|
|
139
|
+
-s, --silent Modo silencioso (sem logs detalhados)
|
|
140
|
+
-y, --yes Confirmar automaticamente sem prompts
|
|
141
|
+
-a, --auto Modo autom\xE1tico (--yes + --silent)
|
|
142
|
+
--split Modo split manual (commits separados por arquivo)
|
|
143
|
+
--smart-split Modo smart split (IA agrupa por contexto)
|
|
144
|
+
-n, --dry-run Visualizar mensagem sem fazer commit
|
|
145
|
+
--validate Habilitar valida\xE7\xE3o com commitlint
|
|
146
|
+
--init-commitlint Criar configura\xE7\xE3o padr\xE3o do commitlint
|
|
147
|
+
-h, --help Mostrar esta ajuda
|
|
148
|
+
-v, --version Mostrar vers\xE3o
|
|
131
149
|
|
|
132
150
|
EXAMPLES:
|
|
133
151
|
commit-wizard # Modo interativo padr\xE3o
|
|
@@ -136,6 +154,8 @@ EXAMPLES:
|
|
|
136
154
|
commit-wizard --smart-split # Smart split com IA
|
|
137
155
|
commit-wizard --dry-run # Apenas visualizar mensagem
|
|
138
156
|
commit-wizard --auto # Modo totalmente autom\xE1tico
|
|
157
|
+
commit-wizard --validate # Habilitar valida\xE7\xE3o com commitlint
|
|
158
|
+
commit-wizard --init-commitlint # Criar configura\xE7\xE3o padr\xE3o do commitlint
|
|
139
159
|
|
|
140
160
|
Para mais informa\xE7\xF5es, visite: https://github.com/user/commit-wizard
|
|
141
|
-
`)}function
|
|
161
|
+
`)}function Pe(){let e=Re();console.log(`commit-wizard v${e}`)}xe();f();Ae();import{log as Me}from"@clack/prompts";async function St(){try{vt(),Me.success("\u2705 commitlint.config.js criado com sucesso!"),Me.info("\u{1F4A1} Instale as depend\xEAncias necess\xE1rias: npm install --save-dev @commitlint/cli @commitlint/config-conventional")}catch(e){Me.error(`\u274C ${e instanceof Error?e.message:"Erro ao criar configura\xE7\xE3o do commitlint"}`),process.exit(1)}}f();async function wt(){Pe()}async function li(){try{let e=Fe(process.argv.slice(2));e.help&&(Ie(),process.exit(0)),e.version&&(await wt(),process.exit(0)),e.initCommitlint&&(await St(),process.exit(0)),e.auto&&(e.silent=!0,e.yes=!0),e.silent||ai("\u{1F9D9}\u200D\u2642\uFE0F Commit Wizard"),await Y(e),e.silent||ci("At\xE9 logo! \u2728")}catch(e){mi.error(`Erro: ${e instanceof Error?e.message:"Erro desconhecido"}`),process.exit(1)}}li();
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"displayName": "Commit Wizard",
|
|
4
4
|
"publisher": "gilbert-oliveira",
|
|
5
5
|
"description": "CLI inteligente para gerar mensagens de commit usando OpenAI",
|
|
6
|
-
"version": "2.12.
|
|
6
|
+
"version": "2.12.3-canary.2",
|
|
7
7
|
"categories": [
|
|
8
8
|
"Other",
|
|
9
9
|
"SCM Providers"
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
},
|
|
17
17
|
"scripts": {
|
|
18
18
|
"dev": "npm run build && node dist/commit-wizard.js",
|
|
19
|
-
"build": "tsup src/bin/commit-wizard.ts --format esm --dts --out-dir dist --clean --minify --splitting false --shims",
|
|
19
|
+
"build": "tsup src/bin/commit-wizard.ts --format esm --target node18 --dts --out-dir dist --clean --minify --splitting false --shims",
|
|
20
20
|
"build:tsc": "tsc --project tsconfig.json",
|
|
21
21
|
"start": "node dist/commit-wizard.js",
|
|
22
22
|
"test": "vitest run",
|
|
@@ -71,6 +71,8 @@
|
|
|
71
71
|
},
|
|
72
72
|
"devDependencies": {
|
|
73
73
|
"@changesets/cli": "^2.29.5",
|
|
74
|
+
"@commitlint/cli": "^20.4.2",
|
|
75
|
+
"@commitlint/config-conventional": "^20.4.2",
|
|
74
76
|
"@types/jest": "^30.0.0",
|
|
75
77
|
"@types/node": "^24.0.13",
|
|
76
78
|
"@typescript-eslint/eslint-plugin": "^8.36.0",
|
package/src/bin/commit-wizard.ts
CHANGED
|
@@ -1,23 +1,27 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
import { intro, outro, log } from '@clack/prompts';
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
4
|
+
import { parseArgs, showHelp } from '../utils/args';
|
|
5
|
+
import { runCommitCommand } from '../commands/commit';
|
|
6
|
+
import { runInitCommand } from '../commands/init';
|
|
7
|
+
import { runVersionCommand } from '../commands/version';
|
|
6
8
|
|
|
7
9
|
async function run() {
|
|
8
10
|
try {
|
|
9
|
-
// Processar argumentos da linha de comando
|
|
10
11
|
const args = parseArgs(process.argv.slice(2));
|
|
11
12
|
|
|
12
|
-
// Mostrar ajuda se solicitado
|
|
13
13
|
if (args.help) {
|
|
14
14
|
showHelp();
|
|
15
15
|
process.exit(0);
|
|
16
16
|
}
|
|
17
17
|
|
|
18
|
-
// Mostrar versão se solicitado
|
|
19
18
|
if (args.version) {
|
|
20
|
-
|
|
19
|
+
await runVersionCommand();
|
|
20
|
+
process.exit(0);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
if (args.initCommitlint) {
|
|
24
|
+
await runInitCommand();
|
|
21
25
|
process.exit(0);
|
|
22
26
|
}
|
|
23
27
|
|
|
@@ -27,14 +31,12 @@ async function run() {
|
|
|
27
31
|
args.yes = true;
|
|
28
32
|
}
|
|
29
33
|
|
|
30
|
-
// Intro apenas se não for modo silencioso
|
|
31
34
|
if (!args.silent) {
|
|
32
35
|
intro('🧙♂️ Commit Wizard');
|
|
33
36
|
}
|
|
34
37
|
|
|
35
|
-
await
|
|
38
|
+
await runCommitCommand(args);
|
|
36
39
|
|
|
37
|
-
// Outro apenas se não for modo silencioso
|
|
38
40
|
if (!args.silent) {
|
|
39
41
|
outro('Até logo! ✨');
|
|
40
42
|
}
|
|
@@ -46,5 +48,4 @@ async function run() {
|
|
|
46
48
|
}
|
|
47
49
|
}
|
|
48
50
|
|
|
49
|
-
|
|
50
|
-
run();
|
|
51
|
+
run();
|