Skip to content

Instantly share code, notes, and snippets.

@chrisdickinson
Last active December 26, 2015 08:59
Show Gist options
  • Save chrisdickinson/7125788 to your computer and use it in GitHub Desktop.
Save chrisdickinson/7125788 to your computer and use it in GitHub Desktop.
examples of how to use my various js-git repos

instructions

make sure to clone this gist! then npm install it then run node example.js

if it doesn't work ping me on twitter (@isntitvacant) or irc (chrisdickinson in #pdxnode on freenode.net)

var load = require('git-fs-repo')
var parse = require('git-parse-human')
var walkRefs = require('git-walk-refs')
var walkTree = require('git-walk-tree')
var through = require('through')
load('.git', function(err, git) {
// find refs named HEAD
console.log(git.refs('HEAD'))
// get the hash!
var hash = git.refs('HEAD')[0].hash
console.log('HEAD is %s', hash)
// find the commit it corresponds to!
// note: find will return an instance
// of whatever git type it finds by the
// name of the provided hash. in this
// case we *know* it'll be a commit,
// but you can also use it to get trees, etc.
git.find(hash, function(err, commit) {
// parse the human author info into
// a more usable object:
var humanInfo = parse(commit.author())
console.log(
'name: ', humanInfo.name, '\n'
, 'time: ', new Date(humanInfo.time + humanInfo.tzoff).toISOString(), '\n'
, 'email: ', humanInfo.email, '\n'
)
// or find the tree that's associated!
git.find(commit.tree(), function(err, tree) {
// each tree has `entries()`, each of which has a unix file mode (`mode`),
// a name (`name`), and a hash that is an `instanceof Buffer`.
tree.entries().forEach(function(entry) {
console.log(
entry.mode.toString(8), '-', entry.name, '-', entry.hash.toString('hex')
)
// and you can use git.find to lookup these entries, too.
// git.find works with buffer hashes as well.
git.find(entry.hash, function(err, tree_or_blob) {
if(tree_or_blob.looseType === 'tree') {
// it's a tree
} else {
// it's a blob, take a look at its data.
console.log(entry.name, tree_or_blob.data().toString())
}
})
})
})
// you can also use git-walk-refs to emit
// commits as a readable stream (like git log might)
walkRefs(git.find, [hash])
.pipe(through(log_commit))
function log_commit(commit) {
console.log('streamed commit!', commit.hash)
}
// or use git-walk-tree to walk the tree of a given commit:
walkTree(git.find, commit)
.pipe(through(log_tree_or_blob))
function log_tree_or_blob(obj) {
console.log('streamed %s!', obj.looseType, obj.hash.toString('hex'))
}
// you can also combine primitives for higher-level operations,
// like getting the contents of a file at a given hash:
// e.g., https://gist.github.com/chrisdickinson/6544035
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment