Skip to content

Instantly share code, notes, and snippets.

@Thaina
Last active June 20, 2016 03:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Thaina/a5cce92fc17c7135e4a3f7148f700000 to your computer and use it in GitHub Desktop.
Save Thaina/a5cce92fc17c7135e4a3f7148f700000 to your computer and use it in GitHub Desktop.
/** @param {string} id
* @param {string} secret */
function BitBucket(id, secret){
this.auth = AccessToken(id, secret);
this.Commit = function(repo,branch,message,files){
return Commit(repo,branch,message,files,this.auth.access_token);
}
}
/** @param {string} id
* @param {string} secret
* @return {{access_token:string}} */
function AccessToken(id, secret){
var resp = UrlFetchApp.fetch("https://bitbucket.org/site/oauth2/access_token", {
method: "POST",
payload: { grant_type: "client_credentials",scope: "repository:write" },
headers: { Authorization: 'Basic ' + Utilities.base64Encode(id + ":" + secret) }
});
return JSON.parse(resp);
}
/** @param {{key:string,value:string}} files key:filename,value:stringContent */
function Commit(repo,branch,message,files,accessToken) {
var resp = UrlFetchApp.fetch("https://bitbucket.org/api/1.0/repositories/" + repo + "/branches-tags", { headers: { Authorization: "Bearer " + accessToken } });
var data = JSON.parse(resp);
Logger.log(data);
var head = null;
for (var i in data.branches)
{
var item = data.branches[i];
if (item.name == branch)
{
head = item.heads[0];
break;
}
}
if(!head)
throw new Error("Cannot get head from " + repo + ":" + branch);
var allFile = [];
for (var fileName in files)
allFile.push({ "path": fileName, "content": files[fileName] });
var commitData = {
"branch": branch,
"files": allFile,
"parents": [head],
"message": message,
"repository": { "full_name": repo },
"timestamp": new Date().toString(),
"transient": false
};
var resp = UrlFetchApp.fetch("https://bitbucket.org/!api/internal/repositories/" + repo + "/oecommits/", {
method: "POST",
contentType: "application/json",
headers: { Authorization: "Bearer " + accessToken },
payload: JSON.stringify(commitData)
});
Logger.log(resp);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment