import{execSync as w}from"node:child_process";import{existsSync as E,mkdirSync as b}from"node:fs";import{join as R}from"node:path";async function S(g={}){let{baseDir:c="/workspace/repos",repos:p=null,depth:m=1,branch:u=null}=g,h=process.env.REPOS;if(!h)throw new Error("REPOS environment variable not set. Are you running in a Zibby workflow container?");let r;try{r=JSON.parse(h)}catch(e){throw new Error(`Failed to parse REPOS env var: ${e.message}`,{cause:e})}if(!Array.isArray(r)||r.length===0)throw new Error("No repositories configured for this project");let f=p?r.filter(e=>p.includes(e.name)):r;if(f.length===0)throw new Error(`No matching repositories found. Available: ${r.map(e=>e.name).join(", ")}`);E(c)||b(c,{recursive:!0});let n={};return await Promise.all(f.map(async e=>{let o=e.provider||"github",t=o==="gitlab"?process.env.GITLAB_TOKEN:process.env.GITHUB_TOKEN;if(!t){console.error(`${o.toUpperCase()}_TOKEN not set, skipping ${e.name}`),n[e.name]=null;return}let d=e.name.replace(/\//g,"-"),l=R(c,d),s=e.cloneUrl||e.url;if(!s){console.error(`Repository "${e.name}" has no clone URL`),n[e.name]=null;return}let i;o==="gitlab"?i=s.replace(/^https:\/\//,`https://oauth2:${t}@`):i=s.replace(/^https:\/\//,`https://x-access-token:${t}@`);let a=["clone"];m>0&&a.push("--depth",m.toString()),u&&a.push("--branch",u),a.push(i,l);let y=`git ${a.join(" ")}`;console.log(`Cloning ${e.name} (${o}) to ${l}...`);try{w(y,{stdio:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),console.log(`Repository ${e.name} cloned successfully`),n[e.name]=l}catch($){let v=$.message.replace(t,"***").replace(i,s);console.error(`Failed to clone ${e.name}: ${v}`),n[e.name]=null}})),n}export{S as cloneRepo};
