CoolFace
Apppublic

Sri-dharshini/multi-tenant-organization-system

sourceHugging Faceupdated 5mo agoView on Hugging Face
0likes
push_to_github.mjs173 linesDownload Raw Back to root
1import fs from 'fs';2import path from 'path';3 4const TOKEN = "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";5const REPO = "sridharshini-16/multi-tenant-organization-system";6 7async function pushToGitHub() {8  const baseHeaders = {9    "Authorization": `Bearer ${TOKEN}`,10    "Accept": "application/vnd.github.v3+json",11    "X-GitHub-Api-Version": "2022-11-28",12  };13 14  // CHECK IF REPO IS EMPTY15  let refsReq = await fetch(`https://api.github.com/repos/${REPO}/git/refs`, { headers: baseHeaders });16  let refs = await refsReq.json();17  18  if (refs.message === "Git Repository is empty." || (Array.isArray(refs) && refs.length === 0)) {19     console.log("Repository is empty. Initializing with a .gitkeep file via Contents API...");20     const initRes = await fetch(`https://api.github.com/repos/${REPO}/contents/.gitkeep`, {21        method: "PUT",22        headers: { ...baseHeaders, "Content-Type": "application/json" },23        body: JSON.stringify({24            message: "Initialize Repository",25            content: Buffer.from("initialized").toString("base64")26        })27     });28     29     if (!initRes.ok) throw new Error("Failed to initialize repo: " + await initRes.text());30     console.log("Initialization complete. Awaiting github propagation...");31     await new Promise(r => setTimeout(r, 2000));32  }33 34  function getFiles(dir, filesList = []) {35    const files = fs.readdirSync(dir);36    for (const file of files) {37      if (['node_modules', '.next', '.git'].includes(file)) continue;38      const fullPath = path.join(dir, file);39      if (fs.statSync(fullPath).isDirectory()) {40         getFiles(fullPath, filesList);41      } else {42         filesList.push(fullPath);43      }44    }45    return filesList;46  }47 48  const allFiles = getFiles(process.cwd());49  const tree = [];50 51  console.log(`Found ${allFiles.length} files. Uploading blobs...`);52  53  for (const filePath of allFiles) {54    const relativePath = path.relative(process.cwd(), filePath).replace(/\\/g, '/');55    const content = fs.readFileSync(filePath);56    let encoding = "utf-8";57    let bodyContent = content.toString('utf-8');58 59    if (filePath.endsWith('.png') || filePath.endsWith('.ico') || filePath.endsWith('.jpg')) {60      encoding = "base64";61      bodyContent = content.toString('base64');62    }63 64    const blobReq = await fetch(`https://api.github.com/repos/${REPO}/git/blobs`, {65      method: "POST",66      headers: { ...baseHeaders, "Content-Type": "application/json" },67      body: JSON.stringify({68        content: bodyContent,69        encoding: encoding70      })71    });72    73    if (!blobReq.ok) {74       console.error(`Failed uploading blob for ${relativePath}:`, await blobReq.text());75       continue;76    }77    78    const { sha } = await blobReq.json();79    tree.push({80      path: relativePath,81      mode: '100644',82      type: 'blob',83      sha: sha84    });85    console.log(`Uploaded: ${relativePath}`);86  }87 88  console.log("Creating tree...");89  90  // Re-fetch refs to get the correct parent91  refsReq = await fetch(`https://api.github.com/repos/${REPO}/git/refs`, { headers: baseHeaders });92  refs = await refsReq.json();93  94  let parentSha = null;95  let branchRef = "heads/main";96  97  let mainRefObj = Array.isArray(refs) ? refs.find(r => r.ref === "refs/heads/main" || r.ref === "refs/heads/master") : null;98  if (mainRefObj) {99      parentSha = mainRefObj.object.sha;100      branchRef = mainRefObj.ref.replace("refs/", ""); 101  } else if (Array.isArray(refs) && refs.length > 0) {102      parentSha = refs[0].object.sha;103      branchRef = refs[0].ref.replace("refs/", "");104  }105 106  // Get base tree to prevent deletion of existing files if any (though we are replacing all)107  const treeRes = await fetch(`https://api.github.com/repos/${REPO}/git/trees`, {108    method: "POST",109    headers: { ...baseHeaders, "Content-Type": "application/json" },110    body: JSON.stringify({ 111      tree,112      ...(parentSha ? { base_tree: parentSha } : {}) 113    })114  }).then(async r => {115    if (!r.ok) throw new Error("Tree creation failed: " + await r.text());116    return r.json();117  });118  119  const treeSha = treeRes.sha;120  console.log("Tree created with SHA:", treeSha);121  122  const parents = parentSha ? [parentSha] : [];123 124  console.log("Creating commit...");125  const commitRes = await fetch(`https://api.github.com/repos/${REPO}/git/commits`, {126    method: "POST",127    headers: { ...baseHeaders, "Content-Type": "application/json" },128    body: JSON.stringify({129      message: "Initialize Permify Final System",130      tree: treeSha,131      parents: parents132    })133  }).then(async r => {134    if (!r.ok) throw new Error("Commit failed: " + await r.text());135    return r.json();136  });137 138  const commitSha = commitRes.sha;139  console.log("Commit created with SHA:", commitSha);140 141  if (parents.length === 0) {142    console.log(`Creating branch reference refs/heads/main...`);143    const updateRes = await fetch(`https://api.github.com/repos/${REPO}/git/refs`, {144      method: "POST",145      headers: { ...baseHeaders, "Content-Type": "application/json" },146      body: JSON.stringify({147        ref: "refs/heads/main",148        sha: commitSha149      })150    });151    if (!updateRes.ok) throw new Error("Failed to create ref: " + await updateRes.text());152  } else {153    console.log(`Updating branch reference refs/${branchRef}...`);154    const updateRes = await fetch(`https://api.github.com/repos/${REPO}/git/refs/${branchRef}`, {155      method: "PATCH",156      headers: { ...baseHeaders, "Content-Type": "application/json" },157      body: JSON.stringify({158        sha: commitSha,159        force: true160      })161    });162    if (!updateRes.ok) throw new Error("Failed to update ref: " + await updateRes.text());163  }164 165  console.log("Successfully deployed to GitHub!");166}167 168pushToGitHub().catch(err => {169  console.error("Error during GitHub deployment:");170  console.error(err);171  process.exit(1);172});173