git-cat-file
Version:
Pure JavaScript `git cat-file -p` for node.js
86 lines (85 loc) • 3.16 kB
JavaScript
;
/**
* https://github.com/kawanet/git-cat-file
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ObjStore = void 0;
const fs_1 = require("fs");
const cache_1 = require("./cache");
const loose_1 = require("./loose");
const pack_1 = require("./pack");
const ref_1 = require("./ref");
/**
* https://github.com/kawanet/git-cat-file
*/
const isObjectId = (oid) => (oid && /^[0-9a-f]{40}$/i.test(oid));
class ObjStore {
constructor(root) {
this.root = root;
this.pack = {};
/**
* get object with the exact objectId
*/
this.getObject = (0, cache_1.shortCache)(async (object_id) => {
if (!isObjectId(object_id)) {
throw new TypeError(`Invalid object_id: ${object_id}`);
}
// packed object
const list = await this.getPackList() || [];
for (const pack of list) {
const obj = await pack.getObject(object_id, this);
if (obj)
return obj;
}
// loose object
return this.loose.getObject(object_id);
});
/**
* get objectId with a loose objectId
*/
this.findObjectId = (0, cache_1.shortCache)(async (object_id) => {
const index = {};
// packed object
{
const packs = await this.getPackList() || [];
for (const pack of packs) {
const items = await pack.findAll(object_id);
if (!items)
continue;
for (const oid of items) {
index[oid] = 1;
}
}
const matched = Object.keys(index);
// console.warn(`matched: ${matched.length} packed object`);
if (matched.length > 1)
return;
}
// loose object
{
const items = await this.loose.findAll(object_id) || [];
// console.warn(`matched: ${items.length} loose object`);
for (const oid of items) {
index[oid] = 1;
}
}
const matched = Object.keys(index);
if (matched.length === 1)
return matched[0];
});
this.findCommitId = (0, cache_1.shortCache)((commit_id) => this.ref.findCommitId(commit_id, this));
this.getPackList = (0, cache_1.shortCache)(async () => {
const base = `${this.root}/objects/pack/`;
// console.warn(`readdir: ${base}`);
let names = await fs_1.promises.readdir(base).catch(_ => null);
if (!names)
return;
names = names.filter(name => /^pack-.*\.pack$/.test(name));
// console.warn(`found: ${names.length} packs`);
return names.map(name => (this.pack[name] || (this.pack[name] = new pack_1.Pack(base + name))));
});
this.loose = new loose_1.Loose(root);
this.ref = new ref_1.Ref(root);
}
}
exports.ObjStore = ObjStore;