UNPKG

@cmtlyt/git-down

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