@snailuu/git-down
Version:
3 lines (2 loc) • 2.34 kB
JavaScript
import{extname as v,resolve as p}from"node:path";import{exec as j}from"node:child_process";import{existsSync as f}from"node:fs";import{mkdir as q,rm as D,cp as I,rename as M,readFile as O,writeFile as S}from"node:fs/promises";import{promisify as F}from"node:util";const a=F(j);async function w(t){if(!f(t))return q(t,{recursive:!0})}async function g(t){if(f(t))return D(t,{recursive:!0,force:!0}).catch(()=>{})}function P(t){return{output:"./git-down",branch:"main",...t}}function R(t){return i=>{if(i){if(!t)throw i;t(i)}t&&t(null)}}function b(t){const i=t.replace(/(^https?:\/\/github\.com\/)|(^git@github\.com:)/,"/"),[,e,o,,n="",...r]=i.split("/"),c=r.join("/"),s=i.includes("blob")||!!v(c);return{href:t,owner:e,project:o.replace(/\.git$/,""),isRepo:i.endsWith(".git")||!i.includes("tree")&&!i.includes("blob"),sourceType:s?"file":"dir",branch:n,pathname:c}}async function T(t,i){f(i)?await I(t,i,{recursive:!0}):await M(t,i)}function W(t){const{gitInfo:i,option:e,callback:o}=t,{branch:n,output:r}=e,{owner:c,project:s}=i,l={cwd:p(r)};return a("git init --quiet",l).then(()=>a(`git remote add origin https://github.com/${c}/${s}`,l),o).then(()=>a(`git pull origin --quiet ${n} --depth 1`,l),o).then(()=>g(p(r,".git")),o)}async function A(t){const{gitInfo:i,callback:e,option:o}=t,{output:n}=o,{pathname:r,sourceType:c,branch:s,owner:l,project:y}=i,u=p(n,`./.git-down-temp-folder-${Date.now()}-${Math.random().toString(36).slice(2)}`);f(u)&&g(u),await w(u).catch(e);const m=p(u,".git/info/sparse-checkout"),k=c==="file"?r:`${r}/*`,C=`${f(m)?await O(m,{encoding:"utf-8"}):""}
${k}`,x=p(n,r.split("/").pop()),h={cwd:u},d=`remote-${Date.now()}-${Math.random().toString(36).slice(2)}`;return a("git init --quiet",h).then(()=>a(`git remote add ${d} https://github.com/${l}/${y}`,h),e).then(async()=>{try{if((await a("git config --get core.sparseCheckout",h)).stdout.trim()==="true")return}catch{}return a("git config core.sparseCheckout true",h)},e).then(()=>S(m,C),e).then(()=>a(`git pull ${d} --quiet ${s} --depth 1`,h),e).then(()=>T(p(u,r),x),e).then(()=>g(u),e)}function $(t,i,e){const o=P(i),n=R(e),r=b(t),c={option:o,callback:n,gitInfo:r};w(o.output).then(()=>(r.isRepo?W:A)(c),n).then(()=>n(null),n)}function G(t,i){return new Promise((e,o)=>{$(t,i,n=>{n?o(n):e()})})}export{G as default,$ as gitDownWithCallback,b as parseGitUrl};