Github-api get commits - github

Can someone explain me or give some tutorial to get all the commit details for a particular in github. I saw this and I didn't understand how to use that.

You can check my article about this:
http://ondrek.me/articles/how-to-parse-github-API-in-nodejs/
This is NodeJs way
(for client js change require("https") to client ajax JSON - code is very simular)
Quick sample link for repo MDOWN of user ONDREK
https://api.github.com/repos/ondrek/mdown/git/refs/heads/
How to make a request to Github API
var options = {
user : 'ondrek',
repo : 'favicon-blog',
branch : 'master'
};
function getHttpRequestJson(customPath, callback){
require('https').request({
hostname: 'api.github.com',
path: customPath,
method: 'GET'
}, function(res){
var data = '';
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function () {
callback(JSON.parse(data));
});
}).end();
}
How to get user details json from Github API
(inject previous code)
var url = '/repos/'+options.user+'/'+options.repo+'/git/refs/heads/'+options.branch;
getHttpRequestJson(url, function(userJson){
var lastCommitUrl = userJson.object.url;
getLastCommit(lastCommitUrl);
});
How to get last commit json from Github API
(inject previous code)
function getLastCommit(url){
getHttpRequestJson(url+auth, function(lastCommitJson){
var treeUrl = lastCommitJson.tree.url;
getTree(treeUrl);
});
}
How to get tree of last commit from Github API
(inject previous code)
function getTree(url){
getHttpRequestJson(url+auth, function(treeJson){
var treeArr = treeJson.tree;
getOnlyPages(treeArr);
});
}
How to get specific folder of last commit from Github API
(inject previous code)
function getOnlyPages(treeArr){
treeArr.forEach(function(ele){
if (ele.path==='blog') { getArticles(ele.url); }
});
}
function getArticles(url){
getHttpRequestJson(url+auth, function(treeJson){
var treeArr = treeJson;
parseMarkdownArticles(treeArr.tree);
});
}

Related

How I can access URL parameters from Azure DevOps extension

how can I access URL parameters from Azure DevOps Extension?
I am developing a hub-like extension based on this example. Basically it is a simple page that displays data in a simple table. Data are loaded from an external REST API server.
I want to call this page from some external link and for this, I need to read URL parameter idBuild from this extension. Is this possible?
Example on my URL: http://server/tfs/org/proj/_apps/hub/devops-plugin.default-hub?idBuild=15987
Edit: More details about this plugin:
For Pull requests, my Pull Request server posts Pull request status with the information about some additional checks (x86 integration tests here).
I want this Status to have a URL, so a user can display some additional information about this status on a separate page. This page is my extension.
In this extension, I read some data from an external API and idBuild is the key. So I want to make URL containing idBuild and pass idBuild to this extension page through this URL.
Some months ago I faced the same problem as you have now.
While using aurelia / typescript I was not able to read the URL parameters, but I found a workaround to retrieve them.
Use the following function to get all the parameters:
function getUrlParameters() {
var parameters = {};
window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, (m, key, value) => {
parameters[key] = value.split("#")[0];
return parameters[key];
});
return parameters;
}
And this piece of code to get the idBuild parameter:
var buildId = getUrlParameters()["idBuild"];
Thanks to R Pelzer answer, here is TypeScript version of his function:
private getUrlParameters(): Map<string, string> {
const parameters: Map<string, string> = new Map<string, string>();
window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, (m, key: string, value: string) => {
const val = value.split("#")[0];
parameters.set(key, val);
return val;
});
return parameters;
}
And here is a usage example:
public async componentDidMount() {
const idBuildParam = this.getUrlParameters().get("idBuild");
if (!idBuildParam)
{
throw RangeError("Missing 'idBuild' URL parameter");
}
const response = await axios.get<PoirotResultDto[]>(`http://localhost:50584/Poirots/${idBuildParam}`);
.... rest of code
}

protractor - testing rest end point

