nuwax-file-server 1.3.0-beta.25 → 1.3.0-beta.26
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.js +1 -1
- package/dist/service/gitService.js +5 -5
- package/dist/utils/git/gitUtils.js +4 -4
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Command as ee}from"commander";import{createRequire as te}from"module";import f from"path";import U from"os";import c from"fs-extra";import{spawn as E}from"cross-spawn";import V from"tree-kill";import{fileURLToPath as q}from"url";import{execFileSync as R}from"child_process";import M from"http";import{createRequire as G}from"module";var I=f.dirname(q(import.meta.url)),H=G(import.meta.url),n={name:"nuwax-file-server",pidDir:f.join(U.tmpdir(),"nuwax-file-server"),pidFileName:"server.pid",lockFileName:"start.lock",defaultStopTimeout:3e4,defaultStartTimeout:3e4,staleLockTimeout:12e4,checkInterval:500};function $(){return f.join(n.pidDir,n.pidFileName)}function F(){return f.join(n.pidDir,n.lockFileName)}function J(){let e=[f.join(I,"..","server.js"),f.join(I,"server.js")];for(let t of e)if(c.existsSync(t))return t;return e[0]}function W(){let e=["../../package.json","../package.json"];for(let t of e)try{let o=H(t);if(o?.version)return o.version}catch{}return"unknown"}function x(){try{let e=$();if(!c.existsSync(e))return null;let t=c.readFileSync(e,"utf8"),o=JSON.parse(t);return!o||typeof o.pid!="number"?null:o}catch(e){return e.code!=="ENOENT"&&console.error(`Read PID file failed: ${e.message}`),null}}function B(e){try{let t=$();c.ensureDirSync(n.pidDir),c.writeFileSync(t,JSON.stringify(e,null,2)),console.debug(`PID file written: ${t}`)}catch(t){throw console.error(`Write PID file failed: ${t.message}`),t}}function v(){try{let e=$();c.existsSync(e)&&(c.removeSync(e),console.debug(`PID file deleted: ${e}`))}catch(e){console.error(`Delete PID file failed: ${e.message}`)}}function g(e){try{return process.kill(e,0),!0}catch(t){return t.code!=="ESRCH"}}function K(e){try{return k()?R("powershell",["-NoProfile","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${e}").CommandLine`],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim():R("ps",["-p",String(e),"-o","command="],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return""}}function X(e){if(!g(e))return!1;let t=K(e);if(!t)return!1;let o=t.toLowerCase(),s=f.basename(f.join(I,"..","server.js")).toLowerCase(),i=n.name.toLowerCase();return o.includes(s)||o.includes(i)}function z(){c.ensureDirSync(n.pidDir);let e=F(),t=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`,o=JSON.stringify({pid:process.pid,token:t,createdAt:new Date().toISOString()},null,2);try{let s=c.openSync(e,"wx");return c.writeSync(s,o),{fd:s,token:t}}catch(s){if(s.code!=="EEXIST")throw s;try{let i=c.readFileSync(e,"utf8"),r=JSON.parse(i),a=Number(r?.pid),u=r?.createdAt?new Date(r.createdAt).getTime():0,l=Date.now()-u,C=Number.isFinite(a)&&a>0&&g(a),p=!u||Number.isNaN(l)||l>n.staleLockTimeout;if(!C||p){c.removeSync(e);let S=c.openSync(e,"wx");return c.writeSync(S,o),console.warn("Detected stale start lock, auto cleaned"),{fd:S,token:t}}}catch{c.removeSync(e);let r=c.openSync(e,"wx");return c.writeSync(r,o),console.warn("Detected invalid start lock, auto cleaned"),{fd:r,token:t}}throw s}}function Q(e){let t=e?.fd,o=e?.token;try{t!=null&&c.closeSync(t)}catch{}try{let s=F();if(c.existsSync(s)){let i=!1;if(!o)i=!0;else try{let r=c.readFileSync(s,"utf8");i=JSON.parse(r)?.token===o}catch{i=!0}i&&c.removeSync(s)}}catch{}}function k(){return process.platform==="win32"}async function Y(e=n.defaultStopTimeout){let t=x();return t?X(t.pid)?(console.log(`Existing service process detected (PID: ${t.pid}), stopping before start...`),await h(t.pid,!1)&&await D(t.pid,e)?(v(),{success:!0,message:`Existing process ${t.pid} stopped gracefully`}):(console.warn(`Graceful stop timeout or failed for PID ${t.pid}, force stop...`),await h(t.pid,!0)?await D(t.pid,e)?(v(),{success:!0,message:`Existing process ${t.pid} stopped forcibly`}):{success:!1,message:`Existing process ${t.pid} did not exit after force stop`}:{success:!1,message:`Failed to stop existing process ${t.pid}`})):(console.log(`Found stale PID file (PID: ${t.pid}), clean it...`),v(),{success:!0,message:"Stale PID file cleaned"}):{success:!0,message:"No existing service process"}}async function h(e,t=!1){return new Promise(o=>{if(!g(e)){console.debug(`Process ${e} does not exist, already stopped`),o(!0);return}let s=t?"SIGKILL":"SIGTERM",i=k()?"taskkill":"tree-kill";if(console.debug(`Use ${i} to stop process ${e} (signal: ${s})`),k()){let r=t?["/F","/PID",String(e)]:["/PID",String(e)],a=E("taskkill",r,{stdio:["ignore","pipe","pipe"],windowsHide:!0}),u="";a.stdout.on("data",l=>{u+=l.toString()}),a.stderr.on("data",l=>{u+=l.toString()}),a.on("error",l=>{console.error(`Stop process failed: ${l.message}`),o(!1)}),a.on("close",l=>{l===0?(console.debug(`Process ${e} stopped`),o(!0)):(console.warn(`taskkill exit code: ${l}, output: ${u}`),t?o(!1):h(e,!0).then(o))})}else V(e,s,r=>{r?r.code==="ESRCH"?(console.debug(`Process ${e} does not exist`),o(!0)):(console.error(`Stop process failed: ${r.message}`),o(!1)):(console.debug(`Process ${e} stopped`),o(!0))})})}async function D(e,t=n.defaultStopTimeout){let o=Date.now();for(;g(e);){if(Date.now()-o>t)return console.warn(`Wait for process ${e} to stop timeout (${t}ms)`),!1;await new Promise(i=>setTimeout(i,n.checkInterval))}let s=Date.now()-o;return console.debug(`Process ${e} stopped after ${s}ms`),!0}async function Z(e,t=n.defaultStartTimeout){let o=Number(e);if(!Number.isFinite(o)||o<=0)return!1;let s=Date.now();for(;Date.now()-s<=t;){if(await new Promise(r=>{let a=M.get({host:"127.0.0.1",port:o,path:"/health",timeout:Math.min(2e3,n.checkInterval*4)},u=>{r(u.statusCode>=200&&u.statusCode<300),u.resume()});a.on("timeout",()=>{a.destroy(),r(!1)}),a.on("error",()=>r(!1))}))return!0;await new Promise(r=>setTimeout(r,n.checkInterval))}return!1}async function N(e={}){let{env:t,port:o,config:s}=e,i=null;console.log(`Start service ${n.name}...`);try{i=z()}catch(r){return r.code==="EEXIST"?{success:!1,pid:null,message:"Another start operation is in progress, please retry later"}:{success:!1,pid:null,message:`Acquire start lock failed: ${r.message}`}}try{let r=Number(e.timeout)||n.defaultStopTimeout,a=await Y(r);if(!a.success)return{success:!1,pid:null,message:`Service start blocked: ${a.message}`};let u={...process.env};t&&(u.NODE_ENV=t,console.log(`Environment: ${t}`)),o&&(u.PORT=o,console.log(`Port: ${o}`)),s&&(u.CONFIG_FILE=s,console.log(`Configuration file: ${s}`));let l=J(),p=E("node",[l,...[]],{env:u,stdio:["pipe","pipe","pipe"],detached:!0,cwd:process.cwd()});if(p.stdout.on("data",m=>{process.stdout.write(m)}),p.stderr.on("data",m=>{process.stderr.write(m)}),p.on("error",m=>{console.error(`Start service failed: ${m.message}`)}),await new Promise(m=>setTimeout(m,2e3)),!g(p.pid))return{success:!1,pid:null,message:"Service start failed"};let S={pid:p.pid,startedAt:new Date().toISOString(),env:t||process.env.NODE_ENV||"production",port:o||process.env.PORT||"60000",version:W(),platform:process.platform};B(S);let P=Number(e.startTimeout)||n.defaultStartTimeout;return await Z(S.port,P)?(p.unref(),console.log(`Service started (PID: ${p.pid})`),console.log(`Service address: http://localhost:${S.port}`),{success:!0,pid:p.pid,message:"Service started successfully"}):(console.error(`Service health check timeout (${P}ms), stop failed instance...`),await h(p.pid,!0),v(),{success:!1,pid:null,message:`Service health check timeout (${P}ms)`})}finally{Q(i)}}async function T(e={}){let{force:t=!1,timeout:o=n.defaultStopTimeout}=e;console.log(`Stop service ${n.name}...`);let s=x();if(!s)return{success:!1,message:"Service not found"};if(!g(s.pid))return console.log("Service process has stopped, clean PID file..."),v(),{success:!0,message:"Service has stopped (process has exited)"};if(!await h(s.pid,t))return{success:!1,message:"Stop service failed"};let r=await D(s.pid,o);return v(),r?{success:!0,message:"Service has stopped"}:{success:!1,message:"Service stop timeout"}}async function O(e={}){console.log(`Restart service ${n.name}...`);let t=await T(e);!t.success&&t.message!=="Service not found"&&console.warn(`Stop service failed: ${t.message}`),await new Promise(s=>setTimeout(s,2e3));let o=await N(e);return o.success?{success:!0,pid:o.pid,message:"Service has restarted"}:{success:!1,pid:null,message:`Restart failed: ${o.message}`}}function _(){let e=x();return e?g(e.pid)?{running:!0,pidInfo:e,message:"Service running"}:{running:!1,pidInfo:e,message:"Service process does not exist"}:{running:!1,pidInfo:null,message:"Service not running"}}function L(e){try{let t=new Date(e),o=new Date;if(isNaN(t.getTime()))return"unknown";let s=Math.floor((o-t)/1e3),i=Math.floor(s/3600),r=Math.floor(s%3600/60),a=s%60;return i>0?`${i} hours ${r} minutes ${a} seconds`:r>0?`${r} minutes ${a} seconds`:`${a} seconds`}catch{return"unknown"}}var Pe=te(import.meta.url),A="1.3.0-beta.25",d=new ee,w={reset:"\x1B[0m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",cyan:"\x1B[36m"};function j(e){console.error(`${w.red}ERROR: ${e}${w.reset}`)}function b(e){console.log(`${w.green}${e}${w.reset}`)}function oe(e){console.log(`${w.blue}${e}${w.reset}`)}function y(e){return async(...t)=>{try{let o=await e(...t);o&&o.success===!1?(j(o.message||"Command failed"),process.exitCode=1):process.exitCode=0}catch(o){j(o?.message||"Command failed with unexpected error"),process.exitCode=1}}}async function se(e){let t=await N({env:e.env,port:e.port,config:e.config,timeout:Number(e.timeout),startTimeout:Number(e.startTimeout)});return t.success&&b(`Service started (PID: ${t.pid})`),t}async function re(e){let t=await T({force:e.force,timeout:Number(e.timeout)});return t.success&&b(t.message||"Service stopped"),t}async function ne(e){let t=await O({env:e.env,port:e.port,config:e.config,timeout:Number(e.timeout),startTimeout:Number(e.startTimeout)});return t.success&&b(t.message||"Service restarted"),t}function ie(){let e=_();return oe(`${n.name} service status:`),console.log(""),console.log(` Service name: ${n.name}`),console.log(` Running status: ${e.running?"Running":"Stopped"}`),console.log(` Message: ${e.message}`),console.log(` PID file: ${$()}`),e.pidInfo&&(console.log(` Process ID: ${e.pidInfo.pid}`),console.log(` Environment: ${e.pidInfo.env||"Unknown"}`),console.log(` Port: ${e.pidInfo.port||"Unknown"}`),console.log(` Version: ${e.pidInfo.version||A}`),console.log(` Platform: ${e.pidInfo.platform||process.platform}`),console.log(` Started at: ${e.pidInfo.startedAt||"Unknown"}`),console.log(` Uptime: ${L(e.pidInfo.startedAt)}`)),console.log(""),{success:e.running,message:e.message}}function ce(){d.name("nuwax-file-server").description("Cross-platform file service deployment tool, supporting start/stop/restart/status").version(A,"-v, --version","Display version number").helpOption("-h, --help","Display help information"),d.command("start").allowUnknownOption().description("Start service").option("--env <environment>","\u73AF\u5883: development|production|test","production").option("--port <port>","Service port").option("--config <path>","Custom configuration file path").option("--timeout <ms>","\u505C\u6B62\u65E7\u8FDB\u7A0B\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).option("--start-timeout <ms>","\u542F\u52A8\u5065\u5EB7\u68C0\u67E5\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStartTimeout}`).action(y(se)),d.command("stop").description("Stop service").option("--force","Force stop").option("--timeout <ms>","\u505C\u6B62\u670D\u52A1\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).action(y(re)),d.command("restart").allowUnknownOption().description("Restart service").option("--env <environment>","\u73AF\u5883: development|production|test","production").option("--port <port>","Service port").option("--config <path>","Custom configuration file path").option("--timeout <ms>","\u505C\u6B62\u65E7\u8FDB\u7A0B\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).option("--start-timeout <ms>","\u542F\u52A8\u5065\u5EB7\u68C0\u67E5\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStartTimeout}`).action(y(ne)),d.command("status").description("View service status").action(y(ie)),d.command("help").description("Display help information").action(()=>{d.outputHelp()}),d.parse(process.argv),process.argv.slice(2).length||(d.outputHelp(),process.exitCode=0)}ce();
|
|
2
|
+
import{Command as ee}from"commander";import{createRequire as te}from"module";import f from"path";import U from"os";import c from"fs-extra";import{spawn as E}from"cross-spawn";import V from"tree-kill";import{fileURLToPath as q}from"url";import{execFileSync as R}from"child_process";import M from"http";import{createRequire as G}from"module";var I=f.dirname(q(import.meta.url)),H=G(import.meta.url),n={name:"nuwax-file-server",pidDir:f.join(U.tmpdir(),"nuwax-file-server"),pidFileName:"server.pid",lockFileName:"start.lock",defaultStopTimeout:3e4,defaultStartTimeout:3e4,staleLockTimeout:12e4,checkInterval:500};function $(){return f.join(n.pidDir,n.pidFileName)}function F(){return f.join(n.pidDir,n.lockFileName)}function J(){let e=[f.join(I,"..","server.js"),f.join(I,"server.js")];for(let t of e)if(c.existsSync(t))return t;return e[0]}function W(){let e=["../../package.json","../package.json"];for(let t of e)try{let o=H(t);if(o?.version)return o.version}catch{}return"unknown"}function x(){try{let e=$();if(!c.existsSync(e))return null;let t=c.readFileSync(e,"utf8"),o=JSON.parse(t);return!o||typeof o.pid!="number"?null:o}catch(e){return e.code!=="ENOENT"&&console.error(`Read PID file failed: ${e.message}`),null}}function B(e){try{let t=$();c.ensureDirSync(n.pidDir),c.writeFileSync(t,JSON.stringify(e,null,2)),console.debug(`PID file written: ${t}`)}catch(t){throw console.error(`Write PID file failed: ${t.message}`),t}}function v(){try{let e=$();c.existsSync(e)&&(c.removeSync(e),console.debug(`PID file deleted: ${e}`))}catch(e){console.error(`Delete PID file failed: ${e.message}`)}}function g(e){try{return process.kill(e,0),!0}catch(t){return t.code!=="ESRCH"}}function K(e){try{return k()?R("powershell",["-NoProfile","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${e}").CommandLine`],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim():R("ps",["-p",String(e),"-o","command="],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return""}}function X(e){if(!g(e))return!1;let t=K(e);if(!t)return!1;let o=t.toLowerCase(),s=f.basename(f.join(I,"..","server.js")).toLowerCase(),i=n.name.toLowerCase();return o.includes(s)||o.includes(i)}function z(){c.ensureDirSync(n.pidDir);let e=F(),t=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`,o=JSON.stringify({pid:process.pid,token:t,createdAt:new Date().toISOString()},null,2);try{let s=c.openSync(e,"wx");return c.writeSync(s,o),{fd:s,token:t}}catch(s){if(s.code!=="EEXIST")throw s;try{let i=c.readFileSync(e,"utf8"),r=JSON.parse(i),a=Number(r?.pid),u=r?.createdAt?new Date(r.createdAt).getTime():0,l=Date.now()-u,C=Number.isFinite(a)&&a>0&&g(a),p=!u||Number.isNaN(l)||l>n.staleLockTimeout;if(!C||p){c.removeSync(e);let S=c.openSync(e,"wx");return c.writeSync(S,o),console.warn("Detected stale start lock, auto cleaned"),{fd:S,token:t}}}catch{c.removeSync(e);let r=c.openSync(e,"wx");return c.writeSync(r,o),console.warn("Detected invalid start lock, auto cleaned"),{fd:r,token:t}}throw s}}function Q(e){let t=e?.fd,o=e?.token;try{t!=null&&c.closeSync(t)}catch{}try{let s=F();if(c.existsSync(s)){let i=!1;if(!o)i=!0;else try{let r=c.readFileSync(s,"utf8");i=JSON.parse(r)?.token===o}catch{i=!0}i&&c.removeSync(s)}}catch{}}function k(){return process.platform==="win32"}async function Y(e=n.defaultStopTimeout){let t=x();return t?X(t.pid)?(console.log(`Existing service process detected (PID: ${t.pid}), stopping before start...`),await h(t.pid,!1)&&await D(t.pid,e)?(v(),{success:!0,message:`Existing process ${t.pid} stopped gracefully`}):(console.warn(`Graceful stop timeout or failed for PID ${t.pid}, force stop...`),await h(t.pid,!0)?await D(t.pid,e)?(v(),{success:!0,message:`Existing process ${t.pid} stopped forcibly`}):{success:!1,message:`Existing process ${t.pid} did not exit after force stop`}:{success:!1,message:`Failed to stop existing process ${t.pid}`})):(console.log(`Found stale PID file (PID: ${t.pid}), clean it...`),v(),{success:!0,message:"Stale PID file cleaned"}):{success:!0,message:"No existing service process"}}async function h(e,t=!1){return new Promise(o=>{if(!g(e)){console.debug(`Process ${e} does not exist, already stopped`),o(!0);return}let s=t?"SIGKILL":"SIGTERM",i=k()?"taskkill":"tree-kill";if(console.debug(`Use ${i} to stop process ${e} (signal: ${s})`),k()){let r=t?["/F","/PID",String(e)]:["/PID",String(e)],a=E("taskkill",r,{stdio:["ignore","pipe","pipe"],windowsHide:!0}),u="";a.stdout.on("data",l=>{u+=l.toString()}),a.stderr.on("data",l=>{u+=l.toString()}),a.on("error",l=>{console.error(`Stop process failed: ${l.message}`),o(!1)}),a.on("close",l=>{l===0?(console.debug(`Process ${e} stopped`),o(!0)):(console.warn(`taskkill exit code: ${l}, output: ${u}`),t?o(!1):h(e,!0).then(o))})}else V(e,s,r=>{r?r.code==="ESRCH"?(console.debug(`Process ${e} does not exist`),o(!0)):(console.error(`Stop process failed: ${r.message}`),o(!1)):(console.debug(`Process ${e} stopped`),o(!0))})})}async function D(e,t=n.defaultStopTimeout){let o=Date.now();for(;g(e);){if(Date.now()-o>t)return console.warn(`Wait for process ${e} to stop timeout (${t}ms)`),!1;await new Promise(i=>setTimeout(i,n.checkInterval))}let s=Date.now()-o;return console.debug(`Process ${e} stopped after ${s}ms`),!0}async function Z(e,t=n.defaultStartTimeout){let o=Number(e);if(!Number.isFinite(o)||o<=0)return!1;let s=Date.now();for(;Date.now()-s<=t;){if(await new Promise(r=>{let a=M.get({host:"127.0.0.1",port:o,path:"/health",timeout:Math.min(2e3,n.checkInterval*4)},u=>{r(u.statusCode>=200&&u.statusCode<300),u.resume()});a.on("timeout",()=>{a.destroy(),r(!1)}),a.on("error",()=>r(!1))}))return!0;await new Promise(r=>setTimeout(r,n.checkInterval))}return!1}async function N(e={}){let{env:t,port:o,config:s}=e,i=null;console.log(`Start service ${n.name}...`);try{i=z()}catch(r){return r.code==="EEXIST"?{success:!1,pid:null,message:"Another start operation is in progress, please retry later"}:{success:!1,pid:null,message:`Acquire start lock failed: ${r.message}`}}try{let r=Number(e.timeout)||n.defaultStopTimeout,a=await Y(r);if(!a.success)return{success:!1,pid:null,message:`Service start blocked: ${a.message}`};let u={...process.env};t&&(u.NODE_ENV=t,console.log(`Environment: ${t}`)),o&&(u.PORT=o,console.log(`Port: ${o}`)),s&&(u.CONFIG_FILE=s,console.log(`Configuration file: ${s}`));let l=J(),p=E("node",[l,...[]],{env:u,stdio:["pipe","pipe","pipe"],detached:!0,cwd:process.cwd()});if(p.stdout.on("data",m=>{process.stdout.write(m)}),p.stderr.on("data",m=>{process.stderr.write(m)}),p.on("error",m=>{console.error(`Start service failed: ${m.message}`)}),await new Promise(m=>setTimeout(m,2e3)),!g(p.pid))return{success:!1,pid:null,message:"Service start failed"};let S={pid:p.pid,startedAt:new Date().toISOString(),env:t||process.env.NODE_ENV||"production",port:o||process.env.PORT||"60000",version:W(),platform:process.platform};B(S);let P=Number(e.startTimeout)||n.defaultStartTimeout;return await Z(S.port,P)?(p.unref(),console.log(`Service started (PID: ${p.pid})`),console.log(`Service address: http://localhost:${S.port}`),{success:!0,pid:p.pid,message:"Service started successfully"}):(console.error(`Service health check timeout (${P}ms), stop failed instance...`),await h(p.pid,!0),v(),{success:!1,pid:null,message:`Service health check timeout (${P}ms)`})}finally{Q(i)}}async function T(e={}){let{force:t=!1,timeout:o=n.defaultStopTimeout}=e;console.log(`Stop service ${n.name}...`);let s=x();if(!s)return{success:!1,message:"Service not found"};if(!g(s.pid))return console.log("Service process has stopped, clean PID file..."),v(),{success:!0,message:"Service has stopped (process has exited)"};if(!await h(s.pid,t))return{success:!1,message:"Stop service failed"};let r=await D(s.pid,o);return v(),r?{success:!0,message:"Service has stopped"}:{success:!1,message:"Service stop timeout"}}async function O(e={}){console.log(`Restart service ${n.name}...`);let t=await T(e);!t.success&&t.message!=="Service not found"&&console.warn(`Stop service failed: ${t.message}`),await new Promise(s=>setTimeout(s,2e3));let o=await N(e);return o.success?{success:!0,pid:o.pid,message:"Service has restarted"}:{success:!1,pid:null,message:`Restart failed: ${o.message}`}}function _(){let e=x();return e?g(e.pid)?{running:!0,pidInfo:e,message:"Service running"}:{running:!1,pidInfo:e,message:"Service process does not exist"}:{running:!1,pidInfo:null,message:"Service not running"}}function L(e){try{let t=new Date(e),o=new Date;if(isNaN(t.getTime()))return"unknown";let s=Math.floor((o-t)/1e3),i=Math.floor(s/3600),r=Math.floor(s%3600/60),a=s%60;return i>0?`${i} hours ${r} minutes ${a} seconds`:r>0?`${r} minutes ${a} seconds`:`${a} seconds`}catch{return"unknown"}}var Pe=te(import.meta.url),A="1.3.0-beta.26",d=new ee,w={reset:"\x1B[0m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",cyan:"\x1B[36m"};function j(e){console.error(`${w.red}ERROR: ${e}${w.reset}`)}function b(e){console.log(`${w.green}${e}${w.reset}`)}function oe(e){console.log(`${w.blue}${e}${w.reset}`)}function y(e){return async(...t)=>{try{let o=await e(...t);o&&o.success===!1?(j(o.message||"Command failed"),process.exitCode=1):process.exitCode=0}catch(o){j(o?.message||"Command failed with unexpected error"),process.exitCode=1}}}async function se(e){let t=await N({env:e.env,port:e.port,config:e.config,timeout:Number(e.timeout),startTimeout:Number(e.startTimeout)});return t.success&&b(`Service started (PID: ${t.pid})`),t}async function re(e){let t=await T({force:e.force,timeout:Number(e.timeout)});return t.success&&b(t.message||"Service stopped"),t}async function ne(e){let t=await O({env:e.env,port:e.port,config:e.config,timeout:Number(e.timeout),startTimeout:Number(e.startTimeout)});return t.success&&b(t.message||"Service restarted"),t}function ie(){let e=_();return oe(`${n.name} service status:`),console.log(""),console.log(` Service name: ${n.name}`),console.log(` Running status: ${e.running?"Running":"Stopped"}`),console.log(` Message: ${e.message}`),console.log(` PID file: ${$()}`),e.pidInfo&&(console.log(` Process ID: ${e.pidInfo.pid}`),console.log(` Environment: ${e.pidInfo.env||"Unknown"}`),console.log(` Port: ${e.pidInfo.port||"Unknown"}`),console.log(` Version: ${e.pidInfo.version||A}`),console.log(` Platform: ${e.pidInfo.platform||process.platform}`),console.log(` Started at: ${e.pidInfo.startedAt||"Unknown"}`),console.log(` Uptime: ${L(e.pidInfo.startedAt)}`)),console.log(""),{success:e.running,message:e.message}}function ce(){d.name("nuwax-file-server").description("Cross-platform file service deployment tool, supporting start/stop/restart/status").version(A,"-v, --version","Display version number").helpOption("-h, --help","Display help information"),d.command("start").allowUnknownOption().description("Start service").option("--env <environment>","\u73AF\u5883: development|production|test","production").option("--port <port>","Service port").option("--config <path>","Custom configuration file path").option("--timeout <ms>","\u505C\u6B62\u65E7\u8FDB\u7A0B\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).option("--start-timeout <ms>","\u542F\u52A8\u5065\u5EB7\u68C0\u67E5\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStartTimeout}`).action(y(se)),d.command("stop").description("Stop service").option("--force","Force stop").option("--timeout <ms>","\u505C\u6B62\u670D\u52A1\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).action(y(re)),d.command("restart").allowUnknownOption().description("Restart service").option("--env <environment>","\u73AF\u5883: development|production|test","production").option("--port <port>","Service port").option("--config <path>","Custom configuration file path").option("--timeout <ms>","\u505C\u6B62\u65E7\u8FDB\u7A0B\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).option("--start-timeout <ms>","\u542F\u52A8\u5065\u5EB7\u68C0\u67E5\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStartTimeout}`).action(y(ne)),d.command("status").description("View service status").action(y(ie)),d.command("help").description("Display help information").action(()=>{d.outputHelp()}),d.parse(process.argv),process.argv.slice(2).length||(d.outputHelp(),process.exitCode=0)}ce();
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import
|
|
2
|
-
`).slice(4);
|
|
1
|
+
import P from"path";import i from"fs";import dt from"crypto";import l from"isomorphic-git";import{createPatch as ut}from"diff";import B from"../appConfig/index.js";import{log as w}from"../utils/log/logUtils.js";import{ValidationError as v,BusinessError as G,SystemError as A,ResourceError as D}from"../utils/error/errorHandler.js";import{resolveProjectPath as ht}from"../utils/common/projectPathUtils.js";import{isGitRepo as gt,ensureGitRepo as T,ensureGitignore as M,addAll as U,stageFiles as L,getDefaultAuthor as mt}from"../utils/git/gitUtils.js";function k(n){const{workspaceType:t,projectId:a,isolationContext:e,userId:s,cId:r}=n||{};if(!t||!["pageApp","taskAgent"].includes(t))throw new v("workspaceType is required and must be pageApp or taskAgent",{field:"workspaceType"});if(t==="taskAgent"){if(!s||!r)throw new v("taskAgent mode requires userId and cId",{field:"userId/cId"});const c=P.join(B.COMPUTER_WORKSPACE_DIR,String(s),String(r));if(!i.existsSync(c))throw new D("Computer workspace does not exist",{userId:s,cId:r});return{targetPath:c,logId:`computer:${s}:${r}`}}if(!a)throw new v("pageApp mode requires projectId",{field:"projectId"});const o=ht(a,e||{});if(!i.existsSync(o))throw new D("Project does not exist",{projectId:a});return{targetPath:o,logId:a}}function q(n){for(let t=0;t<Math.min(n.length,8e3);t++)if(n[t]===0)return!0;return!1}function C(n){const t=Buffer.from(`blob ${n.length}\0`);return dt.createHash("sha1").update(Buffer.concat([t,n])).digest("hex")}function wt(n,t,a,e,s,r,o){const d=ut(n,e?t:"",s?a:"",e?`a/${n}`:"/dev/null",s?`b/${n}`:"/dev/null").split(`
|
|
2
|
+
`).slice(4);d.length>0&&d[d.length-1]===""&&d.pop();const g=[];let u=0,h=0;for(const m of d){if(m.startsWith("@@")){const p=m.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(p){const S=p[1],F=p[2]!==void 0?parseInt(p[2],10):1,N=p[3],R=p[4]!==void 0?parseInt(p[4],10):1,$=F===1?S:`${S},${F}`,H=R===1?N:`${N},${R}`;g.push(`@@ -${$} +${H} @@`);continue}}m.startsWith("+")&&!m.startsWith("+++")?u++:m.startsWith("-")&&!m.startsWith("---")&&h++,g.push(m)}const f=e&&t!==""&&!t.endsWith(`
|
|
3
3
|
`),b=s&&a!==""&&!a.endsWith(`
|
|
4
|
-
`);if((f||b)&&g.length>0){let m=0;for(let R=0;R<g.length;R++)g[R].startsWith("@@")&&(m=R);let
|
|
4
|
+
`);if((f||b)&&g.length>0){let m=0;for(let R=0;R<g.length;R++)g[R].startsWith("@@")&&(m=R);let p=-1,S=-1,F=-1;for(let R=g.length-1;R>m;R--){const $=g[R];$.startsWith("-")&&!$.startsWith("---")&&p<0?p=R:$.startsWith("+")&&!$.startsWith("++")&&S<0?S=R:$.startsWith(" ")&&F<0&&(F=R)}const N=Math.max(p,S,F);if(N>=0){const R=g[N];if(R.startsWith(" "))(f||b)&&g.splice(N+1,0,"\");else if(R.startsWith("+")){let $=-1;for(let H=N-1;H>m;H--)if(g[H].startsWith("-")&&!g[H].startsWith("---")){$=H;break}$>=0&&f?(g.splice($+1,0,"\"),b&&g.splice(N+2,0,"\")):b&&g.splice(N+1,0,"\")}else R.startsWith("-")&&f&&g.splice(N+1,0,"\")}}const O=e&&r?C(r).substring(0,7):"0000000",x=s&&o?C(o).substring(0,7):"0000000",E=[];return E.push(`diff --git a/${n} b/${n}`),e?s?E.push(`index ${O}..${x} 100644`):(E.push("deleted file mode 100644"),E.push(`index ${O}..0000000`)):(E.push("new file mode 100644"),E.push(`index 0000000..${x}`)),E.push(`--- ${e?`a/${n}`:"/dev/null"}`),E.push(`+++ ${s?`b/${n}`:"/dev/null"}`),{diff:[...E,...g].join(`
|
|
5
5
|
`)+`
|
|
6
|
-
`,insertions:u,deletions:
|
|
6
|
+
`,insertions:u,deletions:h}}async function W(n){return l.resolveRef({fs:i,dir:n,ref:"HEAD"})}async function _(n,t,a){try{const{blob:e}=await l.readBlob({fs:i,dir:n,oid:t,filepath:a}),s=Buffer.from(e);return{content:s.toString("utf8"),buf:s}}catch{return null}}async function z(n={}){const{targetPath:t,logId:a}=k(n);if(gt(t))return{success:!0,message:"Git repository already initialized",logId:a,alreadyExists:!0};try{return await l.init({fs:i,dir:t,defaultBranch:"main"}),M(t),await l.setConfig({fs:i,dir:t,path:"user.name",value:B.GIT_DEFAULT_AUTHOR_NAME}),await l.setConfig({fs:i,dir:t,path:"user.email",value:B.GIT_DEFAULT_AUTHOR_EMAIL}),w(a,"INFO","Git repository initialized",{logId:a,targetPath:t}),{success:!0,message:"Git repository initialized successfully",logId:a,alreadyExists:!1}}catch(e){throw w(a,"ERROR","Failed to initialize Git repository",{logId:a,error:e.message}),new A("Failed to initialize Git repository",{originalError:e.message})}}async function K(n={}){const{targetPath:t,logId:a}=k(n);await T(t);try{const e=await l.currentBranch({fs:i,dir:t,fullname:!1}),s=await l.statusMatrix({fs:i,dir:t}),r=[],o=[],c=[],y=[],d=[];for(const[g,u,h,f]of s)u!==f&&r.push(g),u===0&&f!==0&&c.push(g),(u===1&&f===0||h===0&&f!==0)&&y.push(g),f!==0&&h!==0&&h!==f&&o.push(g),u===0&&f===0&&h!==0&&d.push(g);return{success:!0,logId:a,current:e,staged:[...new Set(r)],modified:[...new Set(o)],created:[...new Set(c)],deleted:[...new Set(y)],untracked:[...new Set(d)],conflicted:[],ahead:0,behind:0,tracking:null}}catch(e){throw w(a,"ERROR","Failed to get Git status",{logId:a,error:e.message}),new A("Failed to get Git status",{originalError:e.message})}}async function V(n={}){const{message:t,files:a,authorName:e,authorEmail:s}=n;if(!t||typeof t!="string")throw new v("Commit message cannot be empty",{field:"message"});const{targetPath:r,logId:o}=k(n);await T(r);try{Array.isArray(a)&&a.length>0?await L(r,a):await U(r);const y=(await l.statusMatrix({fs:i,dir:r})).some(([,,,u])=>u!==1);if(!y)return{success:!0,message:"Nothing to commit",logId:o,nothingToCommit:!0};const d={name:e||B.GIT_DEFAULT_AUTHOR_NAME,email:s||B.GIT_DEFAULT_AUTHOR_EMAIL},g=await l.commit({fs:i,dir:r,message:t,author:d});return w(o,"INFO","Git commit successful",{logId:o,commitHash:g,message:t}),{success:!0,message:"Commit successful",logId:o,commit:g,summary:{changes:y?1:0}}}catch(c){throw w(o,"ERROR","Failed to commit",{logId:o,error:c.message}),new A("Failed to commit",{originalError:c.message})}}async function J(n={}){const{files:t}=n,{targetPath:a,logId:e}=k(n);await T(a);try{return Array.isArray(t)&&t.length>0?await L(a,t):await U(a),w(e,"INFO","Git add successful",{logId:e,filesCount:t?t.length:"all"}),{success:!0,message:"Files staged successfully",logId:e}}catch(s){throw w(e,"ERROR","Failed to add files",{logId:e,error:s.message}),new A("Failed to add files",{originalError:s.message})}}async function Q(n={}){const{files:t}=n,{targetPath:a,logId:e}=k(n);await T(a);try{if(Array.isArray(t)&&t.length>0){for(const o of t)await l.resetIndex({fs:i,dir:a,filepath:o});return w(e,"INFO","Git unstage specified files",{logId:e,files:t}),{success:!0,message:"Specified files unstaged successfully",logId:e,files:t}}const r=(await l.statusMatrix({fs:i,dir:a})).filter(([,,,o])=>o!==1).map(([o])=>o);for(const o of r)await l.resetIndex({fs:i,dir:a,filepath:o});return w(e,"INFO","Git unstage all files",{logId:e}),{success:!0,message:"All files unstaged successfully",logId:e,files:"all"}}catch(s){throw w(e,"ERROR","Failed to unstage",{logId:e,error:s.message}),new A("Failed to unstage files",{originalError:s.message})}}async function j(n,t){const a=new Set;for(const s of t){let r=P.dirname(s);for(;r&&r!==".";)a.add(r),r=P.dirname(r)}const e=[...a].sort((s,r)=>{const o=s.split(/[/\\]/).length;return r.split(/[/\\]/).length-o});for(const s of e){const r=P.join(n,s);try{(await i.promises.readdir(r)).length===0&&await i.promises.rmdir(r)}catch{}}}async function X(n={}){const{files:t}=n,{targetPath:a,logId:e}=k(n);await T(a);try{const s=await l.statusMatrix({fs:i,dir:a}),r=Array.isArray(t)&&t.length>0?new Set(t):null,o=[],c=[],y=[];for(const[u,h,f,b]of s)r&&!r.has(u)||(h!==0?(b!==1||f!==1)&&o.push(u):h===0&&b!==0?c.push(u):h===0&&b===0&&f!==0&&y.push(u));const d=await W(a);for(const u of o){const h=await _(a,d,u);if(!h)continue;const f=P.join(a,u);i.mkdirSync(P.dirname(f),{recursive:!0}),i.writeFileSync(f,h.buf),await l.add({fs:i,dir:a,filepath:u})}for(const u of c){try{await l.remove({fs:i,dir:a,filepath:u})}catch{}const h=P.join(a,u);i.existsSync(h)&&await i.promises.unlink(h)}c.length>0&&await j(a,c);for(const u of y){const h=P.join(a,u);i.existsSync(h)&&await i.promises.unlink(h)}y.length>0&&await j(a,y);const g=o.length+c.length+y.length;return w(e,"INFO","Git discard",{logId:e,trackedFiles:o.length,newFiles:c.length,untrackedFiles:y.length}),{success:!0,message:"Files discarded successfully",logId:e,discardedCount:g,trackedFiles:o,newFiles:c,untrackedFiles:y}}catch(s){throw w(e,"ERROR","Failed to discard",{logId:e,error:s.message}),new A("Failed to discard files",{originalError:s.message})}}async function Y(n={}){const{maxCount:t=50,branch:a,skip:e=0,filePath:s}=n,{targetPath:r,logId:o}=k(n);await T(r);try{const c=Math.min(Math.max(1,t),500),y=Math.max(0,e),d={fs:i,dir:r,depth:c+y};a&&(d.ref=a),s&&(d.filepath=s);const h=(await l.log(d)).slice(y,y+c).map(f=>({hash:f.oid,date:new Date(f.commit.author.timestamp*1e3).toISOString(),message:f.commit.message,author_name:f.commit.author.name,author_email:f.commit.author.email}));return{success:!0,logId:o,commits:h,total:h.length}}catch(c){throw w(o,"ERROR","Failed to get Git log",{logId:o,error:c.message}),new A("Failed to get Git log",{originalError:c.message})}}async function Z(n={}){const{source:t="worktree",from:a,to:e,paths:s}=n,{targetPath:r,logId:o}=k(n);await T(r);try{const c=Array.isArray(s)&&s.length>0?new Set(s):null;let y="";const d=[];let g=0,u=0;async function h(f,b,O){const x=!!b,E=!!O;if(x&&E&&b.content===O.content)return;let I=!1;if(x&&q(b.buf)&&(I=!0),E&&!I&&q(O.buf)&&(I=!0),I){const F=x?C(b.buf).substring(0,7):"0000000",N=E?C(O.buf).substring(0,7):"0000000",R=[`diff --git a/${f} b/${f}`];x?E?R.push(`index ${F}..${N} 100644`):(R.push("deleted file mode 100644"),R.push(`index ${F}..0000000`)):(R.push("new file mode 100644"),R.push(`index 0000000..${N}`)),R.push(`Binary files ${x?`a/${f}`:"/dev/null"} and ${E?`b/${f}`:"/dev/null"} differ`),y+=R.join(`
|
|
7
7
|
`)+`
|
|
8
|
-
`,h.push({file:f,changes:0,insertions:0,deletions:0,binary:!0});return}const{diff:m,insertions:y,deletions:S}=mt(f,I?b.content:"",E?O.content:"",I,E,I?b.buf:null,E?O.buf:null);p+=m,h.push({file:f,changes:y+S,insertions:y,deletions:S,binary:!1}),g+=y,u+=S}if(t==="commit"){let f,b;if(a&&e)f=a,b=e;else if(a){const x=await l.readCommit({fs:i,dir:r,oid:a});x.commit.parent&&x.commit.parent.length>0?(f=x.commit.parent[0],b=a):(f=null,b=a)}else throw new v("source=commit requires at least 'from'",{field:"from"});const O=f?new Set(await l.listFiles({fs:i,dir:r,ref:f})):new Set,I=new Set(await l.listFiles({fs:i,dir:r,ref:b})),E=new Set([...O,...I]);for(const x of E){if(c&&!c.has(x))continue;const m=O.has(x)?await _(r,f,x):null,y=I.has(x)?await _(r,b,x):null;await d(x,m,y)}}else{const f=await W(r),b=await l.statusMatrix({fs:i,dir:r});for(const[O,I,E,x]of b){if(c&&!c.has(O))continue;if(t==="staged"){if(x===1||I===0&&x===0)continue}else if(I===0&&x===0||I===1&&E===1&&x===1)continue;const m=I!==0?await _(r,f,O):null;let y=null;if(E!==0){const S=A.join(r,O);if(i.existsSync(S))try{const F=i.readFileSync(S);y={content:F.toString("utf8"),buf:F}}catch{}}await d(O,m,y)}}return{success:!0,logId:o,source:t,diff:p,summary:{files:h,insertions:g,deletions:u}}}catch(c){throw c instanceof v?c:(w(o,"ERROR","Failed to get Git diff",{logId:o,error:c.message}),new k("Failed to get Git diff",{originalError:c.message}))}}async function Z(n={}){const{ref:t="HEAD",filePath:a}=n;if(!a)throw new v("filePath is required",{field:"filePath"});const{targetPath:e,logId:s}=P(n);await T(e);try{let r;if(t==="worktree"||t==="staged"||t===""){const o=A.join(e,a);r=i.existsSync(o)?i.readFileSync(o,"utf8"):""}else try{const o=await l.resolveRef({fs:i,dir:e,ref:t}),{blob:c}=await l.readBlob({fs:i,dir:e,oid:o,filepath:a});r=Buffer.from(c).toString("utf8")}catch{r=""}return{success:!0,logId:s,filePath:a,ref:t,content:r}}catch(r){throw r instanceof D?r:(w(s,"ERROR","Failed to get file content",{logId:s,ref:t,filePath:a,error:r.message}),new k("Failed to get file content",{originalError:r.message}))}}async function tt(n={}){const{target:t,mode:a="mixed"}=n;if(!t)throw new v("Reset target cannot be empty",{field:"target"});if(!["soft","mixed","hard"].includes(a))throw new v("Mode must be soft, mixed or hard",{field:"mode"});const{targetPath:e,logId:s}=P(n);await T(e);try{const r=await l.log({fs:i,dir:e,depth:1}),o=r.length>0?r[0].oid:null,c=await l.currentBranch({fs:i,dir:e,fullname:!1});if(!c)throw new G("Cannot reset: detached HEAD");const p=a==="hard"?new Set(await l.listFiles({fs:i,dir:e,ref:"HEAD"})):null;if(await l.writeRef({fs:i,dir:e,ref:`refs/heads/${c}`,value:t,force:!0}),a==="mixed"||a==="hard"){const h=await l.listFiles({fs:i,dir:e,ref:t}),g=new Set(h);for(const d of h)await l.resetIndex({fs:i,dir:e,filepath:d,ref:t});const u=await l.statusMatrix({fs:i,dir:e});for(const[d,,,f]of u)if(!g.has(d)&&f!==0)try{await l.remove({fs:i,dir:e,filepath:d})}catch{}}if(a==="hard"){const h=await l.listFiles({fs:i,dir:e,ref:t}),g=new Set(h);for(const u of h){const d=await _(e,t,u);if(!d)continue;const f=A.join(e,u);i.mkdirSync(A.dirname(f),{recursive:!0}),i.writeFileSync(f,d.buf)}if(p){for(const u of p)if(!g.has(u)){const d=A.join(e,u);i.existsSync(d)&&i.unlinkSync(d)}}M(e),await l.add({fs:i,dir:e,filepath:".gitignore"})}return w(s,"INFO","Git reset successful",{logId:s,target:t,mode:a,previousHead:o}),{success:!0,message:`Reset (${a}) to ${t} successful`,logId:s,target:t,mode:a,previousHead:o}}catch(r){throw r instanceof G?r:(w(s,"ERROR","Failed to reset",{logId:s,target:t,mode:a,error:r.message}),new k("Failed to reset",{originalError:r.message}))}}async function et(n={}){const{target:t,message:a,authorName:e,authorEmail:s}=n;if(!t)throw new v("Revert target cannot be empty",{field:"target"});const{targetPath:r,logId:o}=P(n);await T(r);try{let c;try{c=(await l.readCommit({fs:i,dir:r,oid:t})).oid}catch{throw new v("Revert target commit does not exist",{field:"target",target:t})}const p=await l.statusMatrix({fs:i,dir:r});if(p.some(([m,y,S,F])=>y===0&&F===0?!1:S!==1||F!==1)){const m=p.filter(([,F])=>F!==0),y=m.filter(([,,F])=>F!==1).map(([F])=>F),S=m.filter(([,,,F])=>F!==1).map(([F])=>F);throw new G("Working directory is not clean, please commit or stash your changes before reverting",{staged:S,modified:y})}const g=new Set(await l.listFiles({fs:i,dir:r,ref:c})),u=await W(r),d=new Set(await l.listFiles({fs:i,dir:r,ref:u})),f=[];for(const m of g){const y=await _(r,c,m);if(!y)continue;const S=A.join(r,m);i.mkdirSync(A.dirname(S),{recursive:!0}),i.writeFileSync(S,y.buf),await l.add({fs:i,dir:r,filepath:m})}for(const m of d)if(!g.has(m)){f.push(m);try{await l.remove({fs:i,dir:r,filepath:m})}catch{}const y=A.join(r,m);i.existsSync(y)&&await i.promises.unlink(y)}if(f.length>0&&await j(r,f),M(r),await l.add({fs:i,dir:r,filepath:".gitignore"}),!(await l.statusMatrix({fs:i,dir:r})).some(([,,,m])=>m!==1))return w(o,"INFO","Nothing to revert, current HEAD already matches target",{logId:o,target:c}),{success:!0,message:"Nothing to revert, already at target state",logId:o,nothingToCommit:!0,target:c};const I={name:e||B.GIT_DEFAULT_AUTHOR_NAME,email:s||B.GIT_DEFAULT_AUTHOR_EMAIL},E=a||`Revert to ${c.substring(0,7)}`,x=await l.commit({fs:i,dir:r,message:E,author:I});return w(o,"INFO","Git revert successful",{logId:o,target:c,commitHash:x,previousHead:u,removedFilesCount:f.length}),{success:!0,message:"Revert successful",logId:o,commit:x,target:c,previousHead:u}}catch(c){throw c instanceof v||c instanceof G?c:(w(o,"ERROR","Failed to revert",{logId:o,target:t,error:c.message}),new k("Failed to revert",{originalError:c.message}))}}async function at(n={}){const{target:t}=n;if(!t)throw new v("Checkout target cannot be empty",{field:"target"});const{targetPath:a,logId:e}=P(n);await T(a);try{const s=await l.listFiles({fs:i,dir:a,ref:t});for(const r of s){const o=await _(a,t,r);if(!o)continue;const c=A.join(a,r);i.mkdirSync(A.dirname(c),{recursive:!0}),i.writeFileSync(c,o.buf),await l.add({fs:i,dir:a,filepath:r})}return M(a),await l.add({fs:i,dir:a,filepath:".gitignore"}),w(e,"INFO","Git checkout files successful",{logId:e,target:t}),{success:!0,message:`Checkout files from ${t} successful`,logId:e,target:t}}catch(s){throw w(e,"ERROR","Failed to checkout files",{logId:e,target:t,error:s.message}),new k("Failed to checkout files",{originalError:s.message})}}async function rt(n={}){const{targetPath:t,logId:a}=P(n);await T(t);try{const e=await l.listTags({fs:i,dir:t});return{success:!0,logId:a,tags:e,latest:e.length>0?e[e.length-1]:null}}catch(e){throw w(a,"ERROR","Failed to list tags",{logId:a,error:e.message}),new k("Failed to list tags",{originalError:e.message})}}async function st(n={}){const{tagName:t,message:a}=n;if(!t)throw new v("Tag name cannot be empty",{field:"tagName"});const{targetPath:e,logId:s}=P(n);await T(e);try{return a?await l.annotatedTag({fs:i,dir:e,ref:t,message:a,tagger:gt()}):await l.tag({fs:i,dir:e,ref:t}),w(s,"INFO","Git tag created",{logId:s,tagName:t,annotated:!!a}),{success:!0,message:"Tag created successfully",logId:s,tagName:t}}catch(r){throw w(s,"ERROR","Failed to create tag",{logId:s,tagName:t,error:r.message}),new k("Failed to create tag",{originalError:r.message})}}async function it(n={}){const{tagName:t}=n;if(!t)throw new v("Tag name cannot be empty",{field:"tagName"});const{targetPath:a,logId:e}=P(n);await T(a);try{return await l.deleteRef({fs:i,dir:a,ref:`refs/tags/${t}`}),w(e,"INFO","Git tag deleted",{logId:e,tagName:t}),{success:!0,message:"Tag deleted successfully",logId:e,tagName:t}}catch(s){throw w(e,"ERROR","Failed to delete tag",{logId:e,tagName:t,error:s.message}),new k("Failed to delete tag",{originalError:s.message})}}async function nt(n={}){const{targetPath:t,logId:a}=P(n);await T(t);try{const e=await l.listBranches({fs:i,dir:t}),s=await l.currentBranch({fs:i,dir:t,fullname:!1}),r={};for(const o of e)r[o]={name:o,current:o===s};return{success:!0,logId:a,branches:r,current:s}}catch(e){throw w(a,"ERROR","Failed to list branches",{logId:a,error:e.message}),new k("Failed to list branches",{originalError:e.message})}}async function ot(n={}){const{branchName:t,startPoint:a}=n;if(!t)throw new v("Branch name cannot be empty",{field:"branchName"});const{targetPath:e,logId:s}=P(n);await T(e);try{const r=a||"HEAD";return await l.branch({fs:i,dir:e,ref:t,object:r,checkout:!0}),w(s,"INFO","Git branch created",{logId:s,branchName:t,startPoint:a}),{success:!0,message:"Branch created and switched to",logId:s,branchName:t}}catch(r){throw w(s,"ERROR","Failed to create branch",{logId:s,branchName:t,error:r.message}),new k("Failed to create branch",{originalError:r.message})}}async function ct(n={}){const{branchName:t}=n;if(!t)throw new v("Branch name cannot be empty",{field:"branchName"});const{targetPath:a,logId:e}=P(n);await T(a);try{const s=await l.statusMatrix({fs:i,dir:a});if(s.some(([o,c,p,h])=>c===0&&h===0?!1:p!==1||h!==1)){const o=s.filter(([,h])=>h!==0),c=o.filter(([,,h])=>h!==1).map(([h])=>h),p=o.filter(([,,,h])=>h!==1).map(([h])=>h);throw new G("Working directory is not clean, please commit or stash your changes before switching branches",{staged:p,modified:c})}return await l.checkout({fs:i,dir:a,ref:t}),w(e,"INFO","Git branch switched",{logId:e,branchName:t}),{success:!0,message:"Branch switched successfully",logId:e,branchName:t}}catch(s){throw s instanceof G?s:(w(e,"ERROR","Failed to switch branch",{logId:e,branchName:t,error:s.message}),new k("Failed to switch branch",{originalError:s.message}))}}async function lt(n={}){const{branchName:t,force:a=!1}=n;if(!t)throw new v("Branch name cannot be empty",{field:"branchName"});const{targetPath:e,logId:s}=P(n);await T(e);try{if(await l.currentBranch({fs:i,dir:e,fullname:!1})===t)throw new G("Cannot delete the current branch, please switch to another branch first");return await l.deleteBranch({fs:i,dir:e,ref:t,force:a}),w(s,"INFO","Git branch deleted",{logId:s,branchName:t,force:a}),{success:!0,message:"Branch deleted successfully",logId:s,branchName:t}}catch(r){throw r instanceof G?r:(w(s,"ERROR","Failed to delete branch",{logId:s,branchName:t,error:r.message}),new k("Failed to delete branch",{originalError:r.message}))}}export{q as init,z as status,K as commit,V as add,J as unstage,Q as discard,X as logHistory,Y as diff,Z as fileContent,tt as reset,et as revert,at as checkout,rt as listTags,st as createTag,it as deleteTag,nt as listBranches,ot as createBranch,ct as switchBranch,lt as deleteBranch};export default{init:q,status:z,commit:K,add:V,unstage:J,discard:Q,logHistory:X,diff:Y,fileContent:Z,reset:tt,revert:et,checkout:at,listTags:rt,createTag:st,deleteTag:it,listBranches:nt,createBranch:ot,switchBranch:ct,deleteBranch:lt};
|
|
8
|
+
`,d.push({file:f,changes:0,insertions:0,deletions:0,binary:!0});return}const{diff:m,insertions:p,deletions:S}=wt(f,x?b.content:"",E?O.content:"",x,E,x?b.buf:null,E?O.buf:null);y+=m,d.push({file:f,changes:p+S,insertions:p,deletions:S,binary:!1}),g+=p,u+=S}if(t==="commit"){let f,b;if(a&&e)f=a,b=e;else if(a){const I=await l.readCommit({fs:i,dir:r,oid:a});I.commit.parent&&I.commit.parent.length>0?(f=I.commit.parent[0],b=a):(f=null,b=a)}else throw new v("source=commit requires at least 'from'",{field:"from"});const O=f?new Set(await l.listFiles({fs:i,dir:r,ref:f})):new Set,x=new Set(await l.listFiles({fs:i,dir:r,ref:b})),E=new Set([...O,...x]);for(const I of E){if(c&&!c.has(I))continue;const m=O.has(I)?await _(r,f,I):null,p=x.has(I)?await _(r,b,I):null;await h(I,m,p)}}else{const f=await W(r),b=await l.statusMatrix({fs:i,dir:r});for(const[O,x,E,I]of b){if(c&&!c.has(O))continue;if(t==="staged"){if(I===1||x===0&&I===0)continue}else if(x===0&&I===0||x===1&&E===1&&I===1)continue;const m=x!==0?await _(r,f,O):null;let p=null;if(E!==0){const S=P.join(r,O);if(i.existsSync(S))try{const F=i.readFileSync(S);p={content:F.toString("utf8"),buf:F}}catch{}}await h(O,m,p)}}return{success:!0,logId:o,source:t,diff:y,summary:{files:d,insertions:g,deletions:u}}}catch(c){throw c instanceof v?c:(w(o,"ERROR","Failed to get Git diff",{logId:o,error:c.message}),new A("Failed to get Git diff",{originalError:c.message}))}}async function tt(n={}){const{ref:t="HEAD",filePath:a}=n;if(!a)throw new v("filePath is required",{field:"filePath"});const{targetPath:e,logId:s}=k(n);await T(e);try{let r;if(t==="worktree"||t==="staged"||t===""){const o=P.join(e,a);r=i.existsSync(o)?i.readFileSync(o,"utf8"):""}else try{const o=await l.resolveRef({fs:i,dir:e,ref:t}),{blob:c}=await l.readBlob({fs:i,dir:e,oid:o,filepath:a});r=Buffer.from(c).toString("utf8")}catch{r=""}return{success:!0,logId:s,filePath:a,ref:t,content:r}}catch(r){throw r instanceof D?r:(w(s,"ERROR","Failed to get file content",{logId:s,ref:t,filePath:a,error:r.message}),new A("Failed to get file content",{originalError:r.message}))}}async function et(n={}){const{target:t,mode:a="mixed"}=n;if(!t)throw new v("Reset target cannot be empty",{field:"target"});if(!["soft","mixed","hard"].includes(a))throw new v("Mode must be soft, mixed or hard",{field:"mode"});const{targetPath:e,logId:s}=k(n);await T(e);try{const r=await l.log({fs:i,dir:e,depth:1}),o=r.length>0?r[0].oid:null,c=await l.currentBranch({fs:i,dir:e,fullname:!1});if(!c)throw new G("Cannot reset: detached HEAD");const y=a==="hard"?new Set(await l.listFiles({fs:i,dir:e,ref:"HEAD"})):null;if(await l.writeRef({fs:i,dir:e,ref:`refs/heads/${c}`,value:t,force:!0}),a==="mixed"||a==="hard"){const d=await l.listFiles({fs:i,dir:e,ref:t}),g=new Set(d);for(const h of d)await l.resetIndex({fs:i,dir:e,filepath:h,ref:t});const u=await l.statusMatrix({fs:i,dir:e});for(const[h,,,f]of u)if(!g.has(h)&&f!==0)try{await l.remove({fs:i,dir:e,filepath:h})}catch{}}if(a==="hard"){const d=await l.listFiles({fs:i,dir:e,ref:t}),g=new Set(d);for(const u of d){const h=await _(e,t,u);if(!h)continue;const f=P.join(e,u);i.mkdirSync(P.dirname(f),{recursive:!0}),i.writeFileSync(f,h.buf)}if(y){for(const u of y)if(!g.has(u)){const h=P.join(e,u);i.existsSync(h)&&i.unlinkSync(h)}}M(e),await l.add({fs:i,dir:e,filepath:".gitignore"})}return w(s,"INFO","Git reset successful",{logId:s,target:t,mode:a,previousHead:o}),{success:!0,message:`Reset (${a}) to ${t} successful`,logId:s,target:t,mode:a,previousHead:o}}catch(r){throw r instanceof G?r:(w(s,"ERROR","Failed to reset",{logId:s,target:t,mode:a,error:r.message}),new A("Failed to reset",{originalError:r.message}))}}async function at(n={}){const{target:t,message:a,authorName:e,authorEmail:s}=n;if(!t)throw new v("Revert target cannot be empty",{field:"target"});const{targetPath:r,logId:o}=k(n);await T(r);try{let c;try{c=(await l.readCommit({fs:i,dir:r,oid:t})).oid}catch{throw new v("Revert target commit does not exist",{field:"target",target:t})}const y=await l.statusMatrix({fs:i,dir:r});if(y.some(([m,p,S,F])=>p===0&&F===0?!1:S!==1||F!==1)){const m=y.filter(([,F])=>F!==0),p=m.filter(([,,F])=>F!==1).map(([F])=>F),S=m.filter(([,,,F])=>F!==1).map(([F])=>F);throw new G("Working directory is not clean, please commit or stash your changes before reverting",{staged:S,modified:p})}const g=new Set(await l.listFiles({fs:i,dir:r,ref:c})),u=await W(r),h=new Set(await l.listFiles({fs:i,dir:r,ref:u})),f=[];for(const m of g){const p=await _(r,c,m);if(!p)continue;const S=P.join(r,m);i.mkdirSync(P.dirname(S),{recursive:!0}),i.writeFileSync(S,p.buf),await l.add({fs:i,dir:r,filepath:m})}for(const m of h)if(!g.has(m)){f.push(m);try{await l.remove({fs:i,dir:r,filepath:m})}catch{}const p=P.join(r,m);i.existsSync(p)&&await i.promises.unlink(p)}if(f.length>0&&await j(r,f),M(r),await l.add({fs:i,dir:r,filepath:".gitignore"}),!(await l.statusMatrix({fs:i,dir:r})).some(([,,,m])=>m!==1))return w(o,"INFO","Nothing to revert, current HEAD already matches target",{logId:o,target:c}),{success:!0,message:"Nothing to revert, already at target state",logId:o,nothingToCommit:!0,target:c};const x={name:e||B.GIT_DEFAULT_AUTHOR_NAME,email:s||B.GIT_DEFAULT_AUTHOR_EMAIL},E=a||`Revert to ${c.substring(0,7)}`,I=await l.commit({fs:i,dir:r,message:E,author:x});return w(o,"INFO","Git revert successful",{logId:o,target:c,commitHash:I,previousHead:u,removedFilesCount:f.length}),{success:!0,message:"Revert successful",logId:o,commit:I,target:c,previousHead:u}}catch(c){throw c instanceof v||c instanceof G?c:(w(o,"ERROR","Failed to revert",{logId:o,target:t,error:c.message}),new A("Failed to revert",{originalError:c.message}))}}async function rt(n={}){const{target:t}=n;if(!t)throw new v("Checkout target cannot be empty",{field:"target"});const{targetPath:a,logId:e}=k(n);await T(a);try{const s=await l.listFiles({fs:i,dir:a,ref:t});for(const r of s){const o=await _(a,t,r);if(!o)continue;const c=P.join(a,r);i.mkdirSync(P.dirname(c),{recursive:!0}),i.writeFileSync(c,o.buf),await l.add({fs:i,dir:a,filepath:r})}return M(a),await l.add({fs:i,dir:a,filepath:".gitignore"}),w(e,"INFO","Git checkout files successful",{logId:e,target:t}),{success:!0,message:`Checkout files from ${t} successful`,logId:e,target:t}}catch(s){throw w(e,"ERROR","Failed to checkout files",{logId:e,target:t,error:s.message}),new A("Failed to checkout files",{originalError:s.message})}}async function st(n={}){const{targetPath:t,logId:a}=k(n);await T(t);try{const e=await l.listTags({fs:i,dir:t});return{success:!0,logId:a,tags:e,latest:e.length>0?e[e.length-1]:null}}catch(e){throw w(a,"ERROR","Failed to list tags",{logId:a,error:e.message}),new A("Failed to list tags",{originalError:e.message})}}async function it(n={}){const{tagName:t,message:a}=n;if(!t)throw new v("Tag name cannot be empty",{field:"tagName"});const{targetPath:e,logId:s}=k(n);await T(e);try{return a?await l.annotatedTag({fs:i,dir:e,ref:t,message:a,tagger:mt()}):await l.tag({fs:i,dir:e,ref:t}),w(s,"INFO","Git tag created",{logId:s,tagName:t,annotated:!!a}),{success:!0,message:"Tag created successfully",logId:s,tagName:t}}catch(r){throw w(s,"ERROR","Failed to create tag",{logId:s,tagName:t,error:r.message}),new A("Failed to create tag",{originalError:r.message})}}async function nt(n={}){const{tagName:t}=n;if(!t)throw new v("Tag name cannot be empty",{field:"tagName"});const{targetPath:a,logId:e}=k(n);await T(a);try{return await l.deleteRef({fs:i,dir:a,ref:`refs/tags/${t}`}),w(e,"INFO","Git tag deleted",{logId:e,tagName:t}),{success:!0,message:"Tag deleted successfully",logId:e,tagName:t}}catch(s){throw w(e,"ERROR","Failed to delete tag",{logId:e,tagName:t,error:s.message}),new A("Failed to delete tag",{originalError:s.message})}}async function ot(n={}){const{targetPath:t,logId:a}=k(n);await T(t);try{const e=await l.listBranches({fs:i,dir:t}),s=await l.currentBranch({fs:i,dir:t,fullname:!1}),r={};for(const o of e)r[o]={name:o,current:o===s};return{success:!0,logId:a,branches:r,current:s}}catch(e){throw w(a,"ERROR","Failed to list branches",{logId:a,error:e.message}),new A("Failed to list branches",{originalError:e.message})}}async function ct(n={}){const{branchName:t,startPoint:a}=n;if(!t)throw new v("Branch name cannot be empty",{field:"branchName"});const{targetPath:e,logId:s}=k(n);await T(e);try{const r=a||"HEAD";return await l.branch({fs:i,dir:e,ref:t,object:r,checkout:!0}),w(s,"INFO","Git branch created",{logId:s,branchName:t,startPoint:a}),{success:!0,message:"Branch created and switched to",logId:s,branchName:t}}catch(r){throw w(s,"ERROR","Failed to create branch",{logId:s,branchName:t,error:r.message}),new A("Failed to create branch",{originalError:r.message})}}async function lt(n={}){const{branchName:t}=n;if(!t)throw new v("Branch name cannot be empty",{field:"branchName"});const{targetPath:a,logId:e}=k(n);await T(a);try{const s=await l.statusMatrix({fs:i,dir:a});if(s.some(([o,c,y,d])=>c===0&&d===0?!1:y!==1||d!==1)){const o=s.filter(([,d])=>d!==0),c=o.filter(([,,d])=>d!==1).map(([d])=>d),y=o.filter(([,,,d])=>d!==1).map(([d])=>d);throw new G("Working directory is not clean, please commit or stash your changes before switching branches",{staged:y,modified:c})}return await l.checkout({fs:i,dir:a,ref:t}),w(e,"INFO","Git branch switched",{logId:e,branchName:t}),{success:!0,message:"Branch switched successfully",logId:e,branchName:t}}catch(s){throw s instanceof G?s:(w(e,"ERROR","Failed to switch branch",{logId:e,branchName:t,error:s.message}),new A("Failed to switch branch",{originalError:s.message}))}}async function ft(n={}){const{branchName:t,force:a=!1}=n;if(!t)throw new v("Branch name cannot be empty",{field:"branchName"});const{targetPath:e,logId:s}=k(n);await T(e);try{if(await l.currentBranch({fs:i,dir:e,fullname:!1})===t)throw new G("Cannot delete the current branch, please switch to another branch first");return await l.deleteBranch({fs:i,dir:e,ref:t,force:a}),w(s,"INFO","Git branch deleted",{logId:s,branchName:t,force:a}),{success:!0,message:"Branch deleted successfully",logId:s,branchName:t}}catch(r){throw r instanceof G?r:(w(s,"ERROR","Failed to delete branch",{logId:s,branchName:t,error:r.message}),new A("Failed to delete branch",{originalError:r.message}))}}export{z as init,K as status,V as commit,J as add,Q as unstage,X as discard,Y as logHistory,Z as diff,tt as fileContent,et as reset,at as revert,rt as checkout,st as listTags,it as createTag,nt as deleteTag,ot as listBranches,ct as createBranch,lt as switchBranch,ft as deleteBranch};export default{init:z,status:K,commit:V,add:J,unstage:Q,discard:X,logHistory:Y,diff:Z,fileContent:tt,reset:et,revert:at,checkout:rt,listTags:st,createTag:it,deleteTag:nt,listBranches:ot,createBranch:ct,switchBranch:lt,deleteBranch:ft};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import
|
|
2
|
-
`+
|
|
1
|
+
import f from"path";import n from"fs";import e from"isomorphic-git";import o from"../../appConfig/index.js";function g(i){return n.existsSync(f.join(i,".git"))}function m(){return{name:o.GIT_DEFAULT_AUTHOR_NAME,email:o.GIT_DEFAULT_AUTHOR_EMAIL}}async function d(i){const t=await e.statusMatrix({fs:n,dir:i});await Promise.all(t.map(([a,s,l])=>{if(l===2)return e.add({fs:n,dir:i,filepath:a}).catch(()=>{});if(s===1&&l===0)return e.remove({fs:n,dir:i,filepath:a}).catch(()=>{})}))}async function A(i,t){for(const a of t){const s=f.join(i,a);n.existsSync(s)?await e.add({fs:n,dir:i,filepath:a}):await e.remove({fs:n,dir:i,filepath:a}).catch(()=>{})}}async function T(i){if(g(i))c(i);else{await e.init({fs:n,dir:i,defaultBranch:"main"}),await e.setConfig({fs:n,dir:i,path:"user.name",value:o.GIT_DEFAULT_AUTHOR_NAME}),await e.setConfig({fs:n,dir:i,path:"user.email",value:o.GIT_DEFAULT_AUTHOR_EMAIL}),c(i);const t=f.join(i,".gitignore");n.existsSync(t)&&await e.add({fs:n,dir:i,filepath:".gitignore"}),(await e.listFiles({fs:n,dir:i})).length===0&&(n.writeFileSync(f.join(i,".gitkeep"),""),await e.add({fs:n,dir:i,filepath:".gitkeep"})),await e.commit({fs:n,dir:i,message:"Initial commit",author:m()})}}async function _(i,t){if(g(i))try{Array.isArray(t)&&t.length>0?await A(i,t):await d(i)}catch{}}function c(i){if(!o.GIT_AUTO_GITIGNORE)return;const t=f.join(i,".gitignore"),a=o.GIT_GITIGNORE_ENTRIES||[];let s=[];n.existsSync(t)&&(s=n.readFileSync(t,"utf8").split(/\r?\n/));const l=new Set(s.map(r=>r.trim()).filter(Boolean)),u=a.filter(r=>!l.has(r));if(u.length>0){const r=s.length>0&&s[s.length-1]!==""?`
|
|
2
|
+
`+u.join(`
|
|
3
3
|
`)+`
|
|
4
|
-
`:
|
|
4
|
+
`:u.join(`
|
|
5
5
|
`)+`
|
|
6
|
-
`;n.appendFileSync(t,
|
|
6
|
+
`;n.appendFileSync(t,r,"utf8")}}export{g as isGitRepo,T as ensureGitRepo,c as ensureGitignore,_ as autoGitAdd,d as addAll,A as stageFiles,m as getDefaultAuthor};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nuwax-file-server",
|
|
3
3
|
"displayName": "nuwax-file-server",
|
|
4
|
-
"version": "1.3.0-beta.
|
|
4
|
+
"version": "1.3.0-beta.26",
|
|
5
5
|
"description": "Cross-platform file service deployment tool with start/stop/restart CLI commands",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"main": "index.js",
|