Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Converted to TypeScript #11

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
typings/
101 changes: 30 additions & 71 deletions examples/readme-caps.js
Original file line number Diff line number Diff line change
@@ -1,78 +1,37 @@
var repo = {};

// This only works for normal repos. Github doesn't allow access to gists as
// far as I can tell.
var githubName = "creationix/js-github";

// Your user can generate these manually at https://github.com/settings/tokens/new
// Or you can use an oauth flow to get a token for the user.
var githubToken = "8fe7e5ad65814ea315daad99b6b65f2fd0e4c5aa";

// Mixin the main library using github to provide the following:
// - repo.loadAs(type, hash) => value
// - repo.saveAs(type, value) => hash
// - repo.readRef(ref) => hash
// - repo.updateRef(ref, hash) => hash
// - repo.createTree(entries) => hash
// - repo.hasHash(hash) => has
let repo = {};
const githubName = "creationix/js-github";
const githubToken = "8fe7e5ad65814ea315daad99b6b65f2fd0e4c5aa";
require('../mixins/github-db')(repo, githubName, githubToken);


// Github has this built-in, but it's currently very buggy so we replace with
// the manual implementation in js-git.
require('js-git/mixins/create-tree')(repo);

// Cache everything except blobs over 100 bytes in memory.
// This makes path-to-hash lookup a sync operation in most cases.
require('js-git/mixins/mem-cache')(repo);

// Combine concurrent read requests for the same hash
require('js-git/mixins/read-combiner')(repo);

// Add in value formatting niceties. Also adds text and array types.
require('js-git/mixins/formats')(repo);

// I'm using generator syntax, but callback style also works.
// See js-git main docs for more details.
var run = require('gen-run');
let run = require('gen-run');
run(function* () {
var headHash = yield repo.readRef("refs/heads/master");
var commit = yield repo.loadAs("commit", headHash);
var tree = yield repo.loadAs("tree", commit.tree);
var entry = tree["README.md"];
var readme = yield repo.loadAs("text", entry.hash);

// Build the updates array
var updates = [
{
path: "README.md", // Update the existing entry
mode: entry.mode, // Preserve the mode (it might have been executible)
content: readme.toUpperCase() // Write the new content
}
];
// Based on the existing tree, we only want to update, not replace.
updates.base = commit.tree;

// Create the new file and the updated tree.
var treeHash = yield repo.createTree(updates);

var commitHash = yield repo.saveAs("commit", {
tree: treeHash,
author: {
name: "Tim Caswell",
email: "[email protected]"
},
parent: headHash,
message: "Change README.md to be all uppercase using js-github"
});

// Now we can browse to this commit by hash, but it's still not in master.
// We need to update the ref to point to this new commit.
console.log("COMMIT", commitHash)

// Save it to a new branch (Or update existing one)
var new_hash = yield repo.updateRef("refs/heads/new-branch", commitHash);

// And delete this new branch:
yield repo.deleteRef("refs/heads/new-branch");
const headHash = yield repo.readRef("refs/heads/master");
const commit = yield repo.loadAs("commit", headHash);
const tree = yield repo.loadAs("tree", commit.tree);
const entry = tree["README.md"];
const readme = yield repo.loadAs("text", entry.hash);
let updates = [
{
path: "README.md",
mode: entry.mode,
content: readme.toUpperCase()
}
];
updates.base = commit.tree;
const treeHash = yield repo.createTree(updates);
const commitHash = yield repo.saveAs("commit", {
tree: treeHash,
author: {
name: "Tim Caswell",
email: "[email protected]"
},
parent: headHash,
message: "Change README.md to be all uppercase using js-github"
});
console.log("COMMIT", commitHash);
const new_hash = yield repo.updateRef("refs/heads/new-branch", commitHash);
yield repo.deleteRef("refs/heads/new-branch");
});
78 changes: 78 additions & 0 deletions examples/readme-caps.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
let repo: any = {};

// This only works for normal repos. Github doesn't allow access to gists as
// far as I can tell.
const githubName = "creationix/js-github";

// Your user can generate these manually at https://github.com/settings/tokens/new
// Or you can use an oauth flow to get a token for the user.
const githubToken = "8fe7e5ad65814ea315daad99b6b65f2fd0e4c5aa";

// Mixin the main library using github to provide the following:
// - repo.loadAs(type, hash) => value
// - repo.saveAs(type, value) => hash
// - repo.readRef(ref) => hash
// - repo.updateRef(ref, hash) => hash
// - repo.createTree(entries) => hash
// - repo.hasHash(hash) => has
require('../mixins/github-db')(repo, githubName, githubToken);


// Github has this built-in, but it's currently very buggy so we replace with
// the manual implementation in js-git.
require('js-git/mixins/create-tree')(repo);

// Cache everything except blobs over 100 bytes in memory.
// This makes path-to-hash lookup a sync operation in most cases.
require('js-git/mixins/mem-cache')(repo);

// Combine concurrent read requests for the same hash
require('js-git/mixins/read-combiner')(repo);

// Add in value formatting niceties. Also adds text and array types.
require('js-git/mixins/formats')(repo);

// I'm using generator syntax, but callback style also works.
// See js-git main docs for more details.
let run = require('gen-run');
run(function* () {
const headHash = yield repo.readRef("refs/heads/master");
const commit = yield repo.loadAs("commit", headHash);
const tree = yield repo.loadAs("tree", commit.tree);
const entry = tree["README.md"];
const readme = yield repo.loadAs("text", entry.hash);

// Build the updates array
let updates: any = [
{
path: "README.md", // Update the existing entry
mode: entry.mode, // Preserve the mode (it might have been executible)
content: readme.toUpperCase() // Write the new content
}
];
// Based on the existing tree, we only want to update, not replace.
updates.base = commit.tree;

// Create the new file and the updated tree.
const treeHash = yield repo.createTree(updates);

const commitHash = yield repo.saveAs("commit", {
tree: treeHash,
author: {
name: "Tim Caswell",
email: "[email protected]"
},
parent: headHash,
message: "Change README.md to be all uppercase using js-github"
});

// Now we can browse to this commit by hash, but it's still not in master.
// We need to update the ref to point to this new commit.
console.log("COMMIT", commitHash)

// Save it to a new branch (Or update existing one)
const new_hash = yield repo.updateRef("refs/heads/new-branch", commitHash);

// And delete this new branch:
yield repo.deleteRef("refs/heads/new-branch");
});
158 changes: 80 additions & 78 deletions lib/xhr-node.js
Original file line number Diff line number Diff line change
@@ -1,81 +1,83 @@
var https = require('https');
var statusCodes = require('http').STATUS_CODES;
var urlParse = require('url').parse;
var path = require('path');

module.exports = function (root, accessToken, githubHostname) {
var cache = {};
githubHostname = (githubHostname || "https://api.github.com/");
return function request(method, url, body, callback) {
if (typeof body === "function" && callback === undefined) {
callback = body;
body = undefined;
}
if (!callback) return request.bind(this, accessToken, method, url, body);
url = url.replace(":root", root);

var json;
var headers = {
"User-Agent": "node.js"
};
if (accessToken) {
headers["Authorization"] = "token " + accessToken;
}
if (body) {
headers["Content-Type"] = "application/json";
try { json = new Buffer(JSON.stringify(body)); }
catch (err) { return callback(err); }
headers["Content-Length"] = json.length;
}
if (method === "GET") {
var cached = cache[url];
if (cached) {
headers["If-None-Match"] = cached.etag;
}
}

var urlparts = urlParse(githubHostname);
var options = {
hostname: urlparts.hostname,
path: path.join(urlparts.pathname, url),
method: method,
headers: headers
};

var req = https.request(options, function (res) {
var body = [];
res.on("data", function (chunk) {
body.push(chunk);
});
res.on("end", function () {
body = Buffer.concat(body).toString();
console.log(method, url, res.statusCode);
console.log("Rate limit %s/%s left", res.headers['x-ratelimit-remaining'], res.headers['x-ratelimit-limit']);
//console.log(body);
if (res.statusCode === 200 && method === "GET" && /\/refs\//.test(url)) {
cache[url] = {
body: body,
etag: res.headers.etag
};
let https = require('https');
let statusCodes = require('http').STATUS_CODES;
let urlParse = require('url').parse;
let path = require('path');
export function xhrNode(root, accessToken, githubHostname) {
let cache = {};
githubHostname = githubHostname || "https://api.github.com/";
return function request(method, url, body, callback) {
if (typeof body === "function" && callback === undefined) {
callback = body;
body = undefined;
}
else if (res.statusCode === 304) {
body = cache[url].body;
res.statusCode = 200;
}
// Fake parts of the xhr object using node APIs
var xhr = {
status: res.statusCode,
statusText: res.statusCode + " " + statusCodes[res.statusCode]
if (!callback)
return request.bind(this, accessToken, method, url, body);
url = url.replace(":root", root);
let json;
let headers = {
"User-Agent": "node.js"
};
var response = {message:body};
if (body){
try { response = JSON.parse(body); }
catch (err) {}
if (accessToken) {
headers["Authorization"] = "token " + accessToken;
}
if (body) {
headers["Content-Type"] = "application/json";
try {
json = new Buffer(JSON.stringify(body));
}
catch (err) {
return callback(err);
}
headers["Content-Length"] = json.length;
}
return callback(null, xhr, response);
});
});
req.end(json);
req.on("error", callback);
};
};
if (method === "GET") {
let cached = cache[url];
if (cached) {
headers["If-None-Match"] = cached.etag;
}
}
let urlparts = urlParse(githubHostname);
let options = {
hostname: urlparts.hostname,
path: path.join(urlparts.pathname, url),
method: method,
headers: headers
};
let req = https.request(options, function (res) {
let body = [];
res.on("data", function (chunk) {
body.push(chunk);
});
res.on("end", function () {
body = Buffer.concat(body).toString();
console.log(method, url, res.statusCode);
console.log("Rate limit %s/%s left", res.headers['x-ratelimit-remaining'], res.headers['x-ratelimit-limit']);
if (res.statusCode === 200 && method === "GET" && /\/refs\//.test(url)) {
cache[url] = {
body: body,
etag: res.headers.etag
};
}
else if (res.statusCode === 304) {
body = cache[url].body;
res.statusCode = 200;
}
let xhr = {
status: res.statusCode,
statusText: res.statusCode + " " + statusCodes[res.statusCode]
};
let response = { message: body };
if (body) {
try {
response = JSON.parse(body);
}
catch (err) { }
}
return callback(null, xhr, response);
});
});
req.end(json);
req.on("error", callback);
};
}
;
Loading