I am trying to invoke rest end point from Protractor E2E tests. I have referred to following site, however this post seems to be based on old API
eg: protractor.promise.defer(); seems no longer valid on latest API.
http://squirrel.pl/blog/2014/01/15/direct-server-http-calls-in-protractor/
Could you please advise/give sample code to invoke rest end point based on latest protractor API (>= 1.3).
I'm trying to write generic function, something like following.
var executeRequest = function(method, url) {
var defer = protractor.promise.defer();
// method can be ‘GET’, ‘POST’ or ‘PUT’
request({uri: url, method: method, json: true}, function(error, response, body) {
if (error || response.statusCode >= 400) {
defer.reject({
error : error,
message : response
});
} else {
defer.fulfill(body);
}
});
// Return a promise so the caller can wait on it for the request to complete
return defer.promise;
};
You could use request-promise instead. Example from their website...
var rp = require('request-promise');
var options = {
uri : 'http://posttestserver.com/post.php',
method : 'POST'
};
rp(options)
.then(console.dir)
.catch(console.error);
I have used npm module - "needle" to invoke restAPI . That has option for redirects, which helped to validate test site even after redirect.
Please find below sample test to validate rest endpoint is up and running.
it("check restendpoint service is running", function(done){
var restendpointUrl = browser.baseUrl + 'service';
needle.get(healthcheckUrl,{follow_max : 5}, function(err,resp) {
expect(resp.statusCode).toBe(200);
if (!err && resp.statusCode == 200) {
expect(true).toBe(true);
} else {
expect(false).toBe(true);
}
done();
});
});
Brine, many thanks for your earlier reply.

Apigee push notification - one

Apigee's push notification is documented here.
http://apigee.com/docs/api-baas/content/introducing-push-notifications
I tried this with the js sdk that Apigee provides here http://apigee.com/docs/app-services/content/installing-apigee-sdk-javascript. It looks like only the client can generate a notification to itself?
But I have a scenario where I would like to push notifications to multiple clients from a nodejs job that runs once every hour. Something like this, but from the nodejs sdk not from the js sdk.
var devicePath = "devices;ql=*/notifications";
How do I do this?
As remus points out above, you can do this with the usergrid module (https://www.npmjs.com/package/usergrid).
You are basically trying to construct an API call that looks like this (sending a message by referencing a device):
https://api.usergrid.com/myorg/myapp/devices/deviceUUID/notifications?access_token= access_token_goes_here '{"payloads":{"androidDev":"Hello World!!"}}'
Or like this (sending a message by referencing a user who is connected to a device)
https://api.usergrid.com/myorg/myapp/users/fred/notifications?access_token=access_token_goes_here '{"payloads":{"androidDev":"Hello World!!"}}'
You can do this with code that looks something like this:
var options = {
method:'POST',
endpoint:'devices/deviceUUID/notifications',
body:{ 'payloads':{'androidDev':'Hello World!!'} }
};
client.request(options, function (err, data) {
if (err) {
//error - POST failed
} else {
//data will contain raw results from API call
//success - POST worked
}
});
or
var options = {
method:'POST',
endpoint:'users/fred/notifications',
body:{ 'payloads':{'androidDev':'Hello World!!'} }
};
client.request(options, function (err, data) {
if (err) {
//error - POST failed
} else {
//data will contain raw results from API call
//success - POST worked
}
});
Note: the second call, that posts to the users/username/notifications endpoint assumes that you have already made a connection between the user and their device (e.g. POST /users/fred/devices/deviceUUID).

hello, is there a way for consuming a Rest service in an app for windows 8.1 using WinJS?

hello I'm trying to consume a REST service in an app for windows 8.1, I'm so gratefull if you can give me more information related about this topic, thanks !!
You could use the XMLHttpRequest object. But, since you are using WinsJS, the WinJS.xhr function would be more convenient.
Here's an example on how to use it:
(function () {
"use strict";
var app = WinJS.Application;
app.onactivated = function (args) {
// Change RSS feed URL as you need to.
var resDiv = document.getElementById("divResult"),
rssURL = "http://blogs.windows.com/windows/b/appbuilder/rss.aspx";
// Call WinJS.xhr to retrieve an XML feed from the Web.
WinJS.xhr({
url: rssURL,
responseType: "document"
}).done(
// When the result has completed, check the status.
function completed(result) {
if (result.status === 200) {
// Get the XML document from the results.
var xmlDocument = result.responseXML,
title = xmlDocument.getElementsByTagName('title')[0];
// Update the HTML in the app.
resDiv.style.backgroundColor = "lightGreen";
resDiv.innerText = "Downloaded RSS feed from the " + title.textContent + " blog.";
}
});
};
app.start();
})();

github api: How to efficiently find the number of commits for a repository?

I want to find the number of commits done to specific github projects, and within them to specific files. I checked the github api docs but only found an API for actually returning all commits. This would be very inefficient since I have to do multiple api calls for paging thru all commits.
Anyone has a better idea?
Update May 2013: see "File CRUD and repository statistics now available in the API"
You now can Get the last year of commit activity data
GET /repos/:owner/:repo/stats/commit_activity
Returns the last year of commit activity grouped by week. The days array is a group of commits per day, starting on Sunday.
Not completely what you are looking for, but closer.
Original answer (April 2010)
No, the current API doesn't support a 'log --all' for listing all commmits from all branches.
The only alternative is presented in "Github API: Retrieve all commits for all branches for a repo", and list through all pages of all commits, branch after branch.
This seems so cumbersome than another alternative would actually to clone the Github repo and apply git commands on that local clone!
(mainly git shortlog)
Note: you can also checkout that python script created by Arcsector.
With GraphQL API v4, you can get total commit count per branch with totalCount for each branch:
{
repository(owner: "google", name: "gson") {
name
refs(first: 100, refPrefix: "refs/heads/") {
edges {
node {
name
target {
... on Commit {
id
history(first: 0) {
totalCount
}
}
}
}
}
}
}
}
Test it in the explorer
0penBrain found a clever way to obtain this information and detailed it in the following Gist : https://gist.github.com/0penBrain/7be59a48aba778c955d992aa69e524c5
Here's the relevant snippet with curl :
curl -I -k "https://api.github.com/repos/:owner/:repo/commits?per_page=1" | sed -n '/^[Ll]ink:/ s/.*"next".*page=\([0-9]*\).*"last".*/\1/p'
The trick is to enable a 1 commit per page pagination, as can be seen in the query-string.
Then the focus must shift from the response JSON body to the HTTP headers where the following entry can be found :
link: <https://api.github.com/repositories/27193779/commits?per_page=1&page=2>; rel="next", <https://api.github.com/repositories/27193779/commits?per_page=1&page=37949>; rel="last"
The sed expression is then in charge of extracting the 37949 number (in this example)
Pure JS Implementation
const base_url = 'https://api.github.com';
function httpGet(theUrl, return_headers) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", theUrl, false); // false for synchronous request
xmlHttp.send(null);
if (return_headers) {
return xmlHttp
}
return xmlHttp.responseText;
}
function get_all_commits_count(owner, repo, sha) {
let first_commit = get_first_commit(owner, repo);
let compare_url = base_url + '/repos/' + owner + '/' + repo + '/compare/' + first_commit + '...' + sha;
let commit_req = httpGet(compare_url);
let commit_count = JSON.parse(commit_req)['total_commits'] + 1;
console.log('Commit Count: ', commit_count);
return commit_count
}
function get_first_commit(owner, repo) {
let url = base_url + '/repos/' + owner + '/' + repo + '/commits';
let req = httpGet(url, true);
let first_commit_hash = '';
if (req.getResponseHeader('Link')) {
let page_url = req.getResponseHeader('Link').split(',')[1].split(';')[0].split('<')[1].split('>')[0];
let req_last_commit = httpGet(page_url);
let first_commit = JSON.parse(req_last_commit);
first_commit_hash = first_commit[first_commit.length - 1]['sha']
} else {
let first_commit = JSON.parse(req.responseText);
first_commit_hash = first_commit[first_commit.length - 1]['sha'];
}
return first_commit_hash;
}
let owner = 'getredash';
let repo = 'redash';
let sha = 'master';
get_all_commits_count(owner, repo, sha);
Credits - https://gist.github.com/yershalom/a7c08f9441d1aadb13777bce4c7cdc3b