avoid branches without metadata

but keep trying to  load metadata for remaining unpublished branches
This commit is contained in:
Cássio Zen 2016-10-10 18:33:49 -03:00
parent cc1c2f91e0
commit e89db336a7
2 changed files with 90 additions and 82 deletions

View File

@ -22,7 +22,7 @@ export default class API {
return {
Authorization: `token ${ this.token }`,
'Content-Type': 'application/json',
...headers
...headers,
};
}
@ -52,7 +52,7 @@ export default class API {
request(path, options = {}) {
const headers = this.requestHeaders(options.headers || {});
const url = this.urlFor(path, options);
return fetch(url, { ...options, headers: headers }).then((response) => {
return fetch(url, { ...options, headers }).then((response) => {
const contentType = response.headers.get('Content-Type');
if (contentType && contentType.match(/json/)) {
return this.parseJsonResponse(response);
@ -67,16 +67,16 @@ export default class API {
cache: 'no-store',
})
.then(response => response.object)
.catch(error => {
.catch((error) => {
// Meta ref doesn't exist
const readme = {
raw: '# Netlify CMS\n\nThis tree is used by the Netlify CMS to store metadata information for specific files and branches.'
raw: '# Netlify CMS\n\nThis tree is used by the Netlify CMS to store metadata information for specific files and branches.',
};
return this.uploadBlob(readme)
.then(item => this.request(`${ this.repoURL }/git/trees`, {
method: 'POST',
body: JSON.stringify({ tree: [{ path: 'README.md', mode: '100644', type: 'blob', sha: item.sha }] })
body: JSON.stringify({ tree: [{ path: 'README.md', mode: '100644', type: 'blob', sha: item.sha }] }),
}))
.then(tree => this.commit('First Commit', tree))
.then(response => this.createRef('meta', '_netlify_cms', response.sha))
@ -91,8 +91,8 @@ export default class API {
[`${ key }.json`]: {
path: `${ key }.json`,
raw: JSON.stringify(data),
file: true
}
file: true,
},
};
return this.uploadBlob(fileTree[`${ key }.json`])
@ -102,7 +102,7 @@ export default class API {
.then(() => {
LocalForage.setItem(`gh.meta.${ key }`, {
expires: Date.now() + 300000, // In 5 minutes
data
data,
});
});
});
@ -130,7 +130,7 @@ export default class API {
return this.request(`${ this.repoURL }/contents/${ path }`, {
headers: { Accept: 'application/vnd.github.VERSION.raw' },
params: { ref: branch },
cache: false
cache: false,
}).then((result) => {
if (sha) {
LocalForage.setItem(`gh.${ sha }`, result);
@ -142,20 +142,22 @@ export default class API {
listFiles(path) {
return this.request(`${ this.repoURL }/contents/${ path }`, {
params: { ref: this.branch }
params: { ref: this.branch },
});
}
readUnpublishedBranchFile(contentKey) {
let metaData;
return this.retrieveMetadata(contentKey)
.then(data => {
const unpublishedPromise = this.retrieveMetadata(contentKey)
.then((data) => {
metaData = data;
return this.readFile(data.objects.entry, null, data.branch);
})
.then(file => {
return { metaData, file };
.then(file => ({ metaData, file }))
.catch((error) => {
return null;
});
return unpublishedPromise;
}
listUnpublishedBranches() {
@ -172,7 +174,7 @@ export default class API {
files.forEach((file) => {
if (file.uploaded) { return; }
uploadPromises.push(this.uploadBlob(file));
parts = file.path.split('/').filter((part) => part);
parts = file.path.split('/').filter(part => part);
filename = parts.pop();
subtree = fileTree;
while (part = parts.shift()) {
@ -211,14 +213,14 @@ export default class API {
.then(commitResponse => this.createBranch(branchName, commitResponse.sha))
.then(branchResponse => this.createPR(options.commitMessage, branchName))
.then((prResponse) => {
return this.user().then(user => {
return this.user().then((user) => {
return user.name ? user.name : user.login;
})
.then(username => this.storeMetadata(contentKey, {
type: 'PR',
pr: {
number: prResponse.number,
head: prResponse.head && prResponse.head.sha
head: prResponse.head && prResponse.head.sha,
},
user: username,
status: status.first(),
@ -228,9 +230,9 @@ export default class API {
description: options.parsedData && options.parsedData.description,
objects: {
entry: entry.path,
files: filesList
files: filesList,
},
timeStamp: new Date().toISOString()
timeStamp: new Date().toISOString(),
}));
});
} else {
@ -241,11 +243,11 @@ export default class API {
.then((response) => {
const contentKey = options.collectionName ? `${ options.collectionName }-${ entry.slug }` : entry.slug;
const branchName = `cms/${ contentKey }`;
return this.user().then(user => {
return this.user().then((user) => {
return user.name ? user.name : user.login;
})
.then(username => this.retrieveMetadata(contentKey))
.then(metadata => {
.then((metadata) => {
let files = metadata.objects && metadata.objects.files || [];
files = files.concat(filesList);
@ -255,9 +257,9 @@ export default class API {
description: options.parsedData && options.parsedData.description,
objects: {
entry: entry.path,
files: _.uniq(files)
files: _.uniq(files),
},
timeStamp: new Date().toISOString()
timeStamp: new Date().toISOString(),
};
})
.then(updatedMetadata => this.storeMetadata(contentKey, updatedMetadata))
@ -269,10 +271,10 @@ export default class API {
updateUnpublishedEntryStatus(collection, slug, status) {
const contentKey = collection ? `${ collection }-${ slug }` : slug;
return this.retrieveMetadata(contentKey)
.then(metadata => {
.then((metadata) => {
return {
...metadata,
status
status,
};
})
.then(updatedMetadata => this.storeMetadata(contentKey, updatedMetadata));
@ -281,7 +283,7 @@ export default class API {
publishUnpublishedEntry(collection, slug, status) {
const contentKey = collection ? `${ collection }-${ slug }` : slug;
return this.retrieveMetadata(contentKey)
.then(metadata => {
.then((metadata) => {
const headSha = metadata.pr && metadata.pr.head;
const number = metadata.pr && metadata.pr.number;
return this.mergePR(headSha, number);
@ -299,7 +301,7 @@ export default class API {
patchRef(type, name, sha) {
return this.request(`${ this.repoURL }/git/refs/${ type }/${ name }`, {
method: 'PATCH',
body: JSON.stringify({ sha })
body: JSON.stringify({ sha }),
});
}
@ -338,7 +340,7 @@ export default class API {
method: 'PUT',
body: JSON.stringify({
commit_message: 'Automatically generated. Merged on Netlify CMS.',
sha: headSha
sha: headSha,
}),
});
}
@ -361,8 +363,8 @@ export default class API {
method: 'POST',
body: JSON.stringify({
content: contentBase64,
encoding: 'base64'
})
encoding: 'base64',
}),
}).then((response) => {
item.sha = response.sha;
item.uploaded = true;
@ -374,11 +376,11 @@ export default class API {
updateTree(sha, path, fileTree) {
return this.getTree(sha)
.then((tree) => {
var obj, filename, fileOrDir;
var updates = [];
var added = {};
let obj, filename, fileOrDir;
const updates = [];
const added = {};
for (var i = 0, len = tree.tree.length; i < len; i++) {
for (let i = 0, len = tree.tree.length; i < len; i++) {
obj = tree.tree[i];
if (fileOrDir = fileTree[obj.path]) {
added[obj.path] = true;
@ -402,10 +404,10 @@ export default class API {
.then((updates) => {
return this.request(`${ this.repoURL }/git/trees`, {
method: 'POST',
body: JSON.stringify({ base_tree: sha, tree: updates })
body: JSON.stringify({ base_tree: sha, tree: updates }),
});
}).then((response) => {
return { path: path, mode: '040000', type: 'tree', sha: response.sha, parentSha: sha };
return { path, mode: '040000', type: 'tree', sha: response.sha, parentSha: sha };
});
});
}
@ -415,7 +417,7 @@ export default class API {
const parents = changeTree.parentSha ? [changeTree.parentSha] : [];
return this.request(`${ this.repoURL }/git/commits`, {
method: 'POST',
body: JSON.stringify({ message, tree, parents })
body: JSON.stringify({ message, tree, parents }),
});
}

View File

@ -78,11 +78,16 @@ export default class GitHub {
promises.push(new Promise((resolve, reject) => {
const contentKey = branch.ref.split('refs/heads/cms/').pop();
return sem.take(() => this.api.readUnpublishedBranchFile(contentKey).then((data) => {
if (data === null || data === undefined) {
resolve(null);
sem.leave();
} else {
const entryPath = data.metaData.objects.entry;
const entry = createEntry('draft', entryPath.split('/').pop().replace(/\.[^\.]+$/, ''), entryPath, { raw: data.file });
entry.metaData = data.metaData;
resolve(entry);
sem.leave();
}
}).catch((err) => {
sem.leave();
reject(err);
@ -91,9 +96,10 @@ export default class GitHub {
});
return Promise.all(promises);
}).then((entries) => {
const filteredEntries = entries.filter(entry => entry !== null);
return {
pagination: {},
entries,
pagination: 0,
entries: filteredEntries,
};
});
}