Last active
August 13, 2021 01:21
-
-
Save davidakerr/2ef46c4c877bed9b5edeadcee8088609 to your computer and use it in GitHub Desktop.
NodeJs Github backup script (All Repositories)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const https = require("https"); | |
const fs = require("fs"); | |
const { exec } = require("child_process"); | |
const outputDir = "repos"; | |
const token = "PERSONAL_ACCESS_TOKEN"; | |
const options = { | |
method: "GET", | |
hostname: "api.github.com", | |
path: "/user/repos", | |
headers: { | |
Authorization: `token ${token}`, | |
"user-agent": "node.js", | |
}, | |
maxRedirects: 20, | |
}; | |
function doRequest(options) { | |
return new Promise((resolve, reject) => { | |
const req = https.request(options, function (res) { | |
const chunks = []; | |
res.on("data", function (chunk) { | |
chunks.push(chunk); | |
}); | |
res.on("end", function (chunk) { | |
const body = Buffer.concat(chunks); | |
resolve(JSON.parse(body.toString())); | |
}); | |
res.on("error", function (error) { | |
reject(error); | |
}); | |
}); | |
req.end(); | |
}); | |
} | |
async function backupGithub() { | |
const repos = await doRequest(options); | |
repos.forEach((repo) => { | |
if (!fs.existsSync(outputDir)) { | |
try { | |
fs.mkdirSync(outputDir); | |
console.log(`Directory doesn't exit creating '${outputDir}'`); | |
} catch (error) { | |
console.error(error); | |
} | |
} | |
if (!fs.existsSync(`${outputDir}/${repo.clone_url.substring(30)}`)) { | |
try { | |
exec( | |
`cd ${outputDir} && git clone --mirror https://${token}@${repo.clone_url.substring( | |
8 | |
)}` | |
); | |
console.log(`Creating mirror ${repo.clone_url}`); | |
} catch (error) { | |
console.error(error); | |
} | |
} else { | |
try { | |
exec( | |
`cd ${outputDir}/${repo.clone_url.substring(30)} && git remote update` | |
); | |
console.log(`Updating mirror ${repo.clone_url.substring(30)}`); | |
} catch (error) { | |
console.error(error); | |
} | |
} | |
}); | |
} | |
backupGithub(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment