lazycommitt 1.0.4 → 1.0.6

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 (3) hide show
  1. package/README.md +12 -13
  2. package/dist/cli.mjs +43 -36
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -97,12 +97,12 @@ lazycommit --exclude package-lock.json --exclude dist/
97
97
 
98
98
  #### Handling large diffs
99
99
 
100
- For large commits with many files, lazycommit automatically uses intelligent chunking to stay within API limits:
100
+ For large commits with many files, lazycommit automatically stays within API limits:
101
101
 
102
- - **Automatic detection**: Large diffs (>50KB) are automatically detected
103
- - **Smart chunking**: Diffs are split into manageable pieces (default: 6000 tokens)
104
- - **Chunked processing**: Each chunk is analyzed separately, then combined
105
- - **Progress indicators**: Clear feedback during chunked processing
102
+ - **Automatic detection**: Large diffs are detected
103
+ - **Per-file splitting**: Diffs are split by file first
104
+ - **Safe chunking**: Each file diff is chunked conservatively (default: 4000 tokens)
105
+ - **Combination**: Results are combined into one concise message
106
106
 
107
107
  ### Git hook
108
108
 
@@ -215,7 +215,7 @@ lazycommit config set proxy=
215
215
 
216
216
  #### model
217
217
 
218
- Default: `Openai/gpt-oss-120b`
218
+ Default: `openai/gpt-oss-120b`
219
219
 
220
220
  #### timeout
221
221
 
@@ -255,9 +255,9 @@ lazycommit config set type=
255
255
 
256
256
  #### chunk-size
257
257
 
258
- Default: `6000`
258
+ Default: `4000`
259
259
 
260
- The maximum number of tokens per chunk when processing large diffs. This helps avoid API rate limits:
260
+ The maximum number of tokens per chunk when processing large diffs. This helps avoid API limits and keeps requests fast:
261
261
 
262
262
  ```sh
263
263
  lazycommit config set chunk-size 4000
@@ -275,11 +275,10 @@ The tool uses Groq's fast inference API to provide quick and accurate commit mes
275
275
 
276
276
  For large commits that exceed API token limits, lazycommit automatically:
277
277
 
278
- 1. **Detects large diffs** (>50KB or ~12.5k tokens)
279
- 2. **Chunks the diff** into manageable pieces (default: 6000 tokens)
280
- 3. **Processes each chunk** separately to generate partial commit messages
281
- 4. **Combines results** into a single, comprehensive commit message
282
- 5. **Falls back gracefully** if chunking fails, showing individual chunk messages
278
+ 1. **Splits by file** to avoid oversized requests
279
+ 2. **Chunks each file** into manageable pieces (default: 4000 tokens)
280
+ 3. **Processes chunks** and combines results into a single message
281
+ 4. **Falls back gracefully** to a high-level summary if needed
283
282
 
284
283
  This ensures you can commit large changes (like new features, refactoring, or initial project setup) without hitting API limits.
285
284
 
package/dist/cli.mjs CHANGED
@@ -1,18 +1,22 @@
1
1
  #!/usr/bin/env node
2
- var ae=Object.defineProperty;var c=(e,t)=>ae(e,"name",{value:t,configurable:!0});import{command as j,cli as ie}from"cleye";import{readFileSync as re}from"fs";import{fileURLToPath as N,pathToFileURL as ce}from"url";import M,{dirname as le,join as me}from"path";import{execa as k}from"execa";import{dim as I,bgCyan as Y,black as U,green as v,red as P}from"kolorist";import{intro as D,spinner as E,confirm as ge,isCancel as H,outro as $,select as fe}from"@clack/prompts";import y from"fs/promises";import he from"os";import Q from"ini";import L from"groq-sdk";var ue="1.0.4",de={version:ue};const G=class G extends Error{};c(G,"KnownError");let f=G;const O=" ",x=c(e=>{e instanceof Error&&!(e instanceof f)&&(e.stack&&console.error(I(e.stack.split(`
2
+ var ke=Object.defineProperty;var h=(e,t)=>ke(e,"name",{value:t,configurable:!0});import{command as X,cli as ve}from"cleye";import{readFileSync as Ce}from"fs";import{fileURLToPath as V,pathToFileURL as Pe}from"url";import G,{dirname as xe,join as Ae}from"path";import{execa as v}from"execa";import{dim as j,bgCyan as Z,black as L,green as T,red as I}from"kolorist";import{intro as ee,spinner as Y,confirm as Me,isCancel as te,outro as C,select as _e}from"@clack/prompts";import w from"fs/promises";import Te from"os";import se from"ini";import ne from"groq-sdk";var Ie="1.0.6",Ee={version:Ie};const q=class q extends Error{};h(q,"KnownError");let p=q;const D=" ",E=h(e=>{e instanceof Error&&!(e instanceof p)&&(e.stack&&console.error(j(e.stack.split(`
3
3
  `).slice(1).join(`
4
4
  `))),console.error(`
5
- ${O}${I(`lazycommit v${de.version}`)}`),console.error(`
6
- ${O}Please open a Bug report with the information above:`),console.error(`${O}https://github.com/KartikLabhshetwar/lazycommit/issues/new/choose`))},"handleCliError"),q=c(async()=>{const{stdout:e,failed:t}=await k("git",["rev-parse","--show-toplevel"],{reject:!1});if(t)throw new f("The current directory must be a Git repository!");return e},"assertGitRepo"),A=c(e=>`:(exclude)${e}`,"excludeFromDiff"),F=["package-lock.json","pnpm-lock.yaml","node_modules/**","dist/**","build/**",".next/**","coverage/**",".nyc_output/**","*.log","*.tmp","*.temp","*.cache",".DS_Store","Thumbs.db","*.min.js","*.min.css","*.bundle.js","*.bundle.css","*.lock"].map(A),J=c(async e=>{const t=["diff","--cached","--diff-algorithm=minimal"],{stdout:s}=await k("git",[...t,"--name-only",...F,...e?e.map(A):[]]);if(!s)return;const{stdout:n}=await k("git",[...t,...F,...e?e.map(A):[]]);return{files:s.split(`
7
- `),diff:n}},"getStagedDiff"),K=c(e=>`Detected ${e.length.toLocaleString()} staged file${e.length>1?"s":""}`,"getDetectedMessage"),W=c(e=>Math.ceil(e.length/4),"estimateTokenCount"),pe=c((e,t=4e3)=>{if(W(e)<=t)return[e];const n=[],a=e.split(`
8
- `);let o="",i=0;for(const g of a){const m=W(g);i+m>t&&o.length>0?(n.push(o.trim()),o=g+`
9
- `,i=m):(o+=g+`
10
- `,i+=m)}return o.trim().length>0&&n.push(o.trim()),n},"chunkDiff"),we=c(async e=>{const t=["diff","--cached","--diff-algorithm=minimal"],{stdout:s}=await k("git",[...t,"--name-only",...F,...e?e.map(A):[]]);if(!s)return null;const n=s.split(`
11
- `).filter(Boolean),a=await Promise.all(n.map(async o=>{try{const{stdout:i}=await k("git",[...t,"--numstat","--",o]),[g,m]=i.split(" ").slice(0,2).map(Number);return{file:o,additions:g||0,deletions:m||0,changes:(g||0)+(m||0)}}catch{return{file:o,additions:0,deletions:0,changes:0}}}));return{files:n,fileStats:a,totalChanges:a.reduce((o,i)=>o+i.changes,0)}},"getDiffSummary"),B=c(e=>y.lstat(e).then(()=>!0,()=>!1),"fileExists"),ye=["","conventional"],{hasOwnProperty:be}=Object.prototype,X=c((e,t)=>be.call(e,t),"hasOwn"),p=c((e,t,s)=>{if(!t)throw new f(`Invalid config property ${e}: ${s}`)},"parseAssert"),C={GROQ_API_KEY(e){if(!e)throw new f("Please set your Groq API key via `lazycommit config set GROQ_API_KEY=<your token>`");return p("GROQ_API_KEY",e.startsWith("gsk_"),'Must start with "gsk_"'),e},locale(e){return e?(p("locale",e,"Cannot be empty"),p("locale",/^[a-z-]+$/i.test(e),"Must be a valid locale (letters and dashes/underscores). You can consult the list of codes in: https://wikipedia.org/wiki/List_of_ISO_639-1_codes"),e):"en"},generate(e){if(!e)return 1;p("generate",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return p("generate",t>0,"Must be greater than 0"),p("generate",t<=5,"Must be less or equal to 5"),t},type(e){return e?(p("type",ye.includes(e),"Invalid commit type"),e):""},proxy(e){if(!(!e||e.length===0))return p("proxy",/^https?:\/\//.test(e),"Must be a valid URL"),e},model(e){return!e||e.length===0?"openai/gpt-oss-120b":e},timeout(e){if(!e)return 1e4;p("timeout",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return p("timeout",t>=500,"Must be greater than 500ms"),t},"max-length"(e){if(!e)return 50;p("max-length",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return p("max-length",t>=20,"Must be greater than 20 characters"),t},"chunk-size"(e){if(!e)return 4e3;p("chunk-size",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return p("chunk-size",t>=1e3,"Must be at least 1000 tokens"),p("chunk-size",t<=8e3,"Must be at most 8000 tokens (Groq limit)"),t}},S=M.join(he.homedir(),".lazycommit"),V=c(async()=>{if(!await B(S))return Object.create(null);const t=await y.readFile(S,"utf8");return Q.parse(t)},"readConfigFile"),R=c(async(e,t)=>{const s=await V(),n={};for(const a of Object.keys(C)){const o=C[a],i=e?.[a]??s[a];if(t)try{n[a]=o(i)}catch{}else n[a]=o(i)}return n},"getConfig"),ke=c(async e=>{const t=await V();for(const[s,n]of e){if(!X(C,s))throw new f(`Invalid config property: ${s}`);const a=C[s](n);t[s]=a}await y.writeFile(S,Q.stringify(t),"utf8")},"setConfigs"),$e={"":"<commit message>",conventional:"<type>(<optional scope>): <commit message>"},Z={"":"",conventional:`Choose the most appropriate type from the following categories that best describes the git diff:
5
+ ${D}${j(`lazycommit v${Ee.version}`)}`),console.error(`
6
+ ${D}Please open a Bug report with the information above:`),console.error(`${D}https://github.com/KartikLabhshetwar/lazycommit/issues/new/choose`))},"handleCliError"),oe=h(async()=>{const{stdout:e,failed:t}=await v("git",["rev-parse","--show-toplevel"],{reject:!1});if(t)throw new p("The current directory must be a Git repository!");return e},"assertGitRepo"),F=h(e=>`:(exclude)${e}`,"excludeFromDiff"),N=["package-lock.json","pnpm-lock.yaml","node_modules/**","dist/**","build/**",".next/**","coverage/**",".nyc_output/**","*.log","*.tmp","*.temp","*.cache",".DS_Store","Thumbs.db","*.min.js","*.min.css","*.bundle.js","*.bundle.css","*.lock"].map(F),ae=h(async e=>{const t=["diff","--cached","--diff-algorithm=minimal"],{stdout:s}=await v("git",[...t,"--name-only",...N,...e?e.map(F):[]]);if(!s)return;const{stdout:n}=await v("git",[...t,...N,...e?e.map(F):[]]);return{files:s.split(`
7
+ `),diff:n}},"getStagedDiff"),ie=h(e=>`Detected ${e.length.toLocaleString()} staged file${e.length>1?"s":""}`,"getDetectedMessage"),U=h(e=>Math.ceil(e.length/4),"estimateTokenCount"),re=h((e,t=4e3)=>{if(U(e)<=t)return[e];const n=[],a=e.split(`
8
+ `);let o="",c=0;for(const m of a){const g=U(m);c+g>t&&o.length>0?(n.push(o.trim()),o=m+`
9
+ `,c=g):(o+=m+`
10
+ `,c+=g)}return o.trim().length>0&&n.push(o.trim()),n},"chunkDiff"),ce=h(async e=>{const t=["diff","--cached","--diff-algorithm=minimal"],{stdout:s}=await v("git",[...t,"--name-only",...N,...e?e.map(F):[]]);if(!s)return null;const n=s.split(`
11
+ `).filter(Boolean),a=await Promise.all(n.map(async o=>{try{const{stdout:c}=await v("git",[...t,"--numstat","--",o]),[m,g]=c.split(" ").slice(0,2).map(Number);return{file:o,additions:m||0,deletions:g||0,changes:(m||0)+(g||0)}}catch{return{file:o,additions:0,deletions:0,changes:0}}}));return{files:n,fileStats:a,totalChanges:a.reduce((o,c)=>o+c.changes,0)}},"getDiffSummary"),le=h(e=>{const t=[];let s="";const n=e.split(`
12
+ `);for(const a of n)a.startsWith("diff --git ")?(s.trim().length>0&&t.push(s.trim()),s=a+`
13
+ `):s+=a+`
14
+ `;return s.trim().length>0&&t.push(s.trim()),t},"splitDiffByFile"),Fe=h(async(e,t=20)=>{const s=await ce(e);if(!s)return null;const{fileStats:n}=s,a=[...n].sort((u,r)=>r.changes-u.changes),o=a.slice(0,Math.max(1,t)),c=s.files.length,m=s.totalChanges,g=n.reduce((u,r)=>u+(r.additions||0),0),d=n.reduce((u,r)=>u+(r.deletions||0),0),i=[];i.push(`Files changed: ${c}`),i.push(`Additions: ${g}, Deletions: ${d}, Total changes: ${m}`),i.push("Top files by changes:");for(const u of o)i.push(`- ${u.file} (+${u.additions} / -${u.deletions}, ${u.changes} changes)`);return a.length>o.length&&i.push(`\u2026and ${a.length-o.length} more files`),i.join(`
15
+ `)},"buildCompactSummary"),me=h(e=>w.lstat(e).then(()=>!0,()=>!1),"fileExists"),Oe=["","conventional"],{hasOwnProperty:Re}=Object.prototype,fe=h((e,t)=>Re.call(e,t),"hasOwn"),y=h((e,t,s)=>{if(!t)throw new p(`Invalid config property ${e}: ${s}`)},"parseAssert"),O={GROQ_API_KEY(e){if(!e)throw new p("Please set your Groq API key via `lazycommit config set GROQ_API_KEY=<your token>`");return y("GROQ_API_KEY",e.startsWith("gsk_"),'Must start with "gsk_"'),e},locale(e){return e?(y("locale",e,"Cannot be empty"),y("locale",/^[a-z-]+$/i.test(e),"Must be a valid locale (letters and dashes/underscores). You can consult the list of codes in: https://wikipedia.org/wiki/List_of_ISO_639-1_codes"),e):"en"},generate(e){if(!e)return 1;y("generate",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return y("generate",t>0,"Must be greater than 0"),y("generate",t<=5,"Must be less or equal to 5"),t},type(e){return e?(y("type",Oe.includes(e),"Invalid commit type"),e):""},proxy(e){if(!(!e||e.length===0))return y("proxy",/^https?:\/\//.test(e),"Must be a valid URL"),e},model(e){return!e||e.length===0?"openai/gpt-oss-120b":e},timeout(e){if(!e)return 1e4;y("timeout",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return y("timeout",t>=500,"Must be greater than 500ms"),t},"max-length"(e){if(!e)return 50;y("max-length",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return y("max-length",t>=20,"Must be greater than 20 characters"),t},"chunk-size"(e){if(!e)return 4e3;y("chunk-size",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return y("chunk-size",t>=1e3,"Must be at least 1000 tokens"),y("chunk-size",t<=8e3,"Must be at most 8000 tokens (Groq limit)"),t}},B=G.join(Te.homedir(),".lazycommit"),ge=h(async()=>{if(!await me(B))return Object.create(null);const t=await w.readFile(B,"utf8");return se.parse(t)},"readConfigFile"),H=h(async(e,t)=>{const s=await ge(),n={};for(const a of Object.keys(O)){const o=O[a],c=e?.[a]??s[a];if(t)try{n[a]=o(c)}catch{}else n[a]=o(c)}return n},"getConfig"),Se=h(async e=>{const t=await ge();for(const[s,n]of e){if(!fe(O,s))throw new p(`Invalid config property: ${s}`);const a=O[s](n);t[s]=a}await w.writeFile(B,se.stringify(t),"utf8")},"setConfigs"),ze={"":"<commit message>",conventional:"<type>(<optional scope>): <commit message>"},he={"":"",conventional:`Choose the most appropriate type from the following categories that best describes the git diff:
12
16
 
13
17
  ${JSON.stringify({feat:"A new feature for the user",fix:"A bug fix",docs:"Documentation only changes",style:"Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)",refactor:"A code change that neither fixes a bug nor adds a feature",perf:"A code change that improves performance",test:"Adding missing tests or correcting existing tests",build:"Changes that affect the build system or external dependencies",ci:"Changes to our CI configuration files and scripts",chore:"Other changes that don't modify src or test files",revert:"Reverts a previous commit"},null,2)}
14
18
 
15
- IMPORTANT: Use the exact type name from the list above.`},ve=c((e,t,s)=>`You are an expert software engineer and git commit message writer. Your task is to analyze git diffs and generate clear, concise, and professional commit messages.
19
+ IMPORTANT: Use the exact type name from the list above.`},R=h((e,t,s)=>`You are an expert software engineer and git commit message writer. Your task is to analyze git diffs and generate clear, concise, and professional commit messages.
16
20
 
17
21
  ## Instructions:
18
22
  1. Analyze the provided git diff carefully
@@ -33,11 +37,11 @@ IMPORTANT: Use the exact type name from the list above.`},ve=c((e,t,s)=>`You are
33
37
 
34
38
  ## Language: ${e}
35
39
  ## Maximum length: ${t} characters
36
- ## Output format: ${$e[s]||"<commit message>"}
40
+ ## Output format: ${ze[s]||"<commit message>"}
37
41
 
38
- ${Z[s]?`
42
+ ${he[s]?`
39
43
  ## Commit Type Guidelines:
40
- ${Z[s]}`:""}
44
+ ${he[s]}`:""}
41
45
 
42
46
  ## Examples of good commit messages:
43
47
  - "feat: Add user authentication with JWT tokens"
@@ -54,43 +58,46 @@ ${Z[s]}`:""}
54
58
  - "WIP"
55
59
  - "Stuff"
56
60
 
57
- Remember: Your response will be used directly as the git commit message. Make it professional and informative.`,"generatePrompt"),Pe=c(async(e,t,s,n,a,o,i,g,m,u,l)=>{const w=new L({apiKey:e,timeout:u});try{return m>1?{choices:(await Promise.all(Array.from({length:m},()=>w.chat.completions.create({model:t,messages:s,temperature:n,top_p:a,frequency_penalty:o,presence_penalty:i,max_tokens:g,n:1})))).flatMap(d=>d.choices)}:await w.chat.completions.create({model:t,messages:s,temperature:n,top_p:a,frequency_penalty:o,presence_penalty:i,max_tokens:g,n:1})}catch(r){if(r instanceof L.APIError){let h=`Groq API Error: ${r.status} - ${r.name}`;throw r.message&&(h+=`
61
+ Remember: Your response will be used directly as the git commit message. Make it professional and informative.`,"generatePrompt"),S=h(async(e,t,s,n,a,o,c,m,g,d,i)=>{const u=new ne({apiKey:e,timeout:d});try{return g>1?{choices:(await Promise.all(Array.from({length:g},()=>u.chat.completions.create({model:t,messages:s,temperature:n,top_p:a,frequency_penalty:o,presence_penalty:c,max_tokens:m,n:1})))).flatMap(l=>l.choices)}:await u.chat.completions.create({model:t,messages:s,temperature:n,top_p:a,frequency_penalty:o,presence_penalty:c,max_tokens:m,n:1})}catch(r){if(r instanceof ne.APIError){let f=`Groq API Error: ${r.status} - ${r.name}`;throw r.message&&(f+=`
58
62
 
59
- ${r.message}`),r.status===500&&(h+=`
63
+ ${r.message}`),r.status===500&&(f+=`
60
64
 
61
- Check the API status: https://console.groq.com/status`),(r.status===413||r.message&&r.message.includes("rate_limit_exceeded"))&&(h+=`
65
+ Check the API status: https://console.groq.com/status`),(r.status===413||r.message&&r.message.includes("rate_limit_exceeded"))&&(f+=`
62
66
 
63
67
  \u{1F4A1} Tip: Your diff is too large. Try:
64
68
  1. Commit files in smaller batches
65
69
  2. Exclude large files with --exclude
66
70
  3. Use a different model with --model
67
- 4. Check if you have build artifacts staged (dist/, .next/, etc.)`),new f(h)}throw r.code==="ENOTFOUND"?new f(`Error connecting to ${r.hostname} (${r.syscall}). Are you connected to the internet?`):r}},"createChatCompletion"),xe=c(e=>e.trim().replace(/[\n\r]/g,"").replace(/(\w)\.$/,"$1"),"sanitizeMessage"),Ae=c(e=>Array.from(new Set(e)),"deduplicateMessages"),_=c(async(e,t,s,n,a,o,i,g,m)=>{try{const u=await Pe(e,t,[{role:"system",content:ve(s,o,i)},{role:"user",content:n}],.7,1,0,0,Math.max(200,o*8),a,g,m);return Ae(u.choices.filter(l=>l.message?.content).map(l=>xe(l.message.content)))}catch(u){const l=u;throw l.code==="ENOTFOUND"?new f(`Error connecting to ${l.hostname} (${l.syscall}). Are you connected to the internet?`):l}},"generateCommitMessage"),Ce=c(async(e,t,s,n,a,o,i,g,m,u=6e3)=>{const l=pe(n,u);if(l.length===1)try{return await _(e,t,s,n,a,o,i,g,m)}catch(r){throw new f(`Failed to generate commit message: ${r instanceof Error?r.message:"Unknown error"}`)}const w=[];for(let r=0;r<l.length;r++){const h=l[r],d=`This is part ${r+1} of ${l.length} of a large diff.
68
- Please generate a commit message that describes the changes in this specific part.
69
- Focus on the most significant changes in this chunk.
71
+ 4. Check if you have build artifacts staged (dist/, .next/, etc.)`),new p(f)}throw r.code==="ENOTFOUND"?new p(`Error connecting to ${r.hostname} (${r.syscall}). Are you connected to the internet?`):r}},"createChatCompletion"),x=h(e=>e.trim().replace(/[\n\r]/g,"").replace(/(\w)\.$/,"$1"),"sanitizeMessage"),ue=h(e=>Array.from(new Set(e)),"deduplicateMessages"),Ge=["feat:","fix:","docs:","style:","refactor:","perf:","test:","build:","ci:","chore:","revert:"],Q=h((e,t)=>{const s=e.replace(/\s+/g," ").trim(),n=s.match(/\b(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)\b\s*:?\s+[^.\n]+/i);let a=n?n[0]:s.split(/[.!?]/)[0];const o=a.toLowerCase();for(const c of Ge){const m=c.slice(0,-1);if(o.startsWith(m+" ")&&!o.startsWith(c)){a=m+": "+a.slice(m.length+1);break}}return a=x(a),a?(a.length>t&&(a=a.slice(0,t)),a):null},"deriveMessageFromReasoning"),W=h(async(e,t,s,n,a,o,c,m,g)=>{try{const d=await S(e,t,[{role:"system",content:R(s,o,c)},{role:"user",content:n}],.7,1,0,0,Math.max(200,o*8),a,m,g),i=d.choices.map(r=>r.message?.content||"").map(r=>x(r)).filter(Boolean);if(i.length>0)return ue(i);const u=d.choices.map(r=>r.message?.reasoning||"").filter(Boolean);for(const r of u){const f=Q(r,o);if(f)return[f]}return[]}catch(d){const i=d;throw i.code==="ENOTFOUND"?new p(`Error connecting to ${i.hostname} (${i.syscall}). Are you connected to the internet?`):i}},"generateCommitMessage"),de=h(async(e,t,s,n,a,o,c,m,g,d=6e3)=>{const u=le(n).flatMap(l=>re(l,d)),r=u.length>0?u:re(n,d);if(r.length===1)try{return await W(e,t,s,n,a,o,c,m,g)}catch(l){throw new p(`Failed to generate commit message: ${l instanceof Error?l.message:"Unknown error"}`)}const f=[];for(let l=0;l<r.length;l++){const $=r[l],b=U($)+1200;let k=Math.max(200,o*8);b+k>7500&&(k=Math.max(200,7500-b));const A=`Analyze this git diff and propose a concise commit message limited to ${o} characters. Focus on the most significant intent of the change.
70
72
 
71
- ${h}`;try{const b=await _(e,t,s,d,1,o,i,g,m);b.length>0&&w.push(b[0])}catch(b){console.warn(`Failed to process chunk ${r+1}:`,b instanceof Error?b.message:"Unknown error")}}if(w.length===0)throw new f("Failed to generate commit messages for any chunks");if(w.length>1){const r=`I have ${w.length} commit messages for different parts of a large change:
73
+ ${$}`;try{const P=await S(e,t,[{role:"system",content:R(s,o,c)},{role:"user",content:A}],.7,1,0,0,k,1,m,g),J=(P.choices||[]).map(M=>M.message?.content).filter(Boolean);if(J.length>0)f.push(x(J[0]));else{const M=P.choices.map(_=>_.message?.reasoning||"").filter(Boolean);if(M.length>0){const _=Q(M[0],o);_&&f.push(_)}}}catch(P){console.warn(`Failed to process chunk ${l+1}:`,P instanceof Error?P.message:"Unknown error")}}if(f.length===0){const l=le(n).map(b=>(b.split(`
74
+ `,1)[0]||"").split(" ")[2]?.replace("a/","")||"").filter(Boolean).slice(0,15),$=`Generate a single, concise commit message (<= ${o} chars) summarizing changes across these files:
75
+ ${l.map(b=>`- ${b}`).join(`
76
+ `)}`;try{const k=((await S(e,t,[{role:"system",content:R(s,o,c)},{role:"user",content:$}],.7,1,0,0,Math.max(200,o*8),1,m,g)).choices||[]).map(A=>A.message?.content).filter(Boolean);if(k.length>0)return[x(k[0])]}catch{}throw new p("Failed to generate commit messages for any chunks")}if(f.length>1){const l=`I have ${f.length} commit messages for different parts of a large change:
72
77
 
73
- ${w.map((h,d)=>`${d+1}. ${h}`).join(`
78
+ ${f.map(($,b)=>`${b+1}. ${$}`).join(`
74
79
  `)}
75
80
 
76
81
  Please generate a single, comprehensive commit message that captures the overall changes.
77
- The message should be concise but cover the main aspects of all the changes.`;try{return await _(e,t,s,r,a,o,i,g,m)}catch{return w}}return w},"generateCommitMessageFromChunks");var _e=c(async(e,t,s,n,a)=>(async()=>{D(Y(U(" lazycommit "))),await q();const o=E();s&&await k("git",["add","--update"]),o.start("Detecting staged files");const i=await J(t);if(!i)throw o.stop("Detecting staged files"),new f("No staged changes found. Stage your changes manually, or automatically stage all changes with the `--all` flag.");const g=await we(t);i.diff.length>5e4&&g?o.stop(`${K(i.files)} (${g.totalChanges.toLocaleString()} changes):
78
- ${i.files.map(d=>` ${d}`).join(`
82
+ The message should be concise but cover the main aspects of all the changes.`;try{return await W(e,t,s,l,a,o,c,m,g)}catch{return f}}return f},"generateCommitMessageFromChunks"),je=h(async(e,t,s,n,a,o,c,m,g)=>{const d=`This is a compact summary of staged changes. Generate a single, concise commit message within ${o} characters that reflects the overall intent.
83
+
84
+ ${n}`,i=await S(e,t,[{role:"system",content:R(s,o,c)},{role:"user",content:d}],.7,1,0,0,Math.max(200,o*8),a,m),u=(i.choices||[]).map(f=>f.message?.content||"").map(f=>x(f)).filter(Boolean);if(u.length>0)return ue(u);const r=i.choices.map(f=>f.message?.reasoning||"").filter(Boolean);for(const f of r){const l=Q(f,o);if(l)return[l]}return[]},"generateCommitMessageFromSummary");var Ye=h(async(e,t,s,n,a)=>(async()=>{ee(Z(L(" lazycommit "))),await oe();const o=Y();s&&await v("git",["add","--update"]),o.start("Detecting staged files");const c=await ae(t);if(!c)throw o.stop("Detecting staged files"),new p("No staged changes found. Stage your changes manually, or automatically stage all changes with the `--all` flag.");const m=await ce(t),g=c.diff.length>5e4;g&&m?o.stop(`${ie(c.files)} (${m.totalChanges.toLocaleString()} changes):
85
+ ${c.files.map(l=>` ${l}`).join(`
79
86
  `)}
80
87
 
81
- \u26A0\uFE0F Large diff detected - using chunked processing`):o.stop(`${K(i.files)}:
82
- ${i.files.map(d=>` ${d}`).join(`
83
- `)}`);const{env:u}=process,l=await R({GROQ_API_KEY:u.GROQ_API_KEY,proxy:u.https_proxy||u.HTTPS_PROXY||u.http_proxy||u.HTTP_PROXY,generate:e?.toString(),type:n?.toString()}),w=E();w.start("The AI is analyzing your changes");let r;try{r=await Ce(l.GROQ_API_KEY,l.model,l.locale,i.diff,l.generate,l["max-length"],l.type,l.timeout,l.proxy,l["chunk-size"])}finally{w.stop("Changes analyzed")}if(r.length===0)throw new f("No commit messages were generated. Try again.");let h;if(r.length===1){[h]=r;const d=await ge({message:`Use this commit message?
84
-
85
- ${h}
86
- `});if(!d||H(d)){$("Commit cancelled");return}}else{const d=await fe({message:`Pick a commit message to use: ${I("(Ctrl+c to exit)")}`,options:r.map(b=>({label:b,value:b}))});if(H(d)){$("Commit cancelled");return}h=d}await k("git",["commit","-m",h,...a]),$(`${v("\u2714")} Successfully committed!`)})().catch(o=>{$(`${P("\u2716")} ${o.message}`),x(o),process.exit(1)}),"lazycommit");const[z,Te]=process.argv.slice(2);var Me=c(()=>(async()=>{if(!z)throw new f('Commit message file path is missing. This file should be called from the "prepare-commit-msg" git hook');if(Te)return;const e=await J();if(!e)return;D(Y(U(" lazycommit ")));const{env:t}=process,s=await R({GROQ_API_KEY:t.GROQ_API_KEY,proxy:t.https_proxy||t.HTTPS_PROXY||t.http_proxy||t.HTTP_PROXY}),n=E();n.start("The AI is analyzing your changes");let a;try{a=await _(s.GROQ_API_KEY,s.model,s.locale,e.diff,s.generate,s["max-length"],s.type,s.timeout,s.proxy)}finally{n.stop("Changes analyzed")}const i=await y.readFile(z,"utf8")!=="",g=a.length>1;let m="";i&&(m=`# \u{1F916} AI generated commit${g?"s":""}
87
- `),g?(i&&(m+=`# Select one of the following messages by uncommeting:
88
- `),m+=`
89
- ${a.map(u=>`# ${u}`).join(`
90
- `)}`):(i&&(m+=`# Edit the message below and commit:
91
- `),m+=`
88
+ \u26A0\uFE0F Large diff detected - using chunked processing`):o.stop(`${ie(c.files)}:
89
+ ${c.files.map(l=>` ${l}`).join(`
90
+ `)}`);const{env:d}=process,i=await H({GROQ_API_KEY:d.GROQ_API_KEY,proxy:d.https_proxy||d.HTTPS_PROXY||d.http_proxy||d.HTTP_PROXY,generate:e?.toString(),type:n?.toString()}),u=Y();u.start("The AI is analyzing your changes");let r;try{if(g){const l=await Fe(t,25);l?r=await je(i.GROQ_API_KEY,i.model,i.locale,l,i.generate,i["max-length"],i.type,i.timeout,i.proxy):r=await de(i.GROQ_API_KEY,i.model,i.locale,c.diff,i.generate,i["max-length"],i.type,i.timeout,i.proxy,i["chunk-size"])}else r=await de(i.GROQ_API_KEY,i.model,i.locale,c.diff,i.generate,i["max-length"],i.type,i.timeout,i.proxy,i["chunk-size"])}finally{u.stop("Changes analyzed")}if(r.length===0)throw new p("No commit messages were generated. Try again.");let f;if(r.length===1){[f]=r;const l=await Me({message:`Use this commit message?
91
+
92
+ ${f}
93
+ `});if(!l||te(l)){C("Commit cancelled");return}}else{const l=await _e({message:`Pick a commit message to use: ${j("(Ctrl+c to exit)")}`,options:r.map($=>({label:$,value:$}))});if(te(l)){C("Commit cancelled");return}f=l}await v("git",["commit","-m",f,...a]),C(`${T("\u2714")} Successfully committed!`)})().catch(o=>{C(`${I("\u2716")} ${o.message}`),E(o),process.exit(1)}),"lazycommit");const[K,De]=process.argv.slice(2);var Ne=h(()=>(async()=>{if(!K)throw new p('Commit message file path is missing. This file should be called from the "prepare-commit-msg" git hook');if(De)return;const e=await ae();if(!e)return;ee(Z(L(" lazycommit ")));const{env:t}=process,s=await H({GROQ_API_KEY:t.GROQ_API_KEY,proxy:t.https_proxy||t.HTTPS_PROXY||t.http_proxy||t.HTTP_PROXY}),n=Y();n.start("The AI is analyzing your changes");let a;try{a=await W(s.GROQ_API_KEY,s.model,s.locale,e.diff,s.generate,s["max-length"],s.type,s.timeout,s.proxy)}finally{n.stop("Changes analyzed")}const c=await w.readFile(K,"utf8")!=="",m=a.length>1;let g="";c&&(g=`# \u{1F916} AI generated commit${m?"s":""}
94
+ `),m?(c&&(g+=`# Select one of the following messages by uncommeting:
95
+ `),g+=`
96
+ ${a.map(d=>`# ${d}`).join(`
97
+ `)}`):(c&&(g+=`# Edit the message below and commit:
98
+ `),g+=`
92
99
  ${a[0]}
93
- `),await y.appendFile(z,m),$(`${v("\u2714")} Saved commit message!`)})().catch(e=>{$(`${P("\u2716")} ${e.message}`),x(e),process.exit(1)}),"prepareCommitMessageHook"),Ie=j({name:"config",parameters:["<mode>","<key=value...>"]},e=>{(async()=>{const{mode:t,keyValue:s}=e._;if(t==="get"){const n=await R({},!0);for(const a of s)X(n,a)&&console.log(`${a}=${n[a]}`);return}if(t==="set"){await ke(s.map(n=>n.split("=")));return}throw new f(`Invalid mode: ${t}`)})().catch(t=>{console.error(`${P("\u2716")} ${t.message}`),x(t),process.exit(1)})});const ee="prepare-commit-msg",te=`.git/hooks/${ee}`,T=N(new URL("cli.mjs",import.meta.url)),Ee=process.argv[1].replace(/\\/g,"/").endsWith(`/${te}`),se=process.platform==="win32",ne=`
100
+ `),await w.appendFile(K,g),C(`${T("\u2714")} Saved commit message!`)})().catch(e=>{C(`${I("\u2716")} ${e.message}`),E(e),process.exit(1)}),"prepareCommitMessageHook"),Ue=X({name:"config",parameters:["<mode>","<key=value...>"]},e=>{(async()=>{const{mode:t,keyValue:s}=e._;if(t==="get"){const n=await H({},!0);for(const a of s)fe(n,a)&&console.log(`${a}=${n[a]}`);return}if(t==="set"){await Se(s.map(n=>n.split("=")));return}throw new p(`Invalid mode: ${t}`)})().catch(t=>{console.error(`${I("\u2716")} ${t.message}`),E(t),process.exit(1)})});const pe="prepare-commit-msg",ye=`.git/hooks/${pe}`,z=V(new URL("cli.mjs",import.meta.url)),Be=process.argv[1].replace(/\\/g,"/").endsWith(`/${ye}`),we=process.platform==="win32",$e=`
94
101
  #!/usr/bin/env node
95
- import(${JSON.stringify(ce(T))})
96
- `.trim();var Oe=j({name:"hook",parameters:["<install/uninstall>"]},e=>{(async()=>{const t=await q(),{installUninstall:s}=e._,n=M.join(t,te),a=await B(n);if(s==="install"){if(a){if(await y.realpath(n).catch(()=>{})===T){console.warn("The hook is already installed");return}throw new f(`A different ${ee} hook seems to be installed. Please remove it before installing lazycommit.`)}await y.mkdir(M.dirname(n),{recursive:!0}),se?await y.writeFile(n,ne):(await y.symlink(T,n,"file"),await y.chmod(n,493)),console.log(`${v("\u2714")} Hook installed`);return}if(s==="uninstall"){if(!a){console.warn("Hook is not installed");return}if(se){if(await y.readFile(n,"utf8")!==ne){console.warn("Hook is not installed");return}}else if(await y.realpath(n)!==T){console.warn("Hook is not installed");return}await y.rm(n),console.log(`${v("\u2714")} Hook uninstalled`);return}throw new f(`Invalid mode: ${s}`)})().catch(t=>{console.error(`${P("\u2716")} ${t.message}`),x(t),process.exit(1)})});const Fe=N(import.meta.url),Se=le(Fe),Re=JSON.parse(re(me(Se,"../package.json"),"utf8")),{description:ze,version:Ge}=Re,oe=process.argv.slice(2);ie({name:"lazycommit",version:Ge,flags:{generate:{type:Number,description:"Number of messages to generate (Warning: generating multiple costs more) (default: 1)",alias:"g"},exclude:{type:[String],description:"Files to exclude from AI analysis",alias:"x"},all:{type:Boolean,description:"Automatically stage changes in tracked files for the commit",alias:"a",default:!1},type:{type:String,description:"Type of commit message to generate",alias:"t"}},commands:[Ie,Oe],help:{description:ze},ignoreArgv:c(e=>e==="unknown-flag"||e==="argument","ignoreArgv")},e=>{Ee?Me():_e(e.flags.generate,e.flags.exclude,e.flags.all,e.flags.type,oe)},oe);
102
+ import(${JSON.stringify(Pe(z))})
103
+ `.trim();var He=X({name:"hook",parameters:["<install/uninstall>"]},e=>{(async()=>{const t=await oe(),{installUninstall:s}=e._,n=G.join(t,ye),a=await me(n);if(s==="install"){if(a){if(await w.realpath(n).catch(()=>{})===z){console.warn("The hook is already installed");return}throw new p(`A different ${pe} hook seems to be installed. Please remove it before installing lazycommit.`)}await w.mkdir(G.dirname(n),{recursive:!0}),we?await w.writeFile(n,$e):(await w.symlink(z,n,"file"),await w.chmod(n,493)),console.log(`${T("\u2714")} Hook installed`);return}if(s==="uninstall"){if(!a){console.warn("Hook is not installed");return}if(we){if(await w.readFile(n,"utf8")!==$e){console.warn("Hook is not installed");return}}else if(await w.realpath(n)!==z){console.warn("Hook is not installed");return}await w.rm(n),console.log(`${T("\u2714")} Hook uninstalled`);return}throw new p(`Invalid mode: ${s}`)})().catch(t=>{console.error(`${I("\u2716")} ${t.message}`),E(t),process.exit(1)})});const Qe=V(import.meta.url),We=xe(Qe),Ke=JSON.parse(Ce(Ae(We,"../package.json"),"utf8")),{description:qe,version:Je}=Ke,be=process.argv.slice(2);ve({name:"lazycommit",version:Je,flags:{generate:{type:Number,description:"Number of messages to generate (Warning: generating multiple costs more) (default: 1)",alias:"g"},exclude:{type:[String],description:"Files to exclude from AI analysis",alias:"x"},all:{type:Boolean,description:"Automatically stage changes in tracked files for the commit",alias:"a",default:!1},type:{type:String,description:"Type of commit message to generate",alias:"t"}},commands:[Ue,He],help:{description:qe},ignoreArgv:h(e=>e==="unknown-flag"||e==="argument","ignoreArgv")},e=>{Be?Ne():Ye(e.flags.generate,e.flags.exclude,e.flags.all,e.flags.type,be)},be);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lazycommitt",
3
- "version": "1.0.4",
3
+ "version": "1.0.6",
4
4
  "description": "Writes your git commit messages for you with AI using Groq",
5
5
  "main": "index.js",
6
6
  "keywords": [