diff --git a/src/pointers.ts b/src/pointers.ts index b07c8d0..95bde23 100644 --- a/src/pointers.ts +++ b/src/pointers.ts @@ -1,4 +1,8 @@ import path from 'path'; +import { toHex } from './util'; + + +const SPEC_URL = 'https://git-lfs.github.com/spec/v1'; export interface PointerInfo { @@ -58,3 +62,21 @@ export function readPointer({ dir, gitdir = path.join(dir, '.git'), content }: P return { info, objectPath }; } + + +/** Formats given PointerInfo for writing in Git tree. */ +export function formatPointerInfo(info: PointerInfo): Buffer { + const lines = [ + `version ${SPEC_URL}`, + `oid sha256:${info.oid}`, + `size ${info.size}`, + ]; + return Buffer.from(lines.join('\n')); +} + + +export async function buildPointerInfo(content: Buffer): Promise { + const size = Buffer.byteLength(content); + const hash = await crypto.subtle.digest('SHA-1', content); + return { oid: toHex(hash), size }; +} diff --git a/src/util.ts b/src/util.ts index 7bf89a5..2e6a7ba 100644 --- a/src/util.ts +++ b/src/util.ts @@ -74,3 +74,14 @@ export async function bodyToBuffer(body: Uint8Array[]): Promise { } return Buffer.from(result.buffer); } + + +// Borrowed from Isomorphic Git core, it is not importable. +export function toHex(buffer: ArrayBuffer): string { + let hex = '' + for (const byte of new Uint8Array(buffer)) { + if (byte < 16) hex += '0' + hex += byte.toString(16) + } + return hex +}