git-cat-file
Version:
Pure JavaScript `git cat-file -p` for node.js
80 lines (79 loc) • 2.18 kB
JavaScript
;
/**
* https://github.com/kawanet/git-cat-file
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.Tree = void 0;
const file_mode_1 = require("./file-mode");
class Tree {
constructor(obj, store) {
this.obj = obj;
this.store = store;
if (obj.type !== "tree") {
throw new TypeError(`Invalid tree object: ${obj.oid} (${obj.type})`);
}
}
getId() {
return this.obj.oid;
}
async getEntries() {
return parseTree(this.obj.data);
}
async getEntry(path) {
let tree = this;
if (/\//.test(path)) {
const names = path.split("/");
path = names.pop();
if (!path)
path = names.pop();
tree = await this.getTree(names.join("/"));
}
if (!tree)
return;
const list = await tree.getEntries();
return list.filter(item => item.name === path).shift();
}
async getTree(path) {
let tree = this;
for (const name of path.split("/")) {
if (!name)
continue;
const entry = await tree.getEntry(name);
if (!entry)
return;
const obj = await this.store.getObject(entry.oid);
if (!obj)
return;
tree = new Tree(obj, this.store);
}
return tree;
}
}
exports.Tree = Tree;
function parseTree(data) {
const list = [];
let start = 0;
let end;
const { length } = data;
while (start < length) {
end = findZero(data, start);
const line = data.slice(start, end - 1).toString();
const [modeStr, name] = splitBySpace(line);
const mode = (0, file_mode_1.getFileMode)(modeStr);
start = end + 20;
const oid = data.slice(end, start).toString("hex");
list.push({ mode, name, oid });
}
return list;
}
function findZero(buf, offset) {
offset |= 0;
while (buf[offset++]) {
// nop
}
return offset;
}
function splitBySpace(line) {
const sp = line.indexOf(" ");
return [line.slice(0, sp), line.slice(sp + 1)];
}