lazycommitt 1.0.2 → 1.0.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.
- package/dist/cli.mjs +20 -20
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
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(`
|
|
3
3
|
`).slice(1).join(`
|
|
4
4
|
`))),console.error(`
|
|
5
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
|
|
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=
|
|
8
|
-
`);let
|
|
9
|
-
`,i=m):(
|
|
10
|
-
`,i+=m)}return
|
|
11
|
-
`).filter(Boolean),
|
|
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:
|
|
12
12
|
|
|
13
13
|
${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
14
|
|
|
@@ -33,7 +33,7 @@ IMPORTANT: Use the exact type name from the list above.`},ve=c((e,t,s)=>`You are
|
|
|
33
33
|
|
|
34
34
|
## Language: ${e}
|
|
35
35
|
## Maximum length: ${t} characters
|
|
36
|
-
## Output format: ${
|
|
36
|
+
## Output format: ${$e[s]||"<commit message>"}
|
|
37
37
|
|
|
38
38
|
${Z[s]?`
|
|
39
39
|
## Commit Type Guidelines:
|
|
@@ -54,7 +54,7 @@ ${Z[s]}`:""}
|
|
|
54
54
|
- "WIP"
|
|
55
55
|
- "Stuff"
|
|
56
56
|
|
|
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,o,
|
|
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+=`
|
|
58
58
|
|
|
59
59
|
${r.message}`),r.status===500&&(h+=`
|
|
60
60
|
|
|
@@ -64,33 +64,33 @@ Check the API status: https://console.groq.com/status`),(r.status===413||r.messa
|
|
|
64
64
|
1. Commit files in smaller batches
|
|
65
65
|
2. Exclude large files with --exclude
|
|
66
66
|
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"),
|
|
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
68
|
Please generate a commit message that describes the changes in this specific part.
|
|
69
69
|
Focus on the most significant changes in this chunk.
|
|
70
70
|
|
|
71
|
-
${h}`;try{const
|
|
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:
|
|
72
72
|
|
|
73
73
|
${w.map((h,d)=>`${d+1}. ${h}`).join(`
|
|
74
74
|
`)}
|
|
75
75
|
|
|
76
76
|
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
|
|
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
78
|
${i.files.map(d=>` ${d}`).join(`
|
|
79
79
|
`)}
|
|
80
80
|
|
|
81
|
-
\u26A0\uFE0F Large diff detected - using chunked processing`):
|
|
81
|
+
\u26A0\uFE0F Large diff detected - using chunked processing`):o.stop(`${K(i.files)}:
|
|
82
82
|
${i.files.map(d=>` ${d}`).join(`
|
|
83
|
-
`)}`);const{env:u}=process,l=await
|
|
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
84
|
|
|
85
85
|
${h}
|
|
86
|
-
`});if(!d||H(d)){
|
|
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
87
|
`),g?(i&&(m+=`# Select one of the following messages by uncommeting:
|
|
88
88
|
`),m+=`
|
|
89
|
-
${
|
|
89
|
+
${a.map(u=>`# ${u}`).join(`
|
|
90
90
|
`)}`):(i&&(m+=`# Edit the message below and commit:
|
|
91
91
|
`),m+=`
|
|
92
|
-
${
|
|
93
|
-
`),await y.appendFile(z,m)
|
|
92
|
+
${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=`
|
|
94
94
|
#!/usr/bin/env node
|
|
95
|
-
import(${JSON.stringify(ce(
|
|
96
|
-
`.trim();var Oe=
|
|
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);
|