@graphql-tools/git-loader
Version:
A set of utils for faster development of GraphQL tools
85 lines (84 loc) • 2.42 kB
JavaScript
import { execFile, execFileSync } from 'child_process';
import unixify from 'unixify';
const createLoadError = (error) => new Error('Unable to load file from git: ' + error);
const createShowCommand = ({ ref, path }) => {
return ['show', `${ref}:${path}`];
};
const createTreeError = (error) => new Error('Unable to load the file tree from git: ' + error);
const createTreeCommand = ({ ref }) => {
return ['ls-tree', '-r', '--name-only', ref];
};
/**
* @internal
*/
export function parseGitTreeOutput(stdout) {
// Git always emits LF; do not use os.EOL (CRLF on Windows) or the tree
// collapses to a single unusable entry and micromatch matches nothing.
// Do not trim entries — git pathnames can legally have leading/trailing spaces.
return stdout
.split(/\r?\n/)
.filter(line => line.length > 0)
.map(line => unixify(line));
}
/**
* @internal
*/
export async function readTreeAtRef(ref) {
try {
return await new Promise((resolve, reject) => {
execFile('git', createTreeCommand({ ref }), { encoding: 'utf-8', maxBuffer: 1024 * 1024 * 1024 }, (error, stdout) => {
if (error) {
reject(error);
}
else {
resolve(parseGitTreeOutput(stdout));
}
});
});
}
catch (error) {
throw createTreeError(error);
}
}
/**
* @internal
*/
export function readTreeAtRefSync(ref) {
try {
return parseGitTreeOutput(execFileSync('git', createTreeCommand({ ref }), { encoding: 'utf-8' }));
}
catch (error) {
throw createTreeError(error);
}
}
/**
* @internal
*/
export async function loadFromGit(input) {
try {
return await new Promise((resolve, reject) => {
execFile('git', createShowCommand(input), { encoding: 'utf-8', maxBuffer: 1024 * 1024 * 1024 }, (error, stdout) => {
if (error) {
reject(error);
}
else {
resolve(stdout);
}
});
});
}
catch (error) {
throw createLoadError(error);
}
}
/**
* @internal
*/
export function loadFromGitSync(input) {
try {
return execFileSync('git', createShowCommand(input), { encoding: 'utf-8' });
}
catch (error) {
throw createLoadError(error);
}
}