1
0
mirror of https://github.com/chinchang/web-maker.git synced 2025-07-16 19:46:19 +02:00

Add a readonly github intergration

This commit is contained in:
Kushagra Gour
2018-11-05 22:05:13 +05:30
parent fb4fc6b37e
commit d127720a1f
4 changed files with 165 additions and 54 deletions

View File

@@ -116,3 +116,57 @@ export function getParentPath(path) {
}
return '';
}
/**
* Fetches the files from a github repo and returns a suitable file structure.
* @param {Promise} Promise of completition. Resolves to the files structure.
*/
export function importGithubRepo(repoUrl) {
let repoSlug, match;
if ((match = repoUrl.match(/github\.com\/([^\/]*\/[^\/]*)/))) {
repoSlug = match[1];
} else {
repoSlug = 'chinchang/github';
}
const queryString = '';
function fetchFile(filepath) {
return fetch(
`https://api.github.com/repos/${repoSlug}/contents/${filepath}${queryString}`
).then(response => response.json());
}
function fetchDir(path, currentDir) {
return fetch(
`https://api.github.com/repos/${repoSlug}/contents/${path}${queryString}`
)
.then(response => response.json())
.then(response => {
if (!response) {
return;
}
return Promise.all(
response.map(file => {
if (file.type === 'file') {
return fetchFile(`${file.path}`).then(actualFile => {
currentDir.push({
name: file.name,
content: atob(actualFile.content)
});
});
} else if (file.type === 'dir') {
const newEntry = {
name: file.name,
children: [],
isFolder: true
};
currentDir.push(newEntry);
return fetchDir(`${file.path}`, newEntry.children);
}
})
);
});
}
const files = [];
return fetchDir('', files).then(() => {
return files;
});
